how can I get the desired output? - c

I tried using the for loop for the test cases as I thought that would bring the desired output but it didn't
int main()
{
int num, temp, digit, sum = 0;
int test,i;
scanf("%d",&test);
for(i=1;i<=test;i++)
{
printf("\n");
scanf("%d", &num);
temp = num;
while (num != 0)
{
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("%d",sum);
}
return 0;
}
Expected results- 2 123 456
Output- 6 15
Obtained Results- 2 123 456
Output- 6 21
The first output is correct but at the second print it is summing up the first result with the second line which I don't want.

You never clear sum after processing 123. You are calculating the correct sum (15) but it is being added to the sum from the previous step (6). To fix the problem clear sum inside the for loop.
for(i=1;i<=test;i++)
{
sum = 0;
printf("\n");

Related

Why this function gives me first sums correct and then prints bad sums

Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }

How to store a value of a variable and update it's value inside a loop in C language?

I am new to programming in C and I am doing some activities for my first year in CS. The following activity consists of calculating the sum of squares of the digits of a user input number and the output should be as follows:
Number: 1234
  n=1234; sum=16
  n=123; sum=25
  n=12; sum=29
  n=1; sum=30
Result: 30
I have got it for the most part, the thing that I don't understand is how to store a value in a variable, update said variable and print the result, all whilst being inside a loop.
This is what I came up with:
int main() {
int num,i,sum=0,result,square;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
i=0;
while(num>i)
{
sum=num%10;
square=sum*sum;
printf("\nn=%d; sum= %d",num,square);
num=num/10;
}
result=sum;
printf("\nResult: %d",sum);
return 0;
}
How can I sum the square of the digits all together and print them as the example given?
Write something like the following
int digit = num % 10;
square = digit * digit;
sum += square;
printf("\n=%d; sum= %d", num, sum );
Pay attention to that the variable i is redundant:
i=0;
while(num>i)
just write
while ( num != 0 )
Also introducing the variable result is redundant and does not make sense because it is used nowhere.
You need a variable, keeping track of the input number (num), a variable keeping track of the sum ('sum') and a variable with the current digit (digit). Every iteration, you can calculate the digit, square it and add it to the sum. The a += b operation is equivalent to a = a + b, in case you are wondering. The same is for a /= b. Also a concept you can use (but don't have to), is implicit boolean conversion. When using a comparison (like num != 0 or num > 0) you can replace it with the number itself. In C, 0 equals false and everything else equals true.
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Calculate the sum of the square of the digits of a number\n" );
printf("Number:");
scanf("%d", &num);
while (num) { // is equal to num != 0
int digit = num % 10;
sum += digit * digit;
printf(" n=%d; sum= %d\n", num, sum);
num /= 10;
}
printf("Result: %d\n", sum);
return 0;
}
EDIT:
Some people prefer to use num != 0 or num > 0, because it is more readable. You should stick to it too for the start, until you are paid to confuse your coworkers.

How should I modify my code to not get output as 0?

This is a code for input-output practice. I am getting the correct output for the first two input lines. But I am getting a zero for the third line input.
The given task is: To calculate the sum of some integers.
Input:
4 1 2 3 4
5 1 2 3 4 5
0
Output:
10
15
#include<stdio.h>
int main()
{
int i, first, next, total;
while(scanf("%d", &first) != EOF)
{
total = 0;
for(i = 1; i <= first; i++)
{
scanf("%d", &next);
total += next;
}
printf("%d\n", total);
if(first == 0)
{
printf(" ");
}
}
return 0;
}
If you do not want output when the first number on a line is zero, then you should test first == 0 before calculating and printing a total and break from the loop (break; if you want to stop the loop) or continue to the next iteration (continue;).

Average value of numbers from N to 1000 (included), without even numbers which are divisible by 6 and 17

First I have to input N, N becomes the first number to be checked.
Input: 79
Output should be: 537.70.
int sum=0;
while(1)
{
scanf("%d", &n);
if(n>=10 && n<80)
{
break;
}
printf("New output:\n");
}
for(i=n;i<=1000;i++)
{
if(i%2==0 && i%6!=0 && i%17!=0)
{
sum+=i;
}
I didnt put (float)sum/N to get average because I'm doing something wrong with sum.
More input output:
Input: 10 Output: 505.21
Input: 44 Output: 521.18
As well as keeping a 'running sum', you also need to keep a count of how many numbers were used, so you can properly calculate the average:
#include <stdio.h>
int main(void)
{
int n;
printf("Enter start number: ");
scanf("%d", &n);
int sum = 0, count = 0;
for (int i = n; i <= 1000; ++i) {
if (!(i % 2) && (i % 6) && (i % 17)) {
sum += i;
++count;
}
}
printf("Average is: %.2f\n", (double)sum / (double)count);
return 0;
}
Input: 79
Output should be: 537.70.
Are you sure about this value? I get 538.70 - but I get the given values for the other test cases you cite.

function_tester.exe has stopped working

In this file I am trying to make something that adds all numbers up to a number entered by a user. Such as, 4: 1 + 2 + 3 + 4 = 10. So if they enter 4 it returns 10.
When I run the code I get an error message saying my file has stopped working. Do i have an endless loop?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
Yes, you have an infinite loop. Also the input is not stored in the num variable.
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
Some lines of your code seem odd to me.
Why do you use a while loop to test the value of num ?
Why do you put a continue statement as last while loop instruction ?
Remarks:
Your code does not work for negative number, is it the expected behaviour?
You are not testing the scanf return value, which could cause trouble.
I am pretty sure that you should check the scanf prototype.
Hope these questions will lead you to improve your code.
Thank you yadras fro informing me that I had the scanf outside of the while loop that was the problem and now it works when I do this.
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}

Resources