A question about break statement in c programming - c

I wrote this loop to add numbers, and the break to get out of the loop if the number entered is less than zero, and in last print the calculated numbers without adding the negative number. but the problem is even I wrote the break statement before the addition when I enter 15 and 15 and -2 the output is 28 rather than 30
I found out how to fix that, what I want to know is why
and thank you.
#include <stdio.h>
void main()
{
int j = 1, num = 0, rslt = 0;
while (1) {
if (num < 0) break;
printf("enter a number : ");
scanf("%d", &num);
rslt = rslt + num;
}
printf("the resluts are %d\n", rslt);
}

Currently, you are effectively testing the input of the previous iteration, after already adding it to your result. Instead, check the number immediately after the user enters it, before you perform any calculations.
#include <stdio.h>
int main(void)
{
int num = 0, rslt = 0;
while (1) {
printf("enter a number : ");
scanf("%d", &num);
if (num < 0)
break;
rslt += num;
}
printf("the results are %d\n", rslt);
}
You might also want to check that scanf returns the number of successful conversions you were expecting (in this case one), to handle the event where the user enters invalid input.
if (1 != scanf("%d", &num))
break;

Related

This code is running properly when I use 1 digit numbers. But It's keep lagging on more digit numbers

Something is wrong. I'm trying to make a cade which can count number count of any natural number. Like number count of 2 is 1, 30 is 2, 456 is 3. My code is running for 1 digit numbers but not for two digit numbers.
#include<stdio.h>
void main(void)
{
int num,count,check;
float div;
printf("Enter a natural number\n");
scanf("%d", &num);
while (num<=0)
{
printf("Error\n");
printf("Enter a number\n");
scanf("%d", &num);
}
while(num>1)
{
count=1;
check=10;
div=num/check;
if(div<=1)
{
printf("Number count is\n%d", count);
break;
}
check = check*10;
count = count+1;
}
}
The problem with your solution is that after check and count are modified at the end of the loop, they are re-declared to 1 and 10 respectively at the beginning of the loop at every passage.
You need to move the declaration just before the while loop.
Also div doesn't need to be a float given that the decimal part of this number is irrelevant.
You could also use less variables by replacing check by 10 and
using num directly instead of temporarily storing results in div.
I think this might be a simpler solution
#include <stdio.h>
int main(){
int num = 0, digits = 0;
while (num <= 0)
{
printf("Enter a natural number\n");
scanf("%d", &num);
num == 0 ? printf("Error\n") : 0;
}
for( ; num > 0; digits++)
num /= 10;
printf("number of digits: %d\n", digits);
}
As num is continuously divided by 10, the decimal of the result gets truncated since num is an int while digits steadily increases.
It is time to learn to use a debugger. Using it would have immediately shown the major problem in your code: you reset the value of count and check inside the loop. So if you enter a number greater or equal to 10, you enter an infinite loop because you will consistently divide that number by 10 and find that the result is >= 1!
There is another less important problem: you use if(div<=1) when it should be if(div<1). Because 10/10 is 1 and has 2 digits...
After those fixes you should have:
...
check = 10;
count = 1;
while (num > 1)
{
div = num / check;
if (div < 1)
{
printf("Number count is\n%d", count);
break;
}
check = check * 10;
count = count + 1;
}
return 0; // main shall return an int value to its environment...
}
Which correctly gives the number of decimal digit on positive integers. But as you were said in comments, you should always test the return value of scanf (what is the user inadvertently types a t instead of 5 for example?).
That being said, this answer intends to show you what the problems were, but Keyne's solution is better...

multiply numbers untill the user enters 0

I don't know why but the loop doesn't stop even when I enter 0. can someone help me with this?
int main(void)
{
float number,product = 1;
printf("Provide floats separated by a line: \n");
scanf("%f" , &number);
while(number != 0)
{
product *= number;
if(number == 0)
break;
}
printf("The product of your values is: %.2f" , product);
printf("\n");
}
You'll need to place the scanf call inside the loop to repeatedly ask the user for input. As it is you only ask once, and then loop forever on the same value.
Here we place the call in the predicate itself:
#include <stdio.h>
int main(void) {
float number = 0,
product = 1;
puts("Provide floats separated by a line:");
while (scanf("%f" , &number) == 1 && number)
product *= number;
printf("The product of your values is: %.2f\n" , product);
}
You should always check the return values of your I/O functions. scanf returns the number of conversions that took place, which here should be 1. On error, EOF, or number being 0 we do not continue the loop.

C Loop until the condition is met problem

I want to write a loop that runs until the user enters a number greater than 10, but I have to do something wrong because it creates an infinite loop.
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
for(int i=0;a<10;i++){
printf("Enter value>10");
i++;
printf("%d",&a);
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
You mix an index that does not make sense. Also you print the memory address of variable instead of its value, not sure it is what you wanted?
Code partially corrected (because I don't know what is your ultimate goal):
#include <stdio.h>
int main()
{
int a;
do {
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
printf("\na: %d\n",a);
} while (a <= 10);
printf("Result:%d\n",a+a-2+a-4+a-6+a-8+a-10);
return 0;
}
ps: \n is line return and added do while which is what you want when you want to execute a loop at least once.
Have a look at your for-loop: you let i start at zero, you continue until a is not smaller than ten anymore, but it's not the value of a you need to check, it's the one of i.
In top of that, you are doing a i++ within your for-loop, while this is already covered in the definition of the for-loop.
I think this is the code that you are looking for: See comments
#include <stdio.h>
int main()
{
int a, ok = 0, end_of_input = 0;
do {
printf("Please input an integer value (min. 10): ");
fflush(stdout); // So the user can see the above line!
switch(scanf("%d",&a)) {
case EOF: // End of input - Give up!
end_of_input = 1;
break;
case 1: // Got a number - Check it!
if (a < 10)
{
ok = 1;
} else {
printf("%d - Not appropriate input. Please try again.\n\n",a);
}
break;
default: // Summat else - "eat" the input to the next line
scanf("%*[^\n]\n"); // "eats" the rest of the line in the buffer w/o assignment
break;
}
} while (end_of_input == 0 || ok == 0);
if (ok) { // User entered a valid number
printf("Got a that is smaller than ten %d\n", d);
} else { // We have ran out of input
printf("See you want to leave us :-(\n");
}
return 0;
}
I am not sure what you are trying to achieve but one problem that I found in your logic is you prompting user for input outside the loop. So whenever you enter number less than 10 it always goes in infinite iteration.
Try following code, with scanf inside loop
int main()
{
int a;
printf("Enter 'a' value (min 10): ");
scanf("%d",&a);
int i=0;
for(;a<10;){
printf("Enter value>10");
scanf("%d",&a);
printf("%d",a);
i++;
}
printf("Result:%d",a+a-2+a-4+a-6+a-8+a-10);
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.

looping "enter student id:" statement

#include <stdio.h>
#include <stdlib.h>
int main()
{
int id = 0;
int pin = 0;
int count1 = 0;
int count2 = 0;
printf("enter student id: ");
scanf("%i",&id);
while(id !=0)
{
id /= 10;
count1++;
}
while(count1 != 7)
{
printf("the student id should be in 7 or 8 digits\n");
printf("enter student id: ");
scanf("%i",&id);
}
if(count1 = 7)
{
printf("enter student pin: ");
scanf("%i",&pin);
}
return 0;
}
If I retype my student id, which is 7 digits, I expect to go to the next statement, but it keeps repeating same question.
How do I fix this?
Your code has a number of problems.
if(count1 = 7) assigns the value 7 to the variable count1, to make a comparison use if(count1 == 7).
Every time the user enters a id, you need to check its length, not just the first time. You could use some sort of loop and conditional. If that condition is met (ie. student id length of 7 or 8 digits), then break the loop and continue.
Every time the user enters a new number, you need to reset count1, otherwise you will just continue increasing it infinitely.
For example you could do this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int id = 0;
int pin = 0;
int count1 = 0;
for(;;)
{
printf("enter student id: ");
scanf("%i",&id);
while(id !=0) {
id /= 10;
count1++;
}
if (count1 != 7 && count1 != 8) {
printf("the student id should be in 7 or 8 digits\n");
count1 = 0;
}
else break;
}
printf("enter student pin: ");
scanf("%i",&pin);
return 0;
}
Since you have if (count1 = 7), 7 is assigned to count1 and the condition is evaluated as truth because in c any non zero condition is true.
To prevent this you might want to turn on compiler warnings, if they were on the compiler would tell you to add explicit parentheses to an assignment used as a truth value.
This answer although it still skips scanf()'s return value which is potentially invoking undefined behavior does solve your problem, but I have got a suggestion for you.
If you want to check how many digits were scanned you can use the "%n" specifier, like this
int
main(void)
{
int value;
int count;
value = 0; /* initialized in case no valid characters are scanned */
count = 0; /* initialized in case no valid characters are scanned */
if ((scanf("%d%n", &value, &count) == 1) && (count == 7))
fprintf(stderr, "ok, value is `%d'\n", value);
else
fprintf(stderr, "wrong length: %d\n", count);
return 0;
}
You just need to read scanf()'s manual page Very Carefully to figure this out, and also to learn how to validate input based on scanf()'s return value.

Resources