-
while loop problem
Could anybody check this out?
it gives me a segmentation fault error when run
Code:
#include <stdio.h>
main()
{
int iBegNum = 0;
int iEndNum = 0;
int iIncre = 0;
printf("\n\tCounting program");
printf("\nEnter the beginning number to start counting from: ");
scanf("%d", iBegNum);
printf("\nEnter the number to stop counting at: ");
scanf("%d", iEndNum);
printf("\nEnter the increment number: ");
scanf("%d", iIncre);
while ( iBegNum <= iEndNum)
{
printf("\nThe value is: %d", iBegNum);
iBegNum = iBegNum + iIncre;
}
printf("\n\nThe program will now exit");
}
-
Code:
printf("\nEnter the beginning number to start counting from: ");
scanf("%d", &iBegNum);
Look up scanf() in your docs...
-
Mainly, it's forgetting the & on your scanf calls.
Perhaps use a compiler (gcc) that can tell you when you're abusing printf/scanf ?
Code:
$ gcc -W -Wall -ansi -pedantic -O2 foo.c
foo.c:5: warning: return type defaults to ‘int’
foo.c: In function ‘main’:
foo.c:13: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
foo.c:16: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
foo.c:19: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’
foo.c:13: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
foo.c:16: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
foo.c:19: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
foo.c:29: warning: control reaches end of non-void function
-
Code:
printf("\nEnter the beginning number to start counting from: ");
scanf("%d", iBegNum);
printf("\nEnter the number to stop counting at: ");
scanf("%d", iEndNum);
printf("\nEnter the increment number: ");
scanf("%d", iIncre);
scanf needs an address to store the converted data into, therefore you must pass the address of (a pointer to) those variables to scanf. To do this you must prefix the variable name with & (the address-of operator).
-
damn that always happens to me.
thanks
-
well it seems i got another problem here
there is a parse error before else but i cant find it
Code:
while ( iNum <= iNumQue )
{
iCurrTime = time(NULL);
do
{
iElapTime = time(NULL);
x = (rand() % 100 ) + 1;
y = (rand() % 100 ) + 1;
iResult = x + y;
printf("\nSum %d and %d", x, y);
} while ((iElapTime - iCurrTime) < 10); /*end do while*/
system("clear");
printf("\n\n%d. Enter your answer: ", iNum);
scanf("%d", &iAns);
if (iAns == iResult)
{
printf("\nCongratulations, you answered correct!");
iNumCorr = iNumCorr + 1;
else /*error: parse error before "else"*/
printf("\nSorry, you answered wrong");
iNumWrg = iNumWrg + 1;
} /*end if*/
iNum = iNum + 1;
} /*end while*/
-
You need to add braces in the vicinity.
-
ohh i got it :)
thank you
-
ok, a small question for the end
how to clear the screen as neither system("clear") nor system("cls") seem to work
>sh: cls: command not found<