While loop not repeating in c - c

I have to create a program that requests integer numbers from the user
repetitively though the keyboard until the user enters 0. I've gotten to the while loop and its not repeating and I'm not sure why. Any help would be greatly appreciated.
Thanks
Edit: I've fixed the loop in terms of it not repeating but now it's infinitely repeating and I have no clue why.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char first[30], last[30];
int n, even, odd, etotal = 0, ototal = 0;
printf("What is your first name?\n");
scanf("%s", &first);
printf("What is your last name?\n");
scanf("%s", &last);
// asks for name
printf("Enter a number\n");
printf("To quit the program enter 0\n");
scanf("%d", &n);
while (n!=0){
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++; }
}
return 0;
}

The loop isn't repeating because you have a return statement in the loop, that will leave the main function immediately. Just remove it.
You also have another problem that's much worse: Undefined behavior. Local non-static variables, like for example n in your code, don't get initialized, instead they have an indeterminate value. Attempting to use such an uninitialized variable leads to said undefined behavior.
You need to explicitly initialize the variable to some value before using it in the condition, for example to reorder the code so you read input before the loop and then also at the end of the loop.

Local variable n is uninitialized producing undefined results collaboratively called undefined behavior. Initialize it before entering loop:
n = 1;
And check result of scanf:
if (scanf("%d", &n) != 1)
// error

Because n is not initialized, so it has a random value:
int n, even, odd, etotal, ototal;
/* ... */
while (n!=0){

Loop is not working because you didn't initialize n and unnecessary return 0 inside the while loop. You can fix it with do..while as below. Because you have the input statement as your first statement, do..while is best opted here.
do{
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++;
}
else {
printf("%d is odd.\n",n);
ototal++;
}
} while (n!=0);

You use scanf to read your input, but after your if/else statement you are returning 0 hence you are leaving the program. So it doesnt matter if you write an even or an odd number.
while (n!=0){
scanf("%d", &n);
if(n%2==0){
printf("%d is even.\n",n);
etotal++; }
else{
printf("%d is odd.\n",n);
ototal++;
}
return 0;
}

Related

In this program to determine whether number is palindrome or not, I can't figure out what's going wrong? I think scanf isn't even taking value

I tried to detect whether a number is palindrome or not without using library functions and without array. i don't think the logic is the problem here. I introduced printf's as a checkpoint after scan and some of the loops but i think the code isn't even reading the input as it is unable to print the value of input
#include<stdio.h>
int main()
{
long a,b,x,i,j,d,y;
long g=0;
long n=0;
long c=10;
printf("Enter a number: ");
scanf("%li",&a); \\takes input
printf("%li",a); \\prints the scanned input(Checkpoint)
do{
n++;
b=a/10;
}while(b!=0); \\to determine the number of digits in input
printf("%li",n); \\(checkpoint)
x=a;
for(i=0;i<n;i++)
y=c*10;
printf("%li",y); \\(checkpoint)
for(j=0;j<n;j++) \\store the reverse value of input in g
{
d=x%c;
y=y/10;
g=g+(d*y);
x=x/10;
}
if(g==a) \\check if number is palindrome
{
printf("Palindrome");
}
else
{
printf("Not a palindrome");
}
return(0);
}
In the loop
do{
n++;
b=a/10;
}while(b!=0);
you never modify the value of a, so the result of a/10 and thus the value of b will always be the same. If a is equal to or larger than 10 then you will have an infinite loop here, as b will never be equal to zero.
Since the output before the loop isn't flushed (actually written to the terminal) then it can look like the scanf call will never return.

Writing simple base code for a program that keeps track of my work hours and pay in C

When I compile my code it says that everything checks out but when I run it nothing happens. The program just runs until I kill the terminal.
#include<stdio.h>
int main()
{
float work;
work=0;
char ans[]="No";
while(ans[0]=='N');
{
printf("Hours worked today ");
scanf("%f", &work);
printf("Is that all? ");
scanf("%s", ans);
}
return 0;
}
You have put a ; after the while condition. Therefore your while loop is empty and will run forever.
The more readable equivalent of your program is this:
int main()
{
float work;
work=0;
char ans[]="No";
while(ans[0]=='N')
{
// empty loop thAT will run forever
}
// we never get here
printf("Hours worked today ");
scanf("%f", &work);
printf("Is that all? ");
scanf("%s", ans);
return 0;
}
In your program juste change
while(ans[0]=='N');
to
while(ans[0]=='N')
and it will work.
char ans[]="No";
...
scanf("%s", ans);
ans can hold only a string of length 2. You should make ans larger, to be able to hold any reasonable input, e.g.:
char ans[200] = "No";
Another problem is the ; after the while:
while(ans[0]=='N');
^
Remove it. It makes an empty instruction the only thing the while repeats.
Another thing: when dealing with user input, be it stdin or file input, you should check if the read was done successfully, in you case you should check the return value of scanf
Simply change
while(ans[0]=='N');
to
while(ans[0]=='N')
, because the former is identical to
while(ans[0]=='N')
{
;
}
,which will never end.

printf after scanf always displays 1 (same unexpected value)

Okay so I'm trying to do a basic program in VS. Enter a number then it gets printed out. 1 is always printed.
int main(){
printf("Enter an integer: ");
int n = scanf_s("%d", &n);
printf("%d", n);
}
You are assigning the returned value from scanf_s() to the variable n, that means that the program will print 1 in case a successful read happened.
What you should do is
int numberOfItemsMatched;
int readValue;
numberOfItemsMatched = scanf_s("%d", &readValue);
if (numberOfItemsMatched == 1)
printf("%d\n", readValue);
I hope the variable names are self explanatory, and it's always a good idea to use this kind of names.
return type of scanf is number of items read. so if scanf is succesful in reading an item, it returns one which is assigned to n here. hence the output is 1. So separate declaration of n and scanf.

While loop with scan in C

So my question is the following.
int n=0;
while(n<=0)
scanf("%d",&n);
This code enters in an infinite loop, and I don't have a clue why. When the user inputs a number > 0, the loop was supposed to stop.
And thanks:)
Over and over and over and over...
stdin is (generally) line-buffered - one has to press <enter> to make the terminal transfer the characters to your program. So now there's a dangling newline character in the buffer, and scanf() will try to read it during the next iteration, but it's not an integer, so it fails and doesn't change the contents of the variable. To solve this, make scanf() eat the newline:
scanf("%d\n", &number);
(Oh yes, n is also used uninitialized, but it seems that your code enters the loop anyway, so that's not the issue. Do initialize it, though, else you will face other strange errors.)
while (n <= 0)
// something
means "do something while value of n is less or equal to 0". Just make sure that n is initialized when condition n <= 0 is being evaluated. Using uninitialized variables produces undefined behavior.
You should do:
int n = 0;
while (n <= 0)
scanf("%d\n",&n);
I think you should change your compiler because i'm getting the fine result.
You might have a problem somewhere else.
You can check here.:
http://ideone.com/C4Yobi
Code:
#include<stdio.h>
main( )
{
int n = 0;
while (n <= 0)
scanf("%d",&n);
printf("%d",n);
}
Input:
-5
4
Output:
4
Since you claim to have tried things and they didn't work (although I don't see why) let's try something else. Let's use a programmer's best friend: printf. How about trying to run this code instead:
int n = 0;
while(n <= 0)
{
printf("Please enter a number: ");
scanf("%d\n", &n);
printf("I see you entered: %d\n", n);
}
printf("Done with the loop. The value of n is: %d\n", n);
This will let you see what the computer is doing and what values it reads as it reads them. Try replacing your code with the above and let's see what happens.

program to find the sum of digits

I can't figure out the problem in this:
#include<stdio.h>
int main()
{
int a,b,count ;
count =0;
printf("enter the value for a ");
scanf("%d ",&a);
while(a>0)
{
b=a%10;
count=b+count;
a=a/10;
printf ("hence the simplified result is %d",count);
}
return 0;
}
There's a silent killer in your code:
scanf("%d ",&a);
The extra space in your scanf will make entering numbers harder: this will match 12<space>, but not 12. Replace the "%d " with "%d".
You do not terminate your printf() with a "\n". The output stream (stdout) is, usually, line buffered. That means that incomplete lines need not be printed unless you force them with fflush(). But there's no need for that.
Simply add a "\n" to your printf()
printf("hence the simplified result is %d\n", count);
One issue is you print the count with every loop, rather than than after the loop.
Not an issue, but C has arithmetic assignment (aka compound assignment) operators that can be more readable. For example, a /= 10 is equivalent to a = a/10.
I think the printf statement should be outside the loop.
Move the printf out side the loop. That will fix it.
Try the following:
#include<stdio.h>
int main()
{
int a,b,count ;
count =0;
printf("enter the value for a ");
scanf("%d",&a);
while(a>0)
{
b=a%10;
count=b+count;
a=a/10;
}
printf ("hence the simplified result is %d",count);
return 0;
}

Resources