loop inside another loop what is wrong with this code - c

My input was
2
4
as I entered t as 2, it should run the the loop twice and accept one more integer but it replies
return 0
I am trying to get many different inputs and running second loop according to them but after first input program returns 0. I don't know why; please correct me
#include <stdio.h>
int main()
{
int t, i, n, sum = 0;
scanf("%d", &t);
for (i = 0; i < t; i++)
{
scanf("%d", &n);
for (i = 1; i < n; i = i + 2)
{
sum = sum + ((n - i + 1) * (n - i + 1));
}
printf("%d\n", sum);
}
return 0;
}

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.

i am using 4 for lopp , 2 are working correct rest 2 are showing issue 3 and 4 loop are showing invalid answer

i am using 4 for lopp , 2 are working correct rest 2 are showing issue 3 and 4 loop are showing invalid answer:
#include <stdio.h>
int main(void) {
// your code goes here
int n,arr[n],i,l=0,m=0,u=0,d=0;
printf("enter the value of n");
scanf("%d",&n);
arr[0]=0;
for(i=0;i<n;i++) {
arr[i+1]=arr[i]+10;
}
printf("%d",arr[3]);
for(i=1;i<=n;i=i+4) {
l=arr[i]+l;
}
for(i=2;i<=n;i=i+4) {
u=arr[i]+u;
}
for(i=3;i<=n;i=i+4) {
m=arr[i]+m;
}
/* for(i=4;i<=n;i=i+4) { d=arr[i]+d; } */
printf("\n%d\n",l);
printf("%d\n",u);
printf("%d\n",m);
printf("%d\n",d);
return 0;
}
answer in negative
Among the things wrong in this code
Your decl of arr[n] is based on an indeterminate n value. The array doesn't magically resize when you read n later in your program. n has to be known before the arr decl.
Your loop limits are potentially out of range (and definitely with the first loop).
The scanf call to populate n isn't checked for successful stdin input. Never assume your IO works, especially the 'I' in IO.
Just fixing those:
#include <stdio.h>
int main(void)
{
int n, i, l = 0, m = 0, u = 0, d = 0;
printf("enter the value of n");
if (scanf("%d", &n) == 1 && n > 0)
{
int arr[n];
arr[0] = 0;
for (i = 0; i<(n - 1); i++) {
arr[i + 1] = arr[i] + 10;
}
printf("%d", arr[3]);
for (i = 1; i < n; i += 4) {
l = arr[i] + l;
}
for (i = 2; i < n; i += 4) {
u = arr[i] + u;
}
for (i = 3; i < n; i += 4) {
m = arr[i] + m;
}
printf("\n%d\n", l);
printf("%d\n", u);
printf("%d\n", m);
printf("%d\n", d);
}
return 0;
}
See it live on ideone.com

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

C program to find the trailing ZEROS at the end of a FACTORIAL of a given number

I have return the code to find a factorial and to display trailing zeros at the end of the factorial, but the output is wrong... could you please help me to find the mistake?
#include <stdio.h>
int main() {
int m = 1, i, N, count = 0;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
m = m * i;
}
printf("%d", m);
while (m > 0) {
if ((m % 10) == 0) {
count = count + 1;
m = m / 10;
}
break;
}
printf("%d", count);
return 0;
}
Your code only works for very small values of N: up to 9. For slightly larger values, you would need to add an else keyword before the break statement and you would get a correct result for a few more cases.
For larger values, you must compute the power of 5 that divides the factorial. You can do this incrementally by summing the power of 5 that divide each individual number up to and including N.
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
/* only consider factors that are multiples of 5 */
count = 0;
for (int i = 5; i <= N; i += 5) {
for (int j = i; j % 5 == 0; j /= 5)
count++;
}
printf("%d\n", count);
return 0;
}
An even simpler and faster solution is this: compute the number of multiples of 5 less or equal to N, add the number of multiples of 5*5, etc.
Here is the code:
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
count = 0;
for (int i = N; (i /= 5) > 0;) {
count += i;
}
printf("%d\n", count);
return 0;
}
you have two problems
your collapse the two outputs so you see only one of them / you cannot see who is who, just add a separator between them
an else is missing when you count so you count to only up to 1 and the result is wrong from factorial 10
So the minimal changes produce :
int main()
{
int m=1,i,N,count=0;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
m=m*i;
}
printf("%d\n",m); /* <<< added \n */
while(m>0)
{
if((m%10)==0)
{
count=count+1;
m=m/10;
}
else /* <<< added else */
break;
}
printf("%d\n",count); /* <<< added \n */
return 0;
}
after the changes :
pi#raspberrypi:/tmp $ ./a.out
5
120
1
pi#raspberrypi:/tmp $ ./a.out
10
3628800
2
Of course that supposes first you are able to compute the factorial without overflow
I also encourage you to check a value was read by scanf, checking it returns 1
#include <stdio.h>
int main()
{
int n,i,f=1,t,c=0;
printf("Enter number ");
scanf("%d",&n);
t=n;
for(i=1;t>=5;i++)
{
t=n/5;
c=c+t;
n=t;
}
printf("number of zeros are %d",c);
return 0;
}

Trying to create a program that calculates the series 𝑆 = 1^2 - 2^2 + 3^2

#include <stdio.h>
int main()
{
int i; //counter for the loop
int n; //integer
int series;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}
So the the loop is just a basic for loop, using I as the counter for as long as it is less than or equal to n
the series that I have to replicate adds odd numbers and subtracts even numbers so the if condition tests if the number is even or odd. The program compiles fine but when I enter the integer as 5 the sum of the series should be 15, however my program gives the sum 32779. Any help on fixing my program would be appreciated.
you didn't initialize series, so it's a random value in the beginning of the calculation.
#include <stdio.h>
int main()
{
int i = 0; //counter for the loop
int n = 0; //integer
int series = 0;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}

Resources