Scramble numbers from array with numbers - C - c

I have been figuring out how to scramble numbers from array after user enters 10 different numbers by using rand(). It crushes when it arrives to adjust() function so feel free to point out my stupid mistake. Cheers. The top part is function, the bottom part is in main().
void adjust(int z[], int size)
{
int i, n, t;
for(i = 0; i < size; i++)
{
size = rand();
t = z[size];
z[size] = z[i];
z[i] = t;
}
printf("\nYour numbers have been scrambled and here they are: \n", t);
}
.....................
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = num; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
addNum(z, 10);
adjust(z, 10);
return 0;

The rand() function returns a number between 0 and RAND_MAX.
Hence, the array index can go well beyond its range.
To get a random index within a range from 0 to N -1 , use rand() % N.
Another issue is that in your for loop, in adjust function, you are destroying the original value of 'size'. That contains the length of your array and is used to check the terminating condition of your for loop. Hence, do not modify 'size'. Use another variable to store your random index.
for(i = 0; i < size; i++)
{
n = rand() % size; // n is between 0 and size-1
t = z[n];
z[n] = z[i];
z[i] = t;
}
// For a better design move the following lines to a separate function
// that way adjust function just does the scrambling while another
// printing function prints out the array. Each function does only one thing.
printf("\nYour numbers have been scrambled and here they are: \n");
for( i = 0; i < size; i++)
{
printf("%d ", z[i]);
}

Related

How to make use of an array returned by a function? in C language

My general goal with this question is to understand how to make use (say, print) of an array returned from an outer function. I'm using prime numbers as an example.
I'm new so going in-depth explaining... Sorry if there's un-needed info or misused terms :)
I defined a function "findprimes" to find every prime between 1 and x.
The function successfully prints an array of primes. However, I don't know if it returns the array of primes. And, if it does, I have no idea how to use said array in main().
This is the function 'findprimes':
int* findprimes(int x) {
int i, j, total=0;
int* numbers = (int*)malloc((x + 1) * sizeof(int));
/* initialization */
for (i = 0; i <= x + 1; i++) {
numbers[i] = 1;
}
/* find primes and assign prime=1 */
for (i = 2; i < sqrt(x); i++) {
if (numbers[i] == 1) {
for (j = i * i; j <= x; j = j + 2) {
if (j % i == 0) {
numbers[j] = 0;
}
}
}
}
/* count how many primes */
for (i = 1; i <= x; i++) {
if (numbers[i] == 1) {
total++;
}
}
/* put primes into their own array */
int* primes = (int*)malloc(total * sizeof(int));
for (i = 1,j=0; i <= x; i++) {
if (numbers[i] == 1) {
primes[j] = i;
j++;
}
}
//I want this part to be in main()
printf("The prime numbers between 1 and %d are: ", x);
for (i = 0; i < total; i++) {
printf("%d ", primes[i]);
}
return primes;
}
I want to print the 'primes' array in main, not in the function 'findprimes' itself. How can I do this?
int main() {
int n;
do {
printf("Enter a value for X>2: ");
scanf("%d", &n);
} while (n <= 2);
findprimes(n); //This returns 'primes' array
//I want to print 'primes' array here
}
Capture the return value in main():
int *primes = findprimes(n);
and use the array:
for (int i = 0; i < some_magic_number; i++)
{
printf("%d\n", primes[i]);
}
and remember to free the memory:
free(primes);
In fact, you also need to free numbers in the function.
The some_magic_number needs to be known — how does the main() function know how many elements are in the array? One way to fix that is to pass a pointer to the function that can hold the number of primes:
int *findprimes(int n, int *num_primes)
and use *num_primes = total; in the function before returning.
You could call the function with:
int some_magic_number;
int *primes = findprimes(n, &some_magic_number);
You'd probably choose an alternative name for the variable in main(), but it illustrates my point.

Problem with frequency analysis of user input array in C

I'm supposed to do a freqency analysis of a user input array. User may enter as many numbers between 0-1000 as s/he wants and a maximum of 100 numbers can be entered, user ends input by entering a negative number. A void function will calculate which number appears the most times and those 2 variables should be sent to the function as pointers.
My problem is that no matter what I do the analysis seems to calculate all the "empty" elements of the array and I can't figure out what I'm doing wrong. If i make the array smaller to lets say 10 elements it works fine. As I'm a complete novice when it comes to programming and I've changed the code about a million times so at this point I can't remeber what I've changed from my original code. When debugging I get stuck in the second for loop in the function..
#include <stdio.h>
#define MAX 100
#define INTERVAL 1000
void frequencyAnalysis(int array[],int *number, int *freq)
{
int element = 0, count = 0;
for (int i = 0; i < MAX; i++) {
int tempElement = array[i];
int tempCount = 0;
for (int j = 0; j < MAX; j++)
if (array[j] == tempElement)
tempCount++;
if (tempCount > count) {
element = tempElement;
count = tempCount;
}
}
*number = element;
*freq = count;
}
int main(void)
{
int array[MAX], i, j, number = 0, freq = 0;
printf("Hello.\n"
"Please enter a number between 0-1000. "
"Enter as many number as you want (maximum 100).\n"
"Exit by entering a negative number.\n\n");
printf("Enter a number:\n");
for (i = 0; i < MAX; i++) {
scanf("%d", &array[i]);
if (array[i] < 0)
break;
}
frequencyAnalysis(array, &number, &freq);
printf("The number:%d is the most frequent number and appears %d times.\n", number, freq);
return 0;
}
Addressing the first issue, pass in how many items the user actually entered so you're not running up to MAX (which would include all the unused cells). The key is nitems.
void frequencyAnalysis(int array[], int nitems, int *number, int *freq)
{
for (int i = 0; i < nitems; i++) {
...
for (int j = 0; j < nitems; j++)
{
// do stuff
}
}
}
int main(void)
{
int array[MAX],i, j, number = 0, freq = 0;
...
frequencyAnalysis(array, i, &number,&freq);
///
}

Input to Multi-Array in C

I am trying to assign user input into an array; however, the program below only picks up on the first element in each line of input. The ultimate goal of this program is to find the diagonal sums of integers and return the absolute value of their difference.
Example input (note that the first number gives the number of rows and columns (square array):
Input:
3
11 2 4
4 5 6
10 8 -12
Output:
Expected = 15
Actual = 10
I realize that the issue lies in the way that the array is setup. If I print the array out I get: 111555999
Any hints/help would be very appreciated.
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%i", &n); //N = number of rows and number of columns (square 2D array)
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d ", &multi_array[c][i]); //enter integers to store in array
}
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i]; //add up top left to bottom right diagonal
}
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
printf("%i", abs(sum1 - sum2)); //print absolute value of the difference between diagonals
return 0;
}
Your major problem is here, where you go out of bounds:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i]; // when i is 0, th
}
When i = 0, you are accessing multi_array[0][3], which is out of bounds when N = 3.
So change it to this:
multi_array[i][n - i - 1]
You should read your array like this:
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf(" %d ", &multi_array[i][c]);
}
}
since C stored its arrays in row-major order. What you have stores the array in column-major order. It's not wrong, but it's something you do only if you really have to.
Finally, change again the input part of your code to this:
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
so that you have to input exactly what you need to. With your initial code I have to type an extra random number when I had completed the input process.
Last but not least, I am posting the whole code, where I have wrote some extra printf()'s, which are actually for the programmer, so that he can see step-by-step if his code is acting as expected or not.
#include <stdio.h>
#include <stdlib.h> /* abs */
int main() {
int n, i, c, multi_array[200][200], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
scanf("%d", &multi_array[i][c]);
}
}
for (i = 0; i < n; i++) {
for (c = 0; c < n; c++) {
printf("|%d|", multi_array[i][c]);
}
printf("\n");
}
for (i = 0; i != n; i++) {
sum1 += multi_array[i][i];
}
printf("sum1 is %d\n", sum1);
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n - i - 1];
}
printf("sum2 is %d\n", sum2);
printf("%i", abs(sum1 - sum2));
return 0;
}
Output:
3
11 2 4
4 5 6
10 8 -12
|11||2||4|
|4||5||6|
|10||8||-12|
sum1 is 4
sum2 is 19
15
You are clearly going out of bounds here:
for (i = 0; i != n; i++) {
sum2 += multi_array[i][n-i]; //add up top right to bottom left diagonal
}
When i is equal to 0 the expression n-i will be equal to n, but the range of the array is from 0 to n-1. The code will read uninitialized values and cause undefined behavior.
The second array index should be 1 less.

Find the sum of numbers in an array C

I have researched for over an hour on this topic and I had no luck so I decided to go ahead and ask this question here. I have been figuring out how find the sum of 10 different numbers from the array after I type numbers on program. For example, it asks you to type 10 different numbers and they would be all added up after they are typed out in an array. Here is the code. The top part is function. The bottom part is from main(). Any helps would be heavily appreciated.
void addNum(int z[])
{
int sum = 0;
int i;
//scanf("%d", &z[i]);
sum = sum + z[i];
printf("\nThe sum of numbers you entered is %d.\n", sum);
}
...........
int z[10];
int i;
int num = 0;
printf("Please enter 10 different numbers: \n");
for(i = 0; i < 10; i++)
{
z[i] = num;
scanf("%d", &num);
}
printf("\nThe numbers you entered were: ");
for (i = 1; i <= 10; i++)
{
printf("%d ", z[i]);
}
printf("\n");
//scanf("%d", z[i]);
addNum(z[i]);
You should do the adding in your function
void addNum(int z[], int sizeOfArray)
{
int sum = 0;
//scanf("%d", &z[i]);
for(int i = 0; i < sizeOfArray; i++){
sum += z[i];
}
printf("\nThe sum of numbers you entered is %d.\n", sum);
}
Pass in the array in the main with the array size
addNum(z,10);
In your code use pass by reference and not pass by value.
When you call "addNum(z[i])" , i is 11 and what you are passing is z[11] which will be garbage at first place but you are passing only value of one variable which is not what you wanted.
What you want to pass is the address of the array either "z" or "&z[0]" . Along with the size of array, so the function knows how many member variables in array.

Most frequent element in a sequence using arrays in C

I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.

Resources