how to get multiple number from one line in C? [duplicate] - c

This question already has answers here:
Accepting any number of inputs from scanf function
(6 answers)
Closed 5 years ago.
If I want to get input 3 numbers, I can write code like this:
scanf("%d %d %d", &a, &b, &c);
but how can I dynamically get the number of inputs from one line?
For example, if user enters N(number), then I have to get N integer number inputs from one line like above.
The input and output should be :
how many do you want to enter: 5
1 2 3 4 5
sum: 15

Since scanf returns the amount of variables filled you can loop until scanf has no more value to read or the count is matched:
int count = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int val = 0;
int sum = 0;
int i = 0;
while(scanf("%d ", &val) == 1 && i++ < count)
sum += val;

As you don't know the size of inputs previously it's better to create a dynamic array based on the input size provided by the user. Input the size of the array and create an array of that size. Then you can easily loop through the array and do whatever you want with it.
int count = 0, sum = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int *num = malloc(sizeof(int)*count);
for(int i = 0; i < count; i++) {
scanf("%d ", &num[i]);
//sum += num[i];
}

Related

How do I take a user input in the form of a matrix in C?

I am trying to code a program that asks the user for the # of rows and columns and generates a 2d array (a matrix) corresponding to their input. I then ask for a second matrix (same dimensions), then I do some math on the 2 matrices. I'm stuck on how to use the scanf function to get the user-inputted matrix. According to the guidelines, the user input will be in the shape of the matrix itself, ex if it is a 2x2 matrix the user enters:
12 10 (then on the next line)
10 10
How do I use the scanf function appropriately to copy this matrix into the 2d array that I've created? I know that you can do scanf("%d %d %d", &int1, &int2, &int3), but I don't know if this will work for a user-determined matrix, since the length could be 2, 10, even a 100 (which is max length for this problem).
#include <stdio.h>
int main(void) {
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
/*User enters matrix in the form:
12 10
10 10
*/
printf("Enter Matrix A\n");
for(int i=0; i<sizeof(matrixA); i++){
for(int j=0; j<sizeof(matrixA[i]);i++){
scanf("%d ",&matrixA[i][j]);
}
}
//to see if scanf worked
for (int i = 0; i<sizeof(matrixA); i++) {
for(int j=0; j<sizeof(matrixA[i]);i++) {
matrixA[i][j] = '.';
printf("%c ",matrixA[i][j]);
}
printf("\n");
}
int matrixB[r][c];
printf("Enter Matrix B\n");
return 0;
}
You are right that
scanf( "%d %d %d", &int1, &int2, &int3 );
will only work if the number of parameters is fixed at compile-time. It cannot be changed at run-time.
Your idea of calling
scanf("%d ",&matrixA[i][j]);
in a loop instead is correct, in principle. However, you should not have a space character in the format string, as this will cause scanf to continue to read input from the input stream, and it will only return after it has encountered a non-whitespace character. This is usually not what you want.
Also, the line
for(int i=0; i<sizeof(matrixA); i++){
is wrong, because sizeof(matrixA) is the size of the array in bytes. Since you instead want to get the number of elements in the outer array, you could write sizeof matrixA / sizeof *matrixA instead. (The parentheses are only necessary when referring to types, not variables.) However, in this case, it would be easier to simply use r instead.
The line
for(int j=0; j<sizeof(matrixA[i]);i++){
is wrong. You probably intended to write j++ instead of i++.
Also, when printing variables of type int with printf, you should usually use %d instead of %c, because otherwise the value may be truncated if the value is higher than 127.
It is unclear what the line
matrixA[i][j] = '.';
is supposed to accomplish, as this will overwrite the previous input of scanf (assuming that you fix your loop as described above).
After fixing all of the issues mentioned above, your code should look like this:
#include <stdio.h>
int main(void)
{
int r;
int c;
printf("Please enter the number of rows : ");
scanf("%d", &r);
printf("Please enter the number of columns : ");
scanf("%d", &c);
int matrixA[r][c];
printf("Enter Matrix A:\n");
for ( int i=0; i < r; i++ )
for( int j=0; j < c; j++ )
scanf( "%d", &matrixA[i][j] );
//to see if scanf worked
printf( "Input complete, the array contents are:\n" );
for ( int i=0; i < r; i++ )
{
for( int j=0; j < c; j++ )
printf( "%d ",matrixA[i][j] );
printf( "\n" );
}
return 0;
}
This program has the following behavior:
Please enter the number of rows : 4
Please enter the number of columns : 4
Enter Matrix A:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Input complete, the array contents are:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
POSIX-specific answer
Well, you don't.
There are two ways to get that done:
Slice stdin into rows by the '\n' character n times; later slice every row in n columns by ' ' the whitespace. getline and strtok come in handy here.
The other approach is more efficient and as usual more complicated: rather than slicing into rows first, you iterative cut-off cols, counting them, and when count == n comes true, you expect '\n' to be there thus ending another line. I wouldn't suggest this approach.
So roughly your codes looks something like:
ssize_t nread;
for (sizet_t i = 0; i < n; i++) {
char *line = NULL;
if ((nread = getline(&line, &len, stream)) != -1) {
fprintf(stderr, "Bad format: %il-th line expected.", i + );
exit(EXIT_FAILURE);
}
char* token = strtok(line, " ");
for (size_t ii = 1 /* because you've already cut-off the first token */; i < n; ii++) {
token = strtok(NULL, " ");
}
}
Of course, you have to parse your char * tokens, but that is something I leave to you as an exercise. It also quite sloppy and does not do any sort of validation a production code is expected to do.

Is there a way to add multiple values into an array in one command prompt?

I am trying to scanf 5 numbers into an array in one command line prompt. I know how to store a value one by one into an array, but in this case I am trying to store 5 values in a line. I know how to hard code it when the limit is clear, but I want to code it based on a user inputted limit.
for example (hard code):
int arr[5];
scanf("%d %d %d %d %d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4]);
for (i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
would give me the values of arr[0] arr[1] arr[2] arr[3] arr[4].
BUT what if the size of aaa is defined by users, or defined by a macro that allows changes? How do you not hard code it?
#define MAX 10
int arr[MAX];
or
printf("what is the limit? : ");
scanf("%d", &limit);
int arr[limit];
I tried using a for loop but it doesn't work.
for(i=0;i<MAX; i++){
scanf("%d %d %d %d %d\n", &aaa[i]); //I want user to input 5 numbers in one line, but this format doesnt work.
}
To conclude/clarify my question.
I want user to input 5 numbers in one line. for example : 1 2 3 4 5 with a space in between. and I want it stored at arr[0] arr[1] arr[2] arr[3] arr[4]. Is there a way to not hard code this?
Help would be greatly appreciated! Thanks!
You want this:
#include <stdio.h>
int main()
{
int arr[5];
printf("Enter 5 numbers separated by space then press Enter\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < 5; i++) {
printf(" %d", arr[i]);
}
}
Execution:
Enter 5 numbers separated by space then press Enter
1 2 3 4 5
1 2 3 4 5
You need to read inputs in the loop as below.
for(i=0;i<MAX; i++) {
scanf("%d", &aaa[i]);
}

how to continously scan for the amount of numbers inside of an array

I currently am having a small trouble in my code, I am supposed to make a program that adds / sums all numbers inside of an array, while I have no problem in doing that, I currently have a problem with the part in which you are supposed to scan the numbers to be put in the array, here are the example of the input
3
5
1 2 3 4 5
8
1 2 3 4 5 6 7 8
9
1 2 3 4 5 6 7 8 9
What this means is that, the user inputs number "3" as it means to create 3 arrays, the number "5" afterward means to put 5 numbers inside of the array (1 2 3 4 5), after the user has inputted the numbers inside of an array, the user inputs "8" which means to make another array consisting of 8 numbers, and then putting numbers into the array again, and so on.
However I am having a problem in which after inputting all the numbers in the array that consists of 5 number, the program instead inputs 5 number into another array again (instead of asking the amount of numbers to be put inside of another array), so instead the number "8 1 2 3 4" gets inputted in another array, and I did not know which part I did wrong.
Here are my C code :
#include <stdio.h>
int main(){
int x, y;
int i;
int n;
int c=1;
int count=0;
int sum=0;
scanf("%d", &y); //this determines the amount of array to be inputted
scanf("%d", &x); //this determines the amount of numbers to be inputted inside of an array
int line[x];
for(int i=0; i<y; i++){
sum=0;
for(int i=0; i<x; i++){
scanf("%d", &line[i]); //scan number for the array
sum += line[i];
}
printf("Case #%d: %d\n", c, sum);//output of all sum
c++;
}
}
You need to read the size for each array - currently you only read it once.
e.g.:
int numLines;
scanf("%d", &numLines);
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
int line[numNumbers];
for(int i = 0; i < numNumbers; i++) {
scanf("%d", &line[i]);
}
}
Additionally you can avoid storing the individual numbers, since you're only interested in the sum, e.g.:
int sum = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sum += number;
}
Also you could defer outputting the sums until all inputs have been processed, so it doesn't visually get interleaved into the input.
This would be a possible way to write that program: godbolt
#include <stdio.h>
int main() {
// get the number of arrays we need to read
int numLines;
scanf("%d", &numLines);
// The sums of each array
int sums[numLines];
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
// read the number of elements for each array
int numNumbers;
scanf("%d", &numNumbers);
// sum up all the numbers of the array
sums[lineIdx] = 0;
for(int i = 0; i < numNumbers; i++) {
int number;
scanf("%d", &number);
sums[lineIdx] += number;
}
}
// after all arrays have been entered,
// output the sums for each case:
for(int lineIdx = 0; lineIdx < numLines; lineIdx++) {
printf("Case #%d: %d\n", lineIdx, sums[lineIdx]);
}
}

C scanf ignore second variable in loop [duplicate]

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Why does scanf ask twice for input when there's a newline at the end of the format string?
(7 answers)
Closed 3 years ago.
int main()
{
float T[100];
float *pt=T;
float suma = 0, srednia, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf(" %d", &rozmiar);
int dzielnik = rozmiar;
printf("\n Enter the number: \n");
for(int i = 0;i<rozmiar;i++)
{
printf("\n i = %d", i );
scanf("%99f\n", &zmienna);
*(pt+i) = zmienna;
}
return 0;
}
This is my code. The idea is simple. I have an array; I want to scan how many numbers I want to put into the array and then put numbers into array. I don't know why but scanf ignores the second variable that I put in array.
If I put "2" in first scanf, program wants 3 variables from me.
My output should be like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
2 (my number)
i=1
3 (my number)
but it's actually like this:
How many numbers would you like to put in: 2
Enter the number:
i = 0
1 (my number)
2 (my number)
i = 1
3 (my number)
The specific problem you were having is with scanf: putting a \n is generally a bad idea because entering a newline is generally how you send off a line of characters to the program. Use '\n' liberally in printf and "never" with scanf.
Here's my modified version. I removed the pointer shenanigans because indexing into the array is simpler and better, and also initialized the array which you should always do:
#include <stdio.h>
int main() {
float T[100] = {0}; // Used to not be initialized.
float suma = 0, zmienna;
int rozmiar;
printf("How many numbers would you like to put in: ");
scanf("%d", &rozmiar);
printf("\n Enter the number: \n");
for (int i = 0; i<rozmiar; i++) {
printf("\n i = %d", i);
scanf("%f", &zmienna);
T[i] = zmienna;
}
return 0;
}

Why is this for loop getting ignored? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm not sure what i'm doing wrong but the for loop is not initializing
The code just goes immediately to displaying the printfs. That have no values in them since the for loop didn't activate
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define PAUSE system("Pause")
main() {
// INITALIZE VARIABLES
int number = 0;
int i = 0;
int odd = 0;
int even = 0;
int totalNum = 0;
int tempNum = 0;
int count;
printf("Enter a number between 2 and 25\n");
scanf("%i", &number);
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
for (i = 1; i == count; ++i){
printf("input numbers\n");
scanf("%i", &tempNum);
if (tempNum % 2 == 0)
even++;
else
odd++;
totalNum = totalNum + tempNum;
} // END FOR LOOP
// DISPLAY OUTPUT
printf("You entered %i numbers\n", count);
printf("The sum of the %i numbers is %i\n", count, totalNum);
printf("The average of the %i numbers is %i\n", count, totalNum / count);
printf("You entered %i odd numbers and %i even numbers\n", odd, even);
PAUSE;
} // END MAIN
Your loop will only execute at best once, when count == 1 as you initialize i to 1.
If you enter a 1 for count,
printf("Enter how many numbers you want to input\n");
scanf("%i", &count);
the loop will run exactly once, until i increments to 2
You probably want:
for (i = 1; i <= count; ++i){
do{
if (number < 2 || number > 25)
printf("That was an invalid number please try again\n");
scanf("%i", &number);
} while (number < 2 || number > 25);
it should be...
do{
if (number < 2 || number > 25){
printf("That was an invalid number please try again\n");
scanf("%i", &number);
}
} while (number < 2 || number > 25);
else it asks always another number
i = 1, so i == count; gives false therefore the loop is ignored.
A for loop in C works like this:
for ( variable initialization; condition; variable update ) {
/* Do something... */
}
The loop will execute for as long as condition is true. So, when you do:
for (i = 1; i == count; ++i)
The loop will execute for as long as i == count is true. So, unless count holds 1 when this line is executed, the loop will never run.
As others pointed out, you probably want this:
for (i = 1; i <= count; ++i)
So your loop will run for all values of i, until it reaches count.
As a side note i should point out that the usual way to write for loops in C is something like this:
for (i = 0; i < count; i++)
We start with i = 0 because C arrays are zero-based, so the Nth element of an array has index n-1
You were so close. In addition to fixing your loop test clause for (i = 1; i <= count; i++), I would suggest using " %d" for your format specifier. Your do loop need only be a while loop to avoid printing your invalid number message every time.
Additionally, While not an error, the standard coding style for C avoids caMelCase variables in favor of all lower-case. See e.g. NASA - C Style Guide, 1994.
With those changes, (and changing your odd/even check to a simple &) you could write your code as follows.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// #define PAUSE system("Pause")
int main (void)
{
int number, i, odd, even, totalnum, tempnum, count;
number = i = odd = even = totalnum = tempnum = count = 0;
printf ("enter a number between 2 and 25: ");
scanf (" %d", &number);
while (number < 2 || number > 25) {
printf ("invalid number, again (between 2 and 25): ");
scanf (" %d", &number);
}
printf ("numbers to input: ");
scanf (" %d", &count);
for (i = 1; i <= count; i++) {
printf ("input number %2d: ", i);
scanf (" %d", &tempnum);
if ((tempnum & 1) == 0)
even++;
else
odd++;
totalnum = totalnum + tempnum;
}
printf ("You entered %d numbers\n", count);
printf ("The sum of the %d numbers is %d\n",
count, totalnum);
printf ("The average of the %d numbers is %d\n",
count, totalnum / count);
printf ("You entered %d odd numbers and %d even numbers\n",
odd, even);
// PAUSE;
return 0;
}
note: main is type int (e.g. int main (int argc, char **argv) or simply int main (void) to indicate no arguments taken). Since it is type int it will return a value to the shell. While historic implementations may have allowed void main that is no longer the case for portable code.
Example Use/Output
$ /bin/forskipped
enter a number between 2 and 25: 4
numbers to input: 4
input number 1: 1
input number 2: 2
input number 3: 3
input number 4: 4
You entered 4 numbers
The sum of the 4 numbers is 10
The average of the 4 numbers is 2
You entered 2 odd numbers and 2 even numbers
Look it over and let me know if you have any questions.

Resources