Sum of digits with test cases in C - c

I am trying to find the sum of digits with test cases. But the problem is after I find one sum, this sum is adding to the next sum but I only one particular sum of that numbers' digit. Please help. Here is my code:
#include <stdio.h>
int main() {
int t, n, i, r, sum=0;
scanf("%d", &t);
for(i=0; i<t; i++) {
scanf("%d", &n);
while(n>0) {
r = n % 10;
sum = sum + r;
n = n / 10;
}
printf("%d\n", sum);
}
return 0;
}
And Here is my output:
3
1234
10
2347
26
8744
49
Why my previous sum adding to the next sum? I am not understanding.
My desired output:
3
1234
10
2347
16
8744
23

Problem:
Your variable sum is set to 0 on the start of the program and you are adding the sum of each test case in the same variable without cleaning the result of the previous test case (by setting sum = 0 before the next test case starts.)
Possible Solution:
Initialize your your variable sum before a test case starts.
Code:
for(i=0; i<t; i++)
{
scanf("%d", &n);
sum = 0; //Set sum = 0
//Test Case started in while loop
while(n>0) {
r = n % 10;
sum = sum + r;
n = n / 10;
}
printf("%d\n", sum);
}

In the begining of your loop set sum to 0. So that before taking sum over next set of elements it is reinitialized to zero.
for(i=0; i<t; i++)
{
sum = 0;
scanf("%d", &n);

You need to set your sum=0; on the first line of the for loop.

Related

Program to print sum of primes in C

#include <stdio.h>
#include <math.h>
int main() {
int n, count, sum;
printf("Enter upper bound n \n");
scanf("%d", &n);
for (int a = 1; a <= n; a++) {
count = 0;
sum = 0;
for (int i = 2; i <= sqrt(a); ++i) {
if (a % i == 0) {
count++;
break;
}
}
if (count == 0 && a != 1) {
sum = a + sum;
}
}
printf("%d", sum);
}
The program is my attempt to print summation of primes < n. I am getting sum = 0 every time and I am unable to fix this issue.
The reason you do not get the sum of primes is you reset the value of sum to 0 at the beginning of each iteration. sum will be 0 or the value of the n if n happens to be prime.
Note also that you should not use floating point functions in integer computations: i <= sqrt(a) should be changed to i * i <= a.
The test on a != 1 can be removed if you start the loop at a = 2.
Here is a modified version:
#include <stdio.h>
int main() {
int n = 0, sum = 0;
printf("Enter upper bound n: \n");
scanf("%d", &n);
// special case 2
if (n >= 2) {
sum += 2;
}
// only test odd numbers and divisors
for (int a = 3; a <= n; a += 2) {
sum += a;
for (int i = 3; i * i <= a; i += 2) {
if (a % i == 0) {
sum -= a;
break;
}
}
}
printf("%d\n", sum);
return 0;
}
For large values of n, a much more efficient approach would use an array and perform a Sieve of Eratosthenes, a remarkable greek polymath, chief librarian of the Library of Alexandria who was the first to compute the circumference of the earth, 2300 years ago.
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int n = 0;
long long sum = 0;
if (argc > 1) {
sscanf(argv[1], "%i", &n);
} else {
printf("Enter upper bound n: \n");
scanf("%i", &n);
}
// special case 2
if (n >= 2) {
sum += 2;
}
unsigned char *p = calloc(n, 1);
for (int a = 3; a * a <= n; a += 2) {
for (int b = a * a; b < n; b += a + a) {
p[b] = 1;
}
}
for (int b = 3; b < n; b += 2) {
sum += p[b] * b;
}
free(p);
printf("%lld\n", sum);
return 0;
}
Error about sum getting set to zero inside the loop has been already pointed out in previous answers
In current form also, your code will not return zero always. It will return zero if value of upper bound is given as non prime number. If prime number is given as upper bound, it will return that number itself as sum.
As mentioned in comment you should initialize sum before first loop something like
int n, count, sum=0;
or you can initialize sum in the loop like
for(a=1,sum=0;a <= n; a++)
and remove sum=0; inside the first loop because it changes sum to 0 every time first loop executes. You can check this by inserting this lines to your code
printf("Before sum %d",sum);
sum = 0;
printf("After Sum %d",sum);
make sure sure that if you are initializing sum in the loop, define "a" in outer of the loop if not the sum goes to local variable to for loop and it hides the outer sum.

How can I make a function and get cumulative sum of previous numbers?

What I want to do is to get a cumulative sum of previous integers starting from 1, for example:
If my input is 4, then the function should work in this way;
1 + (1+2) + (1+2+3) + (1+2+3+4) = 20.
And the output needs to be 20. Also, I have to get this done by a function, not in main(); function while using int n as the only variable.
What I've tried is to make a function which adds from 1 to integer N, and use 'for'to make N start from 1, so that it can fully add the whole numbers until it reaches N.
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
sum = 0;
scanf("%d", &n);
for (n = 0; n <= input; n++) {
sum += n;
}
printf("%d", sum);
return 0;
}
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
What I expected when the input is 4 is 20, but the actual output is 10.
I would have written it this way, remarks are where changes been made
#include <stdio.h>
int sum(int n);
int main() {
int n, input, sum;
// sum = 0; // no need for this
scanf("%d", &n);
/* the next for has no use
for (n = 0; n <= input; n++) {
sum += n;
} */
// I would be adding some input sanitazing if possible here
printf("%d", sum(n));
return 0;
}
int sum(int n) {
int i, /*n, */ rsum = 0; // n is already a parameter, rsum for running sum
// scanf("%d", &n); // nope nope, scanf and printf should be avoided in functions
for (i = 1; i <= n; i++){ // changed i +=1 with i++ , easier to read
for (j=1;j<=i;j++) // need this other loop inside
rsum += j;
}
return rsum;
}
Here it is with a single loop; very fast.
#include <stdio.h>
int cumulative_sum(int m)
{
int sum = 0;
for(int n=1; n<=m; ++n) sum += n*(n+1);
return sum/2;
}
int main(void)
{
int n;
printf("Input value N: ");
scanf("%d", &n);
printf("Answer is %d\n", cumulative_sum(n));
return 0;
}
The main issue is in the function, you are doing only 1 loop (you have also some logical things, which compiler should tell you, like same naming of variable and function.. eg.),
so in case you will put 4 as the input, loop will do only 1+2+3+4, but your case if different, you want to make suma of all iterations like 1 + (1+2) + (1+2+3) + (1+2+3+4)
you are doing only last step basically (1+2+3+4), 4 iterations (4x suma), but actually you need 10 iterations (due suma of all particular suma of elements)
As suggested, try to debug your code - What is a debugger and how can it help me diagnose problems?
- it will really help you do understand your code
As mentioned, the issue is in
int sum(int n) {
int i, n, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i += 1){
sum += i;
}
return n;
}
You have to make two loops eg. like follows:
int sum,n = 0;
//scanf("%d", &n);
n = 4; //input simulation
//just for demonstration
int iterations = 0;
//counter for total loops (how many "brackets" needs to be count)
for(int loopsCounter = 1; loopsCounter <= n;loopsCounter++){
//counter for child elements in brackets (like 1+2 ,1+2+3, ..)
for (int sumaLoopCounter = 1; sumaLoopCounter <= loopsCounter; sumaLoopCounter++){
//simply make sum with the given number
/* first step 0 +1
second 1+2 added to previous suma = 1+3
third 1+2+3,.. added to previous = 4+6
...
*/
sum += sumaLoopCounter;
//just testing for demonstration
iterations++; //iterations = iterations + 1
}
}
printf("%i \n",iterations);
printf("%i",sum);
Then you got output as expected - sum of all "bracket elements" and 10 iterations, which matches numbers of needed additions
10
20

Array additions and averages

So this weeks homework is to: 'Write a program that inputs 6 integers and puts them into an Array. The program
then prints out the following: A list of all Array elements, from 0 to 5 and the sum and
mean value of all elements. NB The mean value of the array elements will not
necessarily be an integer. In order to convert an integer into a real (float) use
casting:
To turn the integer ‘x’ into a float use float(x)
E.g.:
Average = float(sum)/number of elements ;
(In this case the number of elements is 6)'
Not quite sure what I am doing wrong here but my code seems to give back incorrect answers and I can't figure out why.
Any suggestions would be greatly appreciated. I feel like I am going to fail this module as I have struggled with it since the introduction of functions, etc.
Anyway, here is my code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main() {
int numArr[5];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + i;
}
avg = sum /6;
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
'Write a program that inputs 6 integers
int numArr[5];
^^^^^
Change this loop
for (i = 0; i < 6; i++) {
sum = sum + i;
}
like
for (i = 0; i < 6; i++) {
sum = sum + numArr[I];
}
And change this statement
avg = sum /6;
the following way
avg = ( float )sum /6;
And you forgot to output all elements of the array.
Take into account that according to the C Standard the function main without parameters shall be declared like
int main( void )
and you may remove header <math.h> because neither declaration is used from this header in your program.
Your array isn't large enough to hold 6 numbers.
Change
int numArr[5];
to
int numArr[6];
Currently, you are accessing the array out-of-bunds, resulting in undefined behaviour.
There are couple other problems too:
1) You are not summing the array elements
2) You are doing integer division
Fix it, it'd look like:
#include<stdio.h>
#include<math.h>
int main(void) {
int numArr[6];
int i, sum = 0;
float avg;
printf("\nEnter 6 elements : \n");
for (i = 0; i < 6; i++)
scanf("%d", &numArr[i]);
for (i = 0; i < 6; i++) {
sum = sum + numArr[i]; /* was summing `i` instead of numArr[i] */
}
avg = sum /6.0; /* was doing integer division */
printf("The sum is : %d", sum);
printf("The mean value is : %f", avg);
return 0;
}
sum = sum + i;
should be
sum = sum + numArr[i];
Array elements should be added.
Later
avg = sum/6.0
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
avg = (float)sum /6;
Notice numArr[i]
int numArr[5];
should be
int numArr[6];
and
for (i = 0; i < 6; i++) {
sum = sum + i;
}
should be
for (i = 0; i < 6; i++) {
sum = sum + numArr[i];
}
and
avg = sum /6;
should be
avg = sum/6.0 //because division of integer by an integer results by integer value. So we divide integer with a float (6.0) value

How do i get sum to work?

I wrote a function to compute and it should also return the sum. However sum is not working fine.
Output:
Enter how many numbers to print : 7
0 1 1 2 3 5 8
Sum of series is: 31
Sum should be 20
Code:
#include<stdio.h>
void f(int num)
{
int k,count;
int sum=0;
int i = 0;
int j = 1;
printf("%d %d ",i,j);
count = 2; /* count is 2 because we already printed 0 and 1*/
k = i + j;
while(count < num)
{
printf("%d ",k);
i = j;
j = k;
k = i+j;
sum+=k;
count++;
}
printf("\n");
printf("Sum of F series is: %d",sum);
return;
}
int main()
{
int num;
printf("Enter how many numbers to print : ");
fflush(stdout);
scanf("%d",&num);
f(num);
return 0;
}
Any help would be greatly appreciated
Two changes to be done -
1. Initialize sum to 1 -
int sum=1; //as you don't include 0 and 1 in loop
2. Change the position of sum+=k; statement -
printf("%d ",k);
sum+=k;
Because right now in your code -
k = i+j;
sum+=k;
k is being changed(which is incorrect) before it is added to sum, leading to incorrect answer.
Demo

Finding Divisors using loops

I wrote the code for the following program but I don't understand how I can involve a function. The question asks me to use a function that returns the sum of divisors. Please take a look at the question and my code and try to help me out.
THE QUESTION:
Write a C program that finds and prints the sum of divisors for all
the numbers between 101 and 110. The divisors of x are those numbers
x divides without a remainder (e.g. the divisors of number 10 are 1,
2, 5, and 10 and their sum = 1+2+5+10=18, the divisors of number 11
are 1 and 11 and their sum=1+11=12, and so forth).
Your program should also print the number (101 to 110) that has the maximum sum of divisors.
Your program should use at least one function called div_sum that
takes a number and returns its sum of divisors.
MY CODE:
#include <iostream>
#include <stdio.h>
int main()
{
int i=1, x=101, sum, smax=0, xmax=0;
for (x=101; x<=110; x++)
{ sum=0;
for(i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}
if(sum>smax)
{
smax=sum;
xmax=x;
}
printf("The sum of factors of %d = %d\n",x,sum);
}
printf("The number that has the maximum sum of divisors is %d with the sum of %d",xmax,smax);
return 0;
}
You can move the loop where you calculate sum of divisors for each x to separate function:
int div_sum(int x) {
int sum = 0;
for(int i=1; i<=x; i++)
{
if(x%i==0)
sum+=i;
}
return sum;
}
and use it in your program:
for (x=101; x<=110; x++)
{
sum= div_sum(x);
if(sum > amax)
...
}
For each number in the loop, call the function. The function should have all the code you currently have in the loop.
Your code is actually really close.
Here's what I did:
void div_sum()
{
int sum;
int max_sum = 0;
int max_num;
for (int x = 101; x <= 110; x++)
{
sum = 0;
for (int i = 1; i <= x; i++)
if (x%i == 0)
sum = sum + i;
printf("\nFor the number %d, the sum of the divisors is %d\n", x, sum);
if (sum > max_sum)
{
max_sum = sum;
max_num = x;
}
}
printf("max = %d\n", max_num);
}

Resources