+ 1
write a program to print s=2+4-6+8-10.....+n
write a program to print s=2+4-6+8-10.....+n
6 Respuestas
+ 2
include<iostream>
using namespace std;
main (){
int i ,n,s=0;
cin>>n;
for(i=0;i<=n;i++)
{
If(i%2==0)
{
s=s+i;
}}
cout<<s;
}
+ 2
1. Main function returns int, so it should be (standards wise)
int main()
{
// function body
}
2. Since you want to start summing up from 2, you can initialize the for...loop counter <i> by 2 rather than 0.
3. Also, since you only want to add even numbers, you can increment value of <i> by 2 in each iteration of the for...loop. This way, you won't need the even number check `i % 2 == 0` anymore.
for( int i = 2; i <= n; i += 2 )
{
s += i;
}
+ 1
Marwa Ahmeid ok and how did it go? Did your attempt work? Which language(s) did you try to use? Post your code here. If it didn't work we can help you figure out why once we have a look at it.
If you're asking me to do it for you, I won't do that as it won't help you to learn. For my help you must show you tried. I will give a hint. You should use a loop. The languages you mention support for and while loops amoung others. Also look up the % operator and consider division by 2.
+ 1
I think the problem is with the positive and negative signs
0
That could be. I didn't catch the -10.. It could be that you just need to sum all numbers. Can you post the full instructions for the problem?
it might just be that the modules operator and if is not necessary.
0
void main()
{
int i, s=2,n;
printf(”Enter range :”);
scanf(”%d”, &n);
for(i=1;i<n;i++)
{
if((s/2)%2==0)
printf(”%d - “, s);
else
printf(”%d + “, s);
s+=2;
}
printf(”%d”, s);
}
Explanation
=========
In the above code
Consider
2 - 2/2 =1 1%2==0 F
Results in 2+
Similarly
4 - 4/2 = 2 2%2 == 0 T
Results in 4-
The next following numbers follow same pattern