Page 1 of 1
Problem executing a Program
Posted: Fri Nov 09, 2012 1:10 pm
by rakeen
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;
}
Re: Problem executing a Program
Posted: Fri Nov 09, 2012 2:42 pm
by *Mahi*
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;
}
Try this:
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;
}
Can you tell why your code did not work?
Re: Problem executing a Program
Posted: Sat Nov 10, 2012 9:13 am
by rakeen
it should also work fine if i=1. right?
and if (i=1;s<=7;i++) then,
s=0+1
s=1+2
s=3+3
s=6
the output should be 6.
where's the problem!
Re: Problem executing a Program
Posted: Sat Nov 10, 2012 9:19 am
by rakeen
and is there any rule that I've to use the same variable in the Controll Expression?
Re: Problem executing a Program
Posted: Sat Nov 10, 2012 11:18 am
by *Mahi*
There are actually two problems, one I did not notice earlier
1.
Using
crashes the program, as 'a' is not a pointer, so use
instead, as '&a' is a pointer pointing to 'a', and thus scanf function can work properly.
2.
Using the loop
doesn't give you the sum of first $a$ integers, it only sums as long as the sum is smaller than $a$.
Re: Problem executing a Program
Posted: Sat Nov 10, 2012 11:22 am
by *Mahi*
rakeen wrote:and is there any rule that I've to use the same variable in the Controll Expression?
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-
Code: Select all
for( i = 0; s <= (a * (a + 1)) / 2; i++ )
s = s + i;
Then it will continue looping until you get the desired sum.