How do i get sum to work? - c

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

Related

Swapping elements from an array that are prime numbers

I need to input my own array and give its own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example:
My array: 4 6 3 5 7 11 13
The new array: 4 6 5 3 11 7 13
Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same.
#include <stdio.h>
#define array 100
int prime(int b
)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return b; // not prime
}
break;
}
return b;
}
int main()
{
int n, i, a[array];
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]))
{
int temp;
temp = prime(a[i]);
prime(a[i]) == prime(a[i + 1]);
}
}
printf("\nThe new array is:\n");
printf("%d ", prime(a[i]));
return 0;
}
I haven't learned pointers so is there a way without it or?
there are few things needs to modify
need to change function prime return type to bool. since we are interest to check if array element is Prime. if array element is Prime, return True
int prime(int b)
changed to
bool prime(int b)
also need to extend check if prime() function return true and if array index is not last element then only swap array element to next, else skip
if (prime(a[i]) == 1 && a[i-1] != n)
prost(a[i]) looks typo (I guess). corrected to a[i + 1]
this is not optimized code, it just modified version of your code. if you have concern specific performance, please follow suggestion mentioned by
chux - Reinstate Monica
code:
#include <stdbool.h>
#include <stdio.h>
#define array 100
bool prime(int b)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return false; // not prime
}
break;
}
return true;
}
int main()
{
int n, i, a[array];
int temp;
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]) == 1 && a[i] != a[n-1]) /* enter loop only array element is Prime number and it is not last element */
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
a[i++];
}
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output for above code: check out this link
How many elements does the array have?
7
Put in 7 elements from the array!
4
6
3
5
7
11
13
My array is:
4 6 3 5 7 11 13
The new array is:
4 6 5 3 11 7 13
...Program finished with exit code 0
Press ENTER to exit console.
First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.

Sum of digits with test cases in 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.

Looking for the sum of factors equal to the number of oneself

I'm trying to finish my homework, while there is something trapped me.
Here the question:
In the range of N, output those numbers whose factors sum is equal to themselves according to the following format.
Input:
1000
output:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
Here my code, please tell me why can't i get the right output. Appreciate it if
you can improve it for me.
Thanks in advance.
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
Making the same a little clean,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
Modifications retaining your code:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
I have made modifications in your code and corrected/commented where you have made mistakes.

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

How to print this series?(1 \n 2 3 \n 4 5 6 \n 7 8 9 10... ... ...)

I am trying to print the following series: 1 2 3 4 5 6 7 8 9 10 ... ... ...The input of my program contains a single integer n, which determines the number of lines to print.
I've tried to code it but got the following output:
12 33 4 54 5 6 7... ... ...
#include<stdio.h>
int main()
{
int n,i,j,t,m;
scanf("%d", &n);
for(i=1;i<=n;i++)
{
for(j=i,t=1;t<=i;j++,t++)
{
printf("%d ",j);
}
printf("\n");
}
}
To print those numbers, you'll want a counter that starts at 1, increases by 1 every print and is never reset by anything. Adjust your loop like this:
int main()
{
int n, i, j, t = 1;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++, t++)
{
printf("%d ", t);
}
printf("\n");
}
}
Note how t is set to 1, and just gets increased by t++ without resetting like you previously did. Also, you should be printing t, not j.
You should maintain separate counters for the numbers and the number of numbers per line.
int nr = 1, target;
int nrsperline = 1, i;
scanf("%d", &target);
while (nr <= target) {
for (i = 0; i < nrsperline; i++) {
printf("%d ", nr++);
}
printf("\n");
nrsperline++;
}

Resources