C loop until 0 is given - c

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);
}

Related

Find two largest numbers in input

I need to make a program that will perform the following task:
Enter N natural numbers. Complete the input with 0. Output the number
of the maximal number.
I have already done this, and you can see the code below:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num >= max) {
max = num;
max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place + 1);
return 0;
}
The teacher then made the task more difficult – the program needs to print the maximum number and the next maximum after it of the entered numbers.
How can I do it?
If you can use arrays and sort use that way. if not, this is in your code
int main(void) {
int i = 0, num, max_place = -1, second_max_place = -1;
int max = -2147483647;
int second_max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num == 0) break;
if (num >= max) {
second_max = max;
second_max_place = max_place;
max = num;
max_place = i;
}
if(num < max && num >= second_max){
second_max = num;
second_max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else{
printf("\nMax number was on %d place, bruh", max_place + 1);
printf("\nSecond Max number was on %d place, bruh", second_max_place + 1);
}
return 0;
}

Adding values based on the user's input in array basis

I'm stuck with this code:
int main()
{
int a[ ] = {0};
int n,sum = 0;
printf("Enter your element: ");
scanf("%d", &a[n]);
while(n != -1)
{
sum = sum + a[n];
printf("Enter your element: ");
scanf("%d", &n);
}
printf("The sum is %d", sum);
}
My aim is to make a prompt to user to enter his value that will be stored in the elements of the array, then give him the sum of the values that he entered.
However the code does not show any error, but it ends up giving garbage value.
You probably want this:
#include <stdio.h>
int main()
{
int a[100] = { 0 }; // array of 100 numbers all initialized to 0
int sum = 0;
int n = 0;
do
{
printf("Enter your element: ");
int number;
scanf("%d", &number);
if (number == -1)
break;
a[n] = number;
sum += a[n];
n++;
}
while (1);
printf("The sum is %d", sum);
}
Disclaimer: There is no error checking, and there is no check if you entewr more than 100 numbers which results in an index out of range problem.
scanf("%d", &a[n]); accessing array index out of bound if n!=0 this is Undefined Behavior.
And n is uninitialized. So using that as an index is using as index in the array some indeterminate value.
while(n!=1) is not an exhaustive check. better would be n==0 as the array has only 1 element.
Maybe you wanted this
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter no of element: ");
if( scanf("%d", &n) != 1){
fprintf(stderr,"%s","Error in input");
exit(1);
}
if( n <= 0){
fprintf(stderr,"Enter positive number of elements");
exit(1);
}
int a[n];
int sum = 0;
for(size_t i = 0; i < n; i++){
if( scanf("%d",&a[i]) != 1){
fprintf(stderr,"%s","Error in input: give integers");
exit(1);
}
sum+=a[i];
}
printf("The sum is %d", sum);
}
Notice that this program has the following flaws which is difficult to overcome with scanf() - you can try to modify over this using strtol and overflow-checking
If user inputs something other than this range [INT_MIN,INT_MAX], thre will be overflow. (Soln: Use strtol)
Sum can overflow given any large inputs whose sum is not in this range.
(Overflow check:
if ((a[i] > 0 && sum > INT_MAX - a[i]) || (a[i] < 0 && sum < INT_MIN - a[i]))
{
fprintf(stderr,"%s","Sum has overflown");
exit(1);
}

Program C counting total number of odd digits

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;
}

Simple C program is not storing the correct value of the input taken in the variable

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 )

C FOR Condition

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;
}

Resources