Can you help me with this code in c?

I want to calculate the sum of n numbers that I enter but when i am asked to enter the n numbers, it puts me to enter one more of the n numbers that i just entered, what is happening?


#include<stdio.h>

int main(){
		int i,n,sum=0;
		int numbers;
	
    printf("enter the amount of numbers: ");
	scanf("%i",&n);
		
	for(i<=1;i<=n;i++){
		 printf("enter the numbers: ");
		scanf("%i",&numbers);
      
         sum=sum+numbers;

	}

	printf("the sum is: %i",sum); 
	
	return 0;
}

Look closely at your for loop statement, especially the test expression. You have a classic fence post error.

Also, your initialization statement isn’t initializing anything.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.

markdown_Forums

1 Like

Your loop head is malformed.

for (i <= 1; i <= n; i++)

The initialization statement i <= 1 is just performing the logical test to see if i is less than or equal to 1. You need to actually assign an initial value to i.

As a side note, it is typical to start an 0 and continue while your iterator is less than the bound, rather than starting at 1 and continuing until your iterator is less than or equal to the bound.

You can learn more about loops in C/C++, with examples, here:
https://en.cppreference.com/w/cpp/language/for

i see, big mistake, i didn’t notice it
Thank you so much

1 Like