How to reset number to 0 after running program once again - c

I'm making program which converts sum of the numbers entered by user to binary, octal and hexadecimal. I would like to give a user an option to run program once again but with different numbers. Here is the problem - each time user repeats numbers, sum of these numbers are added to the previous entry. How do I stop incrementing? Is there any way to reset sum to 0? Thank you so much for your help!

Is there any way to reset sum to 0?
Yes, set sum to 0 right before the inner loop.
sum = 0;
while(1)
{
printf("Enter number: ");
scanf("%d", &value);
sum += value;
if(value == 0)break;
}
Also, rather then using while (1) with a break condition at the end, use a do..while loop.
sum = 0;
do {
printf("Enter number: ");
scanf("%d", &value);
sum += value;
} while (value != 0);

You would simply need to reset your sum variable to 0 if the user wants to reuse the number system with other numbers -
printf("\nEnter numbers once again? (y/n)\n");
scanf(" %c", &j);
printf("\n\nENTERING ONCE AGAIN\n");
if(j == 'n'||j == 'N')break;
***else sum = 0***

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...

A question about break statement in c programming

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;

Another way to terminate loop?

I'm studying loops in class and for one of the labs, I have to figure out a way for the user to enter an unspecified number of integers to calculate the average. I know I can have the user enter the number of integers to be averaged in order for the loop to be terminated like below:
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
So basically I could have a user input the number of integers to be averaged in order for the loop to terminate, but there has to be another way to make the loop terminate without having the user input it?
Normally you'd use a predetermined "illegal" number like (say -1)
input = read_a_value();
while(input != -1)
{
// do something with input
input = read_a_value();
}
scanf returns the number of successful entries.
This may solve your issue.
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
A downfall is that the scanf will continue to prompt for input if a user presses the Enter Key repeatedly. In fact you might wish to replace the scanf with fgets. Have a look here.
If you are sure that the user doesn't enter too many numbers, use a string.
Length of string, you can choose according to you and split it using spaces to get the numbers

Adding integers in a do-while statement

I have to write a do while loop that reads integers and computes their sum. It continues to add the integers until the user enters -1, but the -1 should not be added to the sum.
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf(" %d", &n);
sum = sum + n;
printf("The sum is %d\n", sum);
}
while (n >= 0);
{
return 0;
printf("Have a nice day!\n");
}
Where am I going wrong? How do I get the -1 to avoid being added to the sum?
You need to declare n, i before use. And you need a break when detecting input -1.
int sum = 0, n = 0;
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf("%d", &n);
if( -1 == n )
break; // <-- break here to get out the loop
sum = sum + n;
printf("The sum is %d\n", sum);
} while (1); // <-- note while(1) should be used instead of while(n >= 0), this makes sure your loop only exits when detecting input -1
Also there's no point adding a printf after you return - ie this code can be removed:
{
return 0;
printf("Have a nice day!\n"); // <-- any code after `return` is meaningless
}
There are a couple of ways to avoid having -1 added to the sum. Let's look at your code, first:
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf(" %d", &n);
sum = sum + n;
printf("The sum is %d\n", sum);
}
while (n >= 0);
The do/while loop will exit if n is less than zero. This is one way to catch the -1 as a sentinel value, so no problem there.
Unfortunately, your code reads the number, adds it to the total, and then checks if it should stop. With that order, you always add before checking.
The most obvious, brute-force way to avoid adding the number is to add an explicit check:
do {
printf ... scanf ... ;
if (n != -1)
sum = sum + n;
} while (n >= 0);
Another way is to cheat. Given that -1 always comes at the end of the list, just undo that at the end:
do {
printf... scanf...;
sum = sum + n;
} while (n >= 0);
sum = sum - n; // CHEAT - just subtract out the last number
printf("The sum is %d\n", sum);
Finally, there is a trick you can use. Sometimes in these situations, you can "shift" the loop, so that you actually do things slightly out of order. In this case, you would like to test before you add. So put the add at the top of the loop, and just set things up so that the very first add is harmless:
n = 0; // X + 0 is X, so adding 0 is harmless.
do {
sum = sum + n;
printf ... scanf ...;
} while (n >= 0);
This may make you uncomfortable for a minute, but it's an idiom you'll see a lot. The loop code has been "twisted" inside the loop, so that the top of the "natural" loop does not start at the top of the actual loop body. It's a good trick to know.
The behavior of your do-while loop will be clearer if you think of it in terms of the GOTOs the compiler sees it as:
// prior code before here...
START_OF_DO:
printf("Enter a number. Enter -1 to stop\n");
scanf(" %d", &n);
sum = sum + n;
printf("The sum is %d\n", sum);
if ( n >= 0 ) {
goto START_OF_DO; // this is what "while (n >= 0);" does
}
return 0;
printf("Have a nice day!\n"); // <-- note that this will never print, because you have already returned
Formed this way, you can see that your sum = sum + n happens before you check if ( n >= 0).
(note I am not suggesting that you ever use goto! But sometimes it's helpful to see these things in terms of the machine instructions the compiler emits.)
You're overwriting the value of n before it checks the condition to run the loop again.
Make these changes and it should work now.
int input = 0; // Change
int n = 0; // Change
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf(" %d", &input); // Change
if(input >=0 ) // Change
{
n = input; // Change
sum = sum + n;
printf("The sum is %d\n", sum);
}
}
while (input != -1); // Change
{
return 0;
printf("Have a nice day!\n");
}

While loop to repeat a series of task multiple times in C program

I am writing a C program to repeat a series of question specified times. I ask user to enter the number of attempts they want and then I run the following while loop based on their number, but the problem is the loop keeps repeating. It does not stop at the specified number of attempt. Here is the code:
#include <stdio.h>
int main(void){
int num1,num2,high,low,average,subtotal,total_aver;
printf("Enter number of tries you want:");
scanf("%d", &num1);
while (num1 < num1 + 1) {
printf("Try number: ");
scanf("%d", &num2);
printf("Enter high ");
scanf("%d", &high);
printf("Enter low ");
scanf("%d", &low);
subtotal = high + low;
total_aver = subtotal / 2;
printf("Average temperature is: %d", total_aver);
}
}
If user enters 3 for number of tries then the program should ask those question in inside the loop three times, but it keeps repeating without ending.
while (num1 < num1 + 1) // condition is never false
Well this is infinite loop . It will continue and continue.
Write loop like this if you want to iterate number of times -
int i=0;
while(i<num1){
// your code
i++;
}
Or without any extra variable -
while(num1>0){
// your code
num1--;
}
This happens because the condition in the while is wrong.
Infact, assigning to num1 to any value, it will exit when num1 will be equal to num1+1. Is this impossibile, isn't it? You have to use another variable to take count of times you repeat the loop.
Fix this way:
int count=0;
while(count<num+1){
//your code
count=count+1;
}

Resources