Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Infinite loop c program?

I have written a code for adding odd number, but it after i execute it, it doesn’t respond after I enter the limit of the sum.
I think that the loop is infinite but cant figure out where I’m wrong

#include<stdio.h>
int main()
{
int n, sum=0;
printf("Enter the limit of sum ");
scanf("%d ", &n);

for(int i=1 ; i<n ; i++)
{
    if(i%2==1)
       { sum=sum+i;}
}
printf("Sum of odd nos from 1 to n is%d\n", sum);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the scanf() function, remove the space after the %d.

scanf("%d", &n);

by the way, if you’re trying to count odd numbers between 1 and n, once you find an odd number you’ll probably want to increase "sum" by 1, not by i.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading