I want to read some number from the terminal and print them afterwards.
However, they all seem to be some kind of random value instead of the one I supplied.
Why doesn't my input get saved correctly?
int main (void)
{
int i = 0 , numeros[21] , cont = 1, z = 0;
puts("\n === Bienvenido ===\n");
puts("\n === Vamos a procesadar un numero de serie de 20 digitos [Numericos] ===\n");
puts("\n === Dime los numeros ===\n");
while (cont != 20 )
{
fflush(stdin);
scanf("%d", &numeros[i]);
printf("\n === Dime otro numero. Numeros: %d ===\n", cont);
cont++;
}
for (z = 0; z < 20; z++)
{
printf("\nLos numeros son: %d\n", numeros[z]);
}
system("pause");
}
Ok, a couple of issues:
numeros is declared as an array of 21 ints, but you're using it as if it were numeros[20]
Undefined behaviour because you're calling fflush on stdin
scanf("%d", &numeros[i]), though unsafe, is all fine and dandy, but i is never incremented
Check return values of functions... always: scanf returns the number of values it scanned, if it returns 0, no %d was scanned, and numeros[i] needs to be reassigned.
Here's an example of how I'd write your program:
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
int c,i=0,
numbers[20],
count=0;
//puts adds new line
puts("enter 20 numbers");
while(count < 20)
{
c = scanf(" %d", &numbers[i]);//note the format: "<space>%d"
if (c)
{//c is 1 if a number was read
++i;//increment i,
++count;//and increment count
}
//clear stdin, any trailing chars should be ignored
while ((c = getc(stdin)) != '\n' && c != EOF)
;
}
for (i=0;i<count;++i)
printf("Number %d: %d\n", i+1, numbers[i]);
return 0;
}
You are not incrementing i in the first loop.
You are incrementing cont, but using numeros[i] to store your input. As i never changes, you only write to the first array element. Change the i to cont, as in
scanf("%d", &numeros[cont]);
What exactly do you want to achieve? I see that you're putting into i=0 index of your numeros array number from stdin. Then you're iterating trough this array, but you've just entered one number! You should propbably change the subsctript of your numeros array to cont like that:
scanf("%d", &numeros[cont]);
scanf("%d", &numeros[i]);
should be replaced with
scanf("%d", &numeros[cont]);
AS you are incrementing cont not i
Related
I'm just learning programming with c.
I wrote a program in c that had a bug in the body of the while loop
I did not put {}.
The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?
int main()
{
int n ,k;
float d ;
printf("please write your arithmetic sequence sentences ");
scanf("%d",&n);
printf("\n");
printf("please write your common differences");
scanf("%d",&k);
printf("\n");
printf("please write your initial element ");
scanf("%f",&d);
printf("error 1");
printf("\n");
printf("error 2");
printf("number \t sum");
printf("erorr 3");
int i = 0;
int j = 0;
int sum = 0;
while (i < n)
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
return 0;
}
Firstly, the program enters an infinite loop:
while (i < n)
j = d + i*k;
Since the values of i and n do not change, the condition never becomes false.
Secondly, the printing sequence:
printf("error 2");
printf("number \t sum");
printf("erorr 3");
does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.
#include <stdio.h>
int main()
{
int n ,k;
int i = 0;
int j = 0;
int sum = 0;
float d ;
// If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
printf("please write your arithmetic sequence sentences ");
if(scanf("%d",&n)){
printf("please write your common differences");
if(scanf("%d",&k)){
printf("please write your initial element ");
if(scanf("%f",&d)){
printf("Number \tSum\n");
} else {
printf("error");
}
} else{
printf("error");
}
} else{
printf("error");
}
// This is where the values get solved
// You also forgot to add {} in your while statement
while (i < n){
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
}
return 0;
}
I am attaching the code for the same.Its working fine.But once i enter a number less than the previous one it stops giving desired output.Any help/suggestion shall be greatly appreciated.
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
In your outer while loop, you're never resetting the value of the variable i back to 1, or j back to 0. That is why subsequent loops will produce an incorrect sum.
There are a smattering of bugs in this code, including:
Comparison to uninitialized value of of ch in the initial while expression.
Failing to reset i and j for each outer-loop iteration
Failing to test for data-read success in either scanf call to ensure proper input.
The continuation scanf("%s", &ch) is simply wrong for a single character with skipped whitespace (which you must do to avoid reading the newline after your list integer input). Unless EOF or an error state is reached, what you have now is guaranteed to invoke undefined behavior, as a string-read of at least one character requires at least two for storage (the character, and a subsequent terminator).
Addressing all of those:
#include <stdio.h>
int main()
{
char ch;
do
{
int n;
printf("Enter the number upto which you want the sum of \n \n");
if (scanf("%d", &n) != 1) // See (3)
break;
int j = 0; // See (2)
for (int i = 1; i <= n; ++i) // See (2)
j += i;
printf("%d \n", j);
printf("Do it with another number? Y/N \n \n");
if (scanf(" %c", &ch) != 1) // See (3) and (4)
break;
} while (ch != 'n' && ch != 'N'); // See (1)
return 0;
}
Everything here is self-explanatory when referred to the previous bug punch list, save for maybe the format string for reading the single character. You mentioned in comments that you tried %c but it skipped to another loop iteration. That's because you didn't have the leading whitespace " %c" that tells scanf to skip white space before extracting the next argument. With that, it should work as desired.
You need to reset i and j for every n.
i = 1;j=0;
while(i<=n)
{
Also your format specifer is wrong. For char, it should be %c and not %s
scanf("%c",&ch);
The simplest solution is to set i to 0 at the outer while:
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
Note that I have changed <= to < for your inner while, since you do not want to increment the value if the same n is inputted one after the other.
#include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%c",&ch);//this is a char not a string
}
return 0;
}
Due to the i is not initializing to 1 when the loop is coming for the second time there it is not going inside the loop and printing the previous value .
I'm writing a program that simulates purchasing cars. The program works well the first go around, but after the purchase is made and the prompt asks for a name, gets() does not search for input. Here is my code.
#include <stdio.h>
int i;
int j=1;
int prices[5] = { 24000,28000,25000,20000,120000 };
int invent[5] = { 5,2,3,8,2 };
int purchased[5] = { 0, 0, 0, 0, 0 };
int main()
{
char name[50];
printf("Welcome to Buy-a-Car!\nPlease enter your name:\n");
gets(name);
printf("Welcome, %s. Here is our available inventory.\n", name);
sale();
return 0;
}
void sale()
{
while (i>0, j != 0) {
printf("1. Toyota Camry %d %d\n2. Honda CRV %d %d\n3. Honda Accord %d %d\n4. Hyundai Elantra %d %d\n5. Audi R8 %d %d", invent[0], prices[0], invent[1], prices[1], invent[2], prices[2], invent[3], prices[3], invent[4], prices[4]);
printf("\nWhich car would you like to purchase?\n");
scanf("%d", &i);
i = i - 1;
printf("How many would you like to purchase?\n(Note: To checkout, please press 0.)\n");
scanf("%d", &j);
if (j > invent[i])
printf("I'm sorry, that number is insufficient. Please try again.\n");
else
invent[i] = invent[i] - j;
purchased[i] = j;
}
checkout();
}
void checkout()
{
printf("Review of transaction:\n1. Toyota Camry %d %d\n2. Honda CRV %d %d\n3. Honda Accord %d %d\n4. Hyundai Elantra %d %d\n5. Audi R8 %d %d", purchased[0], prices[0], purchased[1], prices[1], purchased[2], prices[2], purchased[3], prices[3], purchased[4], prices[4]);
int total;
for (i = 0; i < 5; i++)
{
total = total + (purchased[i] * prices[i]);
}
printf("\n\nTotal: %d\n\n\n", total);
j = 1;
int purchased[5] = { 0, 0, 0, 0, 0 };
main();
}
It's because the '\n' char in buffer after use scanf, use scanf("%d%*c",&var); %*c prevents '\n' to skip line when gets is used
gets is not safe, use fgets(&str,sizeof(str),stdin);
After running scanf(), the Enter (and anything before) is still in the input buffer. You can clear it like this:
scanf("%*[\n]%*c");
or
while( getchar() != '\n' );
Now gets() won't return an empty string. But anyway, it's extremely discouraged to use it. Use fgets or scanf("%[^\n]") instead.
fgets(name, sizeof(name), stdin);
// or
scanf("%[^\n]", name);
Besides, don't call main() from anywhere in your program. Its behavior is undefined. You can wrap the whole stuff up in another function, and use a loop. An endless recursion call will surely end up blowing up the stack.
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]);
The program needs you to enter the number of lines and columns (m and n) , enter elements into the array, then specifiy an element to be found and find it.
Once you do , print the position found at (starting with 1) , the line and column index, also specify the number of times the element was found.
The problems with my program : it prints several times bad numbers before the final printf that shows the correct location. If the location of the searched is at the start it shows nothing. I tested with printf the second for loop and saw that it only displayed the last 2 elements entered into the array.
Another problem is that i get an error anytime i try to enter a array that is bigger than [2] [2] , for example [3][3].
#include <stdio.h>
#include <stdlib.h>
main()
{
int m=0,n=0,tablou[m][n],i,j,e,nr=0,poz=0;
printf("Introduceti nr. de linii si nr. de coloane");
scanf("%d %d",&m,&n);
printf("Introduceti elementele in tablou\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d",&tablou[i][j]);
}
}
printf("Introduceti elementul pe care vreti sa-l gasiti");
scanf("%d",&e);
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
poz++;
if(tablou[i][j]==e)
{
printf("Elementul a fost gasit la pozitia %d fata de elementul 1, pe linia %d si coloana %d",poz,i+1,j+1);
nr++;
}
}
}
if(nr>0)
{
printf("\nElementul a fost gasit de %d ori",nr);
}
}
I can't see what's wrong, any help would be appreciated , thank you.
You should declare the array after initializing n and m to non-zero values, something like this
int m, n;
if (scanf("%d%d", &n, &m) != 2)
{
/* you could write a function that tries to get input again */
printf("invalid input\n");
return -1;
}
int tablou[m][n];
also not that main() should return int.
#iharob uses the new dynamc arrays of C99. It is a nice feature with the compiler doing lots of things for you. In older chainsaw versions of C you have to do that yourself:
int m, n, *tablou;
if (scanf("%d%d", &n, &m) != 2)
{
printf("invalid input\n");
return -1;
}
if ((tablou= calloc(n*m, sizeof(int)))==NULL) return -1;
...
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
poz++;
if(tablou[ i*n + j]==e)
...