Problem executing a Program

Discuss Computer Science and Programming related problems

Moderators: bristy1588, Labib

rakeen
Posts: 384
Joined: Thu Dec 09, 2010 5:21 pm
Location: Dhaka

Problem executing a Program

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;
}``````
Attachments
codeblocks prob scrn shot.JPG (139.3 KiB) Viewed 1933 times
r@k€€/|/

*Mahi*
Posts: 1175
Joined: Wed Dec 29, 2010 12:46 pm
Location: 23.786228,90.354974
Contact:

Re: Problem executing a Program

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?

Use \$L^AT_EX\$, It makes our work a lot easier!

rakeen
Posts: 384
Joined: Thu Dec 09, 2010 5:21 pm
Location: Dhaka

Re: Problem executing a Program

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!
r@k€€/|/

rakeen
Posts: 384
Joined: Thu Dec 09, 2010 5:21 pm
Location: Dhaka

Re: Problem executing a Program

and is there any rule that I've to use the same variable in the Controll Expression?
r@k€€/|/

*Mahi*
Posts: 1175
Joined: Wed Dec 29, 2010 12:46 pm
Location: 23.786228,90.354974
Contact:

Re: Problem executing a Program

rakeen wrote:
There are actually two problems, one I did not notice earlier

1.
Using

Code: Select all

``````   scanf("%d \n",a);
``````

crashes the program, as 'a' is not a pointer, so use

Code: Select all

``````   scanf("%d \n",&a);
``````
instead, as '&a' is a pointer pointing to 'a', and thus scanf function can work properly.
2.
Using the loop

Code: Select all

`` for(i=0;s<=a;i++)``
doesn't give you the sum of first \$a\$ integers, it only sums as long as the sum is smaller than \$a\$.

Use \$L^AT_EX\$, It makes our work a lot easier!

*Mahi*
Posts: 1175
Joined: Wed Dec 29, 2010 12:46 pm
Location: 23.786228,90.354974
Contact:

Re: Problem executing a Program

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.