Getting an Array from user? C programming - c

My console keeps on crashing after entering a few numbers. I am trying to get an array of 10 numbers from the user thru the console and then taking count of positives, negatives, evens, and odds. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pos, neg, even, odd;
int nums[10];
printf("Give me 10 numbers: ");
pos = neg = even = odd = 0;
for(int i = 0; i < 10; i++){
scanf(" %d", nums[i]);
if(nums[i] > 0){
pos++;
if(nums[i] % 2 == 0){
even++;
}
else{
odd++;
}
}
else{
neg++;
}
}
printf("Positives: %d, Negatives: %d, Evens: %d, Odds: %d\n", pos, neg, even, odd);
return 0;
}

In your code,
scanf(" %d", nums[i]);
should be
scanf(" %d", &(nums[i]));
or,
scanf(" %d", nums+i);
as you need to pass the pointer to variable as the format specifier's argument in scanf() .
To elaborate, %d expects a pointer to int and what you're supplying is an int variable. it invokes undefined behavior.
That said,
Always check the return value of scanf() to ensure proper scanning.
int main() should be int main(void) to conform to the standard.

Modify scanf like scanf(" %d", &nums[i]);

scanf(" %d", nums[i]);
Scanf expects a pointer to a location to write to, and you're not giving it one.
Change your scanf to:
scanf(" %d", &(nums[i]));
to make your program work.
With this change I tested your program with stdin of
20 10 9 1 39 1 2 2 31 1
And recieved output:
Give me 10 numbers: Positives: 10, Negatives: 0, Evens: 4, Odds: 6
ideone of the thing for your testing purposes.

Change scanf(" %d", nums[i]); to scanf(" %d", &nums[i]);, because scanf() needs addresses. The parentheses around nums[i] isn't necessary, and may effect readability.
Also note that 0 is even, but not negative.

When scanf is usedto convert numbers, it expects a pointer to the corresponding type as argument, in your case int *:
scanf(" %d", &nums[i]);
This should get rid of your crash. scanf has a return value, namely the number of conversions made or the special value EOF to indicate the end of input. Please check it, otherwise you can't be sure that you have read a valid number.
When you look at your code, you'll notice that you don't need an array. Afterreading the number, you don't do aything with the array. You just keep a tally of odd, even and so on numbers. That means you just need a single integer to store the current number. That also extends your program nicely to inputs of any length.
Here's a variant that reads numbers until the end of input is reached (by pressing Ctrl-D or Ctrl-Z) or until a non-number is entered, e.g. "stop":
#include <stdlib.h>
#include <stdio.h>
int main()
{
int count = 0;
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
int num;
while (scanf("%d", &num) == 1) {
count++;
if (num > 0) pos++;
if (num < 0) neg++;
if (num % 2 == 0) even++;
if (num % 2 != 0) odd++;
}
printf("%d numbers, of which:\n", count);
printf(" %d positive\n", pos);
printf(" %d negative\n", neg);
printf(" %d even\n", even);
printf(" %d odd\n", odd);
return 0;
}

Change scanf statement after for loop to
scanf(" %d", &nums[i]);

Related

Reading a table with only one scanf

This code with C language is supposed to count all characters equal to A as well as number characters in a table .. ~~ I've started by reading the table's characters giving by the user using a for loop and then i've used another for loop to count the number of characters equal to A as well as numbers~~
THE PROBLEM is with SCANF! what should I do to write scanf one time and not twice ???
#include <stdio.h>
#include <stdlib.h>
int main()
{
char T[100] = {0};
int i=0,N=0,b=0,n=0,x=0,j=0,k=0;
printf("give the number of your table's columns \n");
scanf("%d", &N);
if (N > 0 && N <= 100) {
for (i; i < N; i++) {
scanf("%c",T[i]);
printf("give the character of the column number %d /n", i);
scanf("%c",T[i]);
}
for (i = 0; i < N; i++) {
if (T[i] == 'A') b++;
else if (T[i]<='9' && T[i]>='0') n++;
}
printf("the number of characters equal to A is %d\n",b);
printf("The number of numeric characters is %d\n",n);
}
return 0;
}
your code needing only few editing
#include <stdio.h>
#include <stdlib.h>
int main()
{
char T[100]={0};
int i=0,N=0,b=0,n=0,x=0,j=0,k=0;
printf("give the number of your table's columns:\n");
scanf(" %d", &N);
if (N > 0 && N <= 100)
{
for (i=0; i < N; i++) {
//one scanf removed
printf("give the character of the column number %d \n", i);//<--/n to \n
scanf(" %c",&T[i]); //<-- & added to store the value
}
for (i = 0; i < N; i++) {
if (T[i] == 'A') b++;
else if (T[i]<='9' && T[i]>='0') n++;
}
printf("the number of characters equal to A is %d\n",b);
printf("The number of numeric characters is %d\n",n);
}
return 0;
}
while using scanf use & so it can store value while using scanf give a space before the scanf(" %c",&T[i]);
for (i; i < N; i++) {
scanf("%c",T[i]);
printf("give the character of the column number %d /n", i);
scanf("%c",T[i]);
}
here you tried to override T[i] twice without & in scanf removing one scanf and adding & and also for(i=0;i<n;i++) will be better way to go use \n instead of /n
Is this what you were looking to do?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, A_bin=0, Num_bin=0,length;
char array[100];
printf("Enter a string of numbers and letters: ");
scanf("%s",array); //Storing the Char array in "array"
length=strlen(array); //Getting the length of the Char array
for(i=0;i<=length;i++)
{
if (array[i]=='A') A_bin+=1;
else if (array[i]>= '0' && array[i]<='9') Num_bin+=1;
}
printf("The amount of 'A's in the string is: %d \n" ,A_bin);
printf("The amount of digits in the string is: %d" ,Num_bin);
return 0;
}
Instead of that story I wrote you. Here is what I think you were looking for right. This only looks for capital 'A' although could be adjusted for any characters you wanted by following the scheme. You could always adjust the array size as well for very large inputs. May have errors, play with it and see how it works. Hope the example I provided helped.
Output Example:
Enter a string of numbers and letters: AAJUR874EYRIAA
The amount of 'A's in the string is: 4
The amount of digits in the string is: 3

for loop resulting in undefined behaviour c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!
In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);
The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);
There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}

Not sure why my program keeps prompting error when I try to close it?

#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)

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.

Can anyone help me with this C program?

I've just started to learn coding
#include <stdio.h>
int main(void)
{
int i=0, x=0;
for (i=1; i<=100; i++) {
x++;
if (x%5==0 || x%3==0)
printf("The numbers are : %d\n", &x);
}
return 0;
}
so I'm trying to print all the integers <=100 that are divisible by either 3 or 5.
In the line:
printf("the numbers are : %d", &x);
printf is expecting an integer because of the %d format specifier, you have given it the address of an integer, thats what the & means, address of x. To fix this give printf what it desires, an int:
printf("the numbers are : %d", x);
The ampersand (&) operator returns the address of a variable, which isn't what you want - you just want the value. Also, note that you don't need two variables (x and i) - you can just use the loop's counter:
printf("The numbers are:\n");
for (i = 1; i <= 100; i++) {
if (i % 5 == 0 || i % 3 == 0) {
printf("%d ", i);
}
}
Removing the & will eliminate the error. You may also want to move the "the numbers are:" statement outisde of the loop so the text does not print each time through the loop.

Resources