I need to create a simple program which asks for 10 numbers from user and then shows the sum of those numbers or, if the user gives 0 as input, stops and immediately displays the sum of those numbers, and I need to create it only by using a "for" condition. Here is the code:
#include <stdio.h>
int main(){
int num = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &num);
if(num == 0){
printf("Sum: %d\n", num);
}
}
printf("Sum: %d\n", num);
getchar();
getchar();
}
It stops only when the number is greater than "10".Whats wrong?
I think you want to do this kind of work with your code.
#include <stdio.h>
int main(){
int num = 0;
int sum=0;
for(num = 0; num < 10; num++){
int i;
printf("Input a number: \n");
scanf("%d", &i);
sum = sum+i;
if(i == 0){
printf("Sum: %d\n", sum);
getchar();
return 0;
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
You are changing the value of the counter inside the for loop. That's why, when you read a value greater than or equal to 10, it will abandon the for loop, since you have the condition num < 10.
Let me tweak the code for you:
#include <stdio.h>
int main(){
int sum = 0;
int i;
int num;
for(i = 0; i < 10; i++){
printf("Input a number: \n");
scanf("%d", &num);
sum += num;
if(num == 0){
break; //means leave the loop
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
I'm using 3 variables:
sum, which is used to store the overall sum.
i, which is used as the for loop counter.
num, which is used to store the current number given by the user.
First of all, I'm waiting for an input:
printf("Input a number: \n");
scanf("%d", &num);
Now, the input is stored in num, so I'm upgrading the sum, to add the new value:
sum += num;
The I check if the current number is zero; in that case I'll just leave the loop:
if(num == 0){
break;
}
The problem in your code is, you're using the same variable num both as counter and for taking user input which is breaking the logic in for loop.
Use another variable for taking user input.
Also, you've to have a break statement to discontinue the for loop once you've got the breaking criteria.
Note: as I mentioned in my comments, there is no logic for Sum.
Check the below code.
#include <stdio.h>
int main(){
int num = 0;
int sum = 0; //to hold the sum
int input = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &input);
sum += input; // yoo-hoo, time to add-up
if(input == 0){
printf("Sum: %d\n", sum);
break; // time to say bye-bye to for loop
}
}
if (num == 10) //only print if not printed previously
printf("Sum: %d\n", sum);
return 0;
}
Related
I'm trying to make a loop that lets the user enter numbers one by each other and calculate the sum of all those numbers until the user enters 0 as an input. However, my code is running only once and then stops.
#include <stdio.h>
int main(void) {
int i = 0;
int num;
int total = 0;
printf("Give me a number \n");
scanf("%d", num);
if(num < 0 && num > 0){
printf("Give me a number \n");
scanf("%d", num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}
There are no loops in your code
The condition (num < 0 && num > 0) is alway false. A number can't be: less than zero AND greater than zero
Wrong call of scanf
You probably want:
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
while(num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
}
The above solution will exit the program if the user inputs a non-integer, e.g. a letter.
An alternative solution that will end the loop on non-integer input is:
printf("Give me a number \n");
while(scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
}
This last solution can even be written a little more compact - like:
while(printf("Give me a number \n"), scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
}
It's a bit harder to read but avoids duplicated lines.
This is the idiomatic way IMO. There is only one scanf call to scanf and we use break to end the loop prematurely if the user has entered 0.
#include <stdio.h>
int main() {
int i = 0;
int num;
int total = 0;
while (1) // loop forever
{
printf("Give me a number \n");
scanf("%d", &num);
if (num == 0) // if the number is 0
break; // we terminate the loop
total = total + num;
i = i + 1;
}
printf("You entered %d numbers, the total is %d", i, total);
}
Disclaimer:
for brevity there is no error check for scanf which IMO is OK for toy programs.
Otherways the remarks provided by 4386427 in his answer are correct.
Make sure to take the address of the variable (&num) in the scanf() call and add a do{ } while() statement.
int main(){
int i = 0;
int num;
int total =0;
do {
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
} while(num != 0);
printf("The total is %d", total);
}
the problem is in the if statement you are trying to check if the given number (num) is at once greater than 0 and less than 0 which is why the if scope won't be accessed u can use the following if statement
if(num!=0)
this will check if the num is different than zero!
and since you are trying to repeat this bloc until 0 is inserted you have to use a while/dowhile instead.
you have also to pay attention to the scanf because you forgot to specify the pointer of the num variable (scanf("%d", &num);)
In your case, use of while (num != 0) would be more suitable.
int main(){
int i = 0;
int num = 1;
int total = -1;
while (num != 0){
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}
I'm trying to check if five numbers are odd or even. I want to use a for-loop that iterates 5 times and uses a for loop that checks if the number is odd or even.
Code:
#include <stdio.h>
int main()
{
int a ,b ,c ,d ,e;
scanf("%d %d %d %d %d", &a, &b ,&c ,&d ,&e);
int count = 5;
for (int i = 0; i < count; i++)
{
if(num % 2 == 0) //num should be a then b then c etc.
printf("even");
else
printf("odd");
}
}
I cant find any information about swapping/switching variables inside a loop/statment. If anyone has an answer or where to find the information i will be forever grateful!
Thanks in advance!
//Noob programmer
Instead of scanf-ing into distinct variables (a, b, etc.), perhaps you can scanf into an array of integers.
Then you can use indexing of the array.
int num = numbers[i];
Within the for loop.
As I mentioned in a comment, this can be solved with only a single variable and without arrays:
#include <stdio.h>
int main()
{
unsigned const count = 5;
for (unsigned i = 0; i < count; i++)
{
printf("Please enter a number: ");
fflush(stdout); // To make sure the output is printed
int number;
scanf("%d", &number); // Note: Doesn't handle errors
if (number % 2 == 0)
{
printf("The number %d is even\n", number);
}
else
{
printf("The number %d is odd\n", number);
}
}
}
If you do not want to learn the arrays there is a hardcore way of doing it:
for (int i = 0; i < count; i++)
{
switch(i)
{
case 0:
num = a;
break;
case 1:
num = b;
break;
/* etc etc etc */
}
}
My logic is entered num store into temp variable and find factorial using temp = temp * (num - i) inside while until num is greater than 0 and initially i = 1 , but I get problem that my loop goes in to infinite loop how to solve this problem ?
#include <stdio.h>
int main() {
int num, temp, i;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d", &num);
printf("num = %d\n", num);
temp = num;
printf("temp = %d\n", temp);
i = 1;
while (num > 0) {
temp = temp * (num - i);
i++;
printf(" i = %d\n ", i);
}
printf("fact = %d \n ", temp);
return 0;
}
Here you are checking num > 0 but never updating value of num inside the loop
Update it to check num - i > 0 or num > i
while(num - i > 0)
{
temp = temp * (num-i);
i++;
printf(" i = %d\n ",i);
}
while(num > 0)
{
num is never updated inside the loop, so num will always be > 0.What you want is
while((num-i) > 0)
i is updated in every run of the loop, so eventually num-i will become 0 and the loop will terminate.
while(num>0) was not updated. So You can use while((num-i)>0) for update loop.Try below C code.
#include <stdio.h>
int main(){
int num,temp,i;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d",&num);
printf("num = %d\n",num);
temp = num;
printf("temp = %d\n",temp);
i=1;
while((num - i) > 0){
temp = temp * (num-i);
i++;
printf(" i = %d\n ",i);
}
printf("fact = %d \n ",temp);
return 0;
}
You don't require an extra variable i. It is important that you should take care the time and space complexity of a program.
#include <stdio.h>
int main()
{
int num,temp;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d",&num);
printf("num = %d\n",num);
temp = 1;
while(num > 0)
{
printf(" num= %d\n ",num);
temp = temp * num;
num--;
}
printf("fact = %d \n ",temp);
return 0;
}
You never update num inside the body of the while (num > 0) loop, hence an infinite loop.
You should use a simpler method: a classic for loop with an index i incrementing from 1 to n inclusive. This way you do not modify the value of num and can use it for the final output:
#include <stdio.h>
int main(void) {
int num, res, i;
printf("Enter a number whose factorial to compute: ");
if (scanf("%d", &num) == 1) {
res = 1;
for (i = 1; i <= num; i++) {
res = res * i;
}
printf("%d! = %d\n", num, res);
}
return 0;
}
Notes:
the initial value of i could be changed to 2.
factorials grow very quickly: this program will only handle numbers from 0 to 12. Changing the type of res to unsigned long long will handle up to 20.
I'm writing a C program that counts the number of odd digits from user input.
Eg.
Please enter the number: 12345
countOddDigits(): 3
int countOddDigits(int num);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int num)
{
int result = 0, n;
while(num != 0){
n = num % 10;
if(n % 2 != 0){
result++;
}
n /= 10;
}
return result;
}
The code is not working.
Can someone tell me where does it go wrong?
There were a few mistakes in your code. Here is a working version of your code:
#include <stdio.h>
int countOddDigits(int n);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int n)
{
int result = 0;
while(n != 0){
if(n % 2 != 0)
result++;
n /= 10;
}
return result;
}
You are mixing n and num together - there is no need for two variables.
n%=10 is just causing mistakes - you need to check the last digit if(n%2!=0) and then move to the next one n/=10, that's all.
Looping variable is not correct. Your outer loop is
while (num !=0)
but the num variable is never decremented; the final statement decrements the n variable. My guess is you want to initialize
int n = num;
while (n != 0 )
{ ...
n/= 10;
}
Can anybody tell me where why the correct value of input is not being stored in this program?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sum=0;
printf("Enter the number: ");
while(num!=0)
{
sum = sum+num;
scanf("%d", &num);
}
printf("Answerr = %d", sum);
return 0;
}
Here's the output:
Enter the number: 2
0
Sum = 10
Better do:
num= 0;
do
{
scanf("%d", &num);
sum = sum+num;
} while(num!=0);
Note the initialization of num is still needed as scanf could fail which would not affect num.
You cannot know what exactly this part will do :
while (num != 0)
{
sum = sum + num;
scanf("%d", &num);
}
because num is not initialized, so you are adding to sum a value which you do not know. Change it to :
while(num != 0)
{
scanf("%d", &num);
sum = sum + num;
}
so that num has a value when you add it, and also initialize num to something different than 0, for example :
int num = 2;
so that your while loop is executed at least one (in other words, so that you get the chance to read num).
A better approach would be to use a do-while loop like this :
int num = 0;
do
{
scanf("%d", &num);
sum = sum + num;
}while (num != 0);
so as to be sure that your loop will be executed at least once. Even with this approach you should still initialize num in case scanf fails (and therefore num does not get a value).
In order to check the return value of scanf, use this piece of code :
if ( scanf("%d", &num) == 1)
sum = sum + num;
Change your code to:
int main()
{
int num = 0, sum = 0;
printf("Enter the number: ");
do
{
scanf_s("%d", &num);
sum = sum + num;
} while (num != 0);
printf("Answer = %d", sum);
return 0;
}
I replaced the whileloop with a do while one. You've to initialize sum, otherwise you'll work with an undefined value in your first run ( if working with a while loop).
you are adding value of num before reading it
do like this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, sum=0;
printf("Enter the number: ");
do{
scanf("%d", &num);
sum = sum+num;
}
while(num!=0);
printf("Answerr = %d", sum);
return 0;
}
The variable num was not initialized. As result the loop has undefined behavior. Also you should check whether the input was valid before adding values. Take into account that neither declaration from the header <stdlib.h> is used. So you may remove the header.
The program can look the following way
#include <stdio.h>
int main( void )
{
long long int sum = 0;
while ( 1 )
{
int num;
printf( "Enter number (0 - exit): " );
if ( scanf( "%d", &num) != 1 || num == 0 ) break;
sum += num;
}
printf( "\nAnswer = %lld\n", sum );
return 0;
}
Or you could place the prompt before the loop as for example
#include <stdio.h>
int main( void )
{
long long int sum = 0;
printf( "Enter numbers (0 - exit): " );
while ( 1 )
{
int num;
if ( scanf( "%d", &num) != 1 || num == 0 ) break;
sum += num;
}
printf( "\nAnswer = %lld\n", sum );
return 0;
}
And according to the C Standard function main without parameters shall be declared like
int main( void )