2-D Array in C storing user inputs - c

total C newbie here. Thanks for any help beforehand.
I am required to write a code which has the following properties:
Asking user to input the number of rows and columns they would like in their 2-D array
creates a 2-D array with that many rows and columns for storing integers
fills the array with random numbers between 1 and 1000
outputs the largest number in the array
This is where I could go for now:
#include <stdio.h>
int main(){
int rows;
int columns;
scanf("%d", &rows);
scanf("%d", &columns);
}
What should I do?
Sorry for the very open question, I am stuck and don't know what to do. A guideline will be perfect. Thanks :)
EDIT:
Thanks for the guideline, here is how I solved it:
SOLUTION:
#include <stdio.h>
#include <time.h>
int main () {
//Declare variables
int a,b,k,l,big,z[100][100];
//Ask user input
printf("ENTER ROWS & COLUMNS\n");
scanf("%d\n%d", &a, &b);
//Randomize array values
srand(time(NULL));
big = 1;
for (k=0;k<a;k++){
for(l=0;l<b;l++){
z[k][l]=rand()%1000 + 1;
if(z[k][l]>big) big=z[k][l];
printf("%d\t", z[k][l]);
}
printf("\n");
}
//Print biggest number
printf("\nBIGGEST NUMBER IN THE ARRAY: %d", big);
return 0;
}

A guideline will be perfect.
okay... let's go...
Asking user to input the number of rows and columns they would like in their 2-D array
Use scanf or better fgets followed by sscanf
creates a 2-D array with that many rows and columns for storing integers
Use malloc (search the net for "how to correctly malloc a 2D array" or simply see Correctly allocating multi-dimensional arrays)
fills the array with random numbers between 1 and 1000
Use srand, rand and the % operator
outputs the largest number in the array
Iterate all elements of the array and compare against a running max.

C does not support natively 2D arrays, you need to allocate an array of arrays. You don't know the size in advance, so you need to allocate the arrays memory dynamically using malloc.
For generating random numbers, you could use rand, but you need to set a seed first for the sequence of the pseudo-random integers using srand to get (possibly) a different number on every execution, or you can use rand_r to do the both operation with one function. Note that rand generate a random number between 0 and RAND_MAX, you need to use a trick with the modulus operator % to generate a random number in a specific range [min, max].
min + (rand() % (max - min + 1))
You can iterate over the arrays with two loops, to get the maximum number.
To know how to use these function, you can read the man pages: malloc rand
As a side note, you don't really need the 2D array to get the maximum number, you can calculate it directly with allocating any additional memory.
Your solution will work, but it's limited to 100 columns and 100 rows. If for instance the user enters higher numbers, your code will mostly crash. One solution is to validate the input and refuse numbers above 100 if you don't want to handle dynamic memory allocation, but in real world that is very much rare and dynamic memory allocation is a necessary.
You shouldn't name your variables with one-character names, especially if they live long. A good descriptive name like columnsNumber is preferred.

Related

Size of Array not showing the expectation

The goal is to get the number of even arrays and that of the odd arrays.
The output should be approximately 50% each, I have tried:
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int arr[10]={0}, random_number, i, odd_saver[]={0}, even_saver[]={0};
srand( time( NULL ) );
for (i=0; i<10000; i++){
random_number= (10*rand())/(RAND_MAX+1);
arr[random_number]+=1;
if (arr[random_number]%2==0){
even_saver[random_number]+=1;
}else{
odd_saver[random_number]+=1;
}
}
printf("\n");
size_t even_size = sizeof(even_saver[random_number]) / sizeof(even_saver[0]);
size_t odd_size = sizeof(odd_saver[random_number]) / sizeof(odd_saver[0]);
printf("%d %.2f%%\n", (int)even_size, (double)(even_size*100)/10000);
printf("%d %.2f%%\n", (int)odd_size, (double)(odd_size*100)/10000);
return 0;
}
but the output is not according to my expectation.
I need help, and more explanation about what I am doing wrong will be highly appreciated.
The output:
1 0.01%
1 0.01%
As H.R. Emon has implied, in C you cannot create odd_saver[]={0}, even_saver[]={0}; as arrays of size 1 and later try to increase their size by adding to them.
You aim to calculate your indexes for accessing all arrays in your code to be 0..9, which matches the array arr of size 10. (Though the method of calculating random numbers could be discussed...)
With that assumption, you can create all of your arrays the same way:
int arr[10]={0}, random_number, i, odd_saver[10]={0}, even_saver[10]={0};
I think your goal is to output the number of different even and different odd numbers (i.e. not counting multiple occurences of the same).
For that you cannot use the size of the even/odd arrays. For one because in C there are no dynamically growing arrays (as H.R. Emon has pointed out). But also because once you have an 8 or 9 occurring, incrementing that index in the arrays would (if such arrays would exist in C) falsely get you too high a size.
You will simply have to count the non-zeros in your even/odd arrays.
(By the way, it should be possible to use even/odd arrays of half the size, by dividing the index by 2 and using appropriate offsets.)
i am afraid you are trying to do things that c doesn't allow you to do. you are trying to invoke dynamic array in c. but c don't support dynamic array. so it will lead to you undefined behavior. if you need dynamic allocation you can use vector std::vector it's a stl function which helps you to use to allocate memory dynamically.
vector details

Calculate the frequency of each number as each number is generated using the arrays and print the number

Write a C program using the arrays to eliminate the duplicate numbers. Generate 50 random
numbers between 50 and 150 using rand function. Insert the random numbers to the array with
a size 50. As each number is generated, print it only if it’s not a duplicate of a number already
generated. Provide for the “worst-case” in which all 50 numbers are different.
This how I would approach it:
The easier way for me is to have a frequency table (an array of size 151), since you are dealing with a short range of numbers.
Initialize the array with 0's (Could use memset() here).
Get a random number within your range (lets say n)
Check that array[n] is 0.
If it is, print the number and increment the array by one (array[n]++)
If not, print an error
Repeat until you've read 50 numbers

dynamic memory allocation and dynamic array

I need to write a program, that will ask a user to enter a number of how many ints they would like to enter.. so the output would look like
Enter number of Ints (must be greater then 1)
and they would input a number between 2 - infinity (if they really wanted to go that far)
at that point i would scanf that number and set it to a variable
now with that number, i want to run a for loop to ask them to begin entering their Ints
for (count = 0; count < numofInts; count++)
{
printf(" Enter an integer: ");
scanf("%d", &Number);
}
the problem im having is that i need to make sure that it records every number that they enter, so i need to have those values stored to an array, but the number of elements of the array must be dynamic so that it can change depending on the numofInts, I'm supposed to use Malloc() to create a dynamic memory allocated space, and i understand that it creates a variable with a memory space of what ever i set the malloc to, but i don't know how to store a series a variables to that space, and then call them back as i need them.
The end result of the program is supposed to take a number like 123456789, and cycle through the number storing the intergers as the "largest" int, and then spit out which int is the largest, so like x = 1234567890, x % 10, x = 0, largest = x, x / 10, x % 10, x = 9, if x > largest, largest = x, and just loop that till it cycles through the whole number, and store that number at the very end. I have that part down, but because i have to take a series of numbers and run this loop for all of those numbers, i need to be able to store and recall those values and place them in the loop to be able to store the largest digits of those numbers
any help with this problem would be greatly appreciated, i just have not been able to figure out how to use malloc or to create a dynamic array and most of the tutorials ive read online or watched from youtube are about C++ and i need to do this with just C...
http://pastebin.com/PZyvEQ4J
what i have so far
After you read numInts, you allocate the array like so:
int* arr = malloc(numInts*sizeof(int));
Now you populate the array with your already existing function and assigning the values read to the array.
I'm not going to give you a full solution, since this is homework and wouldn't help you, but you access the i'th element of the array with the [] operator:
arr[i];
Learn more about pointers and calloc

C Programming : Sum of third upper anti-diagonal a squared matrix , help badly needed please

im doing a short course in c programming and i have been so busy lately with my other classes and and helping my bother prepare for his wedding (as im his best man)that I have fallen behind and need help. any help towards this short assignment would be much appreciated as im not familiar at all with matrixs and its due in a few days.
the assignment is to Sum of third upper anti-diagonal a squared matrix .
i have been given this information:
The matrix should be a square, integer matrix of size N. In this assignment the matrix will be stored
in a 1d block of memory. You will have to convert between the conceptual 2d matrix addressing and
1d block addressing with pointer arithmetic.
Note on random numbers:
rand() function returns the next integer a sequence of pseudo-random integers in the range
[0, RAND_MAX]. RAND_MAX is a very large number and varies from system to system. To get an
integer in the range [min, max]:
(int)((min)+rand()/(RAND_MAX+1.0) * ((max)-(min)+1))
srand(SEED) is used to set the seed for rand. If srand() is called with the same seed value, the
sequence of pseudo-random numbers is repeated. To get different random numbers each time a
programme runs use time(NULL) as the seed. Rand is in stdlib.h, which needs to be included.
The program should be structured as follows.
#define N 32 // Matrix size
#define MYSEED 1234 // Last 4 digits of your student number.
int *initialise( ) // Allocate memory for the matrix using malloc
// Initialise the matrix with random integers x, 1≤ x ≤ 9
// Use 'MYSEED' as the seed in the random generator.
// Return a pointer to the matrix
void print_matrix(int *) // Print matrix on screen
int compute_diagonal(int *) // Compute your required calculation using pointer arithmetic.
// (square bracket [ ] array indexes shouldn't be used)
// Return the solution.
void finalise(int *) //free the allocated memory.
int main() // The main function should print the solution to screen.
Without doing your homework assignment for you, here's a tip:
Make a functions that abstract storing and retrieving values out of the matrix. One of the signatures should look a lot like this:
int retrieve(int* matrix, int row, int col);
Ok since this is homework and you still have a few days I will not give you an exact answer here. But I will give you some thoughts with which it should be pretty easy to come to your answer.
Indexing a matrix 1D-way: You are not allowed to use matrix[x][y] here, but only a one-dimensional array. So just take a minute and think of how the index (x,y) can be computed within a 1D array. Keep in mind that C stores elements rowwise (i.e. the elements matrix[0][0], matrix[0][1], matrix[0][2] refer to matrix[0], matrix[1], matrix[2]). It is a simply forumla in terms of X, Y and N
Filling the matrix randomly is easy, the function to create a random int is already given, just walk the matrix along and fill every element
Adding the third anti-upper diagonal. This isn really a programming question. Just sketch a small matrix on a piece of paper and see what elements you have to add. Look at their indices and than combine your newly gained knowledge with your result from my point 1 and you will know what to add up
Edit: Since you are not allowed to use the bracket operator, keep in mind that matrix[5] is the same as *(matrix+5).
I think it's fair to tell you this ;)

Escaping loop whilst adding to dynamic array - C

Currently my program allows the user to enter 5 integers which are used to create an average number. This is set to five as after the fifth number is entered the loop is broken.
I am trying to implement a method which will let the user continue to add as many numbers as they like to an array from which i can then use to create an average without a limit on the amount of numbers that can be entered.
I have come across a few problems, firstly i cannot create an array which is dyamic as i have no idea how many numbers the user may wish to enter which means i can't give it a definitive size.
Secondly the way my program currently creates the average is by looping through the elements in the array and adding the consecutively to an integer, from which the the average is made. I cannot specify the limit for the loop to continue running if i cannot determine the array.
Hopefully my example explains this better.
#include <stdio.h>
#include <string.h>
void main()
{
int i = 0;
int arrayNum[5];
int temp = 1;
int anotherTemp = 0;
int answer = 0;
printf("Enter as many numbers as you like, when finished enter a negative number\n");
for(i = 0; i < 5; i++)
{
scanf("%d", &temp);
arrayNum[i] = temp;
anotherTemp = anotherTemp + arrayNum[i];
}
answer = anotherTemp / 5;
printf("Average of %d,%d,%d,%d,%d = %d",arrayNum[0],arrayNum[1],arrayNum[2],arrayNum[3],arrayNum[4],answer);
}
Although this may not be the best way to implement it, it does work when the amount of numbers are specified beforehand.
What would be the best way to get around this and allow the user to enter as many number as necessary?
Edit: Although i needed to use an array I have decided that it is not necessary as the solution is much simpler without being restricted to it.
In terms of code simplicity, you might want to check out the realloc() function; you can allocate an initial array of some size, and if the user enters too many numbers call realloc() to get yourself a bigger array and continue from there.
You don't, however, actually need to keep the numbers as you go along at all, at least if you only care about the average:
int input;
int sum = 0;
int count = 0;
int average;
while (1) {
scanf("%d", &input);
if (input < 0) {
break;
}
sum += input;
count++;
}
average = sum / count;
If you're trying to compute an average, then you don't need to save the numbers. Save yourself the work of worrying about the array. Simply accumulate (add) each number to a single total, count each number, then divide when you're done. Two variables are all that you need.
With this method, you aren't in any risk of overflowing your array, so you can use a while loop... while (temp != -1)
Basically you start with a dynamically allocated array with a fixed size, and then allocate a new array that is bigger (say, twice as big as initial size) and copy the stuff from the old array to the new one whenever you run out of space.
For the second part of the problem, keep a counter of the number of items the user entered and use it when averaging.
Something like this.
Use a dynamic array data structure, like Vector in Java (java.util.Vector).
You can implement such a dynamic array yourself easily:
allocate array of size N
as soon as you need more elements than N, allocate a new bigger array (e.g. with size N+10), copy the content of the old array into the new array and set your working reference to the new array and your array size variable N to the new size (e.g. N+10). Free the old array.

Resources