Code: Select all
// Sum of first n integer using loop
#include <stdio.h>
int main()
{
int a,s=0,i;
scanf("%d \n",a);
for(i=0;s<=a;i++) //try to do this using only 2 VARIABLES
s=s+i;
printf("the sum is: \t %d",s);
return 0;
}
Moderators:Labib, bristy1588
Code: Select all
// Sum of first n integer using loop
#include <stdio.h>
int main()
{
int a,s=0,i;
scanf("%d \n",a);
for(i=0;s<=a;i++) //try to do this using only 2 VARIABLES
s=s+i;
printf("the sum is: \t %d",s);
return 0;
}
Try this:rakeen wrote:Code: Select all
// Sum of first n integer using loop #include <stdio.h> int main() { int a,s=0,i; scanf("%d \n",a); for(i=0;s<=a;i++) //try to do this using only 2 VARIABLES s=s+i; printf("the sum is: \t %d",s); return 0; }
Code: Select all
// Sum of first n integer using loop
#include <stdio.h>
int main()
{
int a,s=0,i;
scanf("%d \n",&a);
for(i=0;i<=a;i++) //try to do this using only 2 VARIABLES
//I modified the line above
s=s+i;
printf("the sum is: \t %d",s);
return 0;
}
There are actually two problems, one I did not notice earlierrakeen wrote:
Code: Select all
scanf("%d \n",a);
Code: Select all
scanf("%d \n",&a);
Code: Select all
for(i=0;s<=a;i++)
Using one less variable does not help in programming in any ways, as far as I know. But still, if you want to sum the first $a$ numbers with that loop, you can rewrite the looping condition like this-rakeen wrote:and is there any rule that I've to use the same variable in the Controll Expression?
Code: Select all
for( i = 0; s <= (a * (a + 1)) / 2; i++ )
s = s + i;