+ 2
How can I print this series 1 -2 3 -4 5 -6...N
Using only one decision statment and only one write statement. I'm using this , int n ,ans; For(int I;I<=n;I++) { ans=I; if(ans%2==0) { ans=ans*(-1); printf ("%d",ans); } else { printf ("%d",ans); } } But this take two conditional statements and write statement.
14 Antworten
+ 5
if (ans % 2 == 0)
// make ans negative
printf('%d', ans)
You don't need the else-part, just output ans once at the end in the loop block
+ 4
int n, ans;
for (int l = 0; l <= n, l++){
ans = l;
if (ans%2==0) ans*=(-1);
printf(“%d”, ans);
}
Try this
+ 3
variation on Mirielle 's clever solution
#include <iostream>
using namespace std;
int main() {
int n = 10;
for(int i=1; i <= n; i++)
printf("%d ",((i%2)*+i*2)-i);
}
+ 3
y'all overcomplicating this:
int sign = 1;
for(int i; i<=n; i++){
printf("%d", i*sign);
sign *= (-1);
}
to expand a little on this: any time a distinct operation is being repeated at every iteration (in this case, a sign flip), you should be able to generate the result without any extra logic, even if the solution isn't obvious at first. Just make sure that it really is the same operation happening each time
+ 2
That means that the if condition can only be checked once? That’s really hard…
+ 2
Orin Cook
🤯 omg. i am humbled. and you can condense it even more... (I made altrations bec the OP wanted negative even numbers, but yeah your way is better.😎😎😎)
int main() {
int sign=-1, n=10, i=0;
while(i<=n)
printf("%d ",++i*(sign*=-1));
}
+ 2
Hetal Chavda
I wonder if ternary operators counts as if else? here is my one variable solution.
int main() {
int n=1;
while(n<=10)
{printf("%d ",(n%2==0?-1:1)*n);n++;}
}
or combining it with Orin Cook 's method:
int main() {
int n=1, s=-1;
while(n<=10)
printf("%d ",(s*=-1)*n++);
}
or the while loop version of Mirielle 's method
int main() {
int n = 1;
while(n<=10)
{printf("%d ",((n%2)*+n*2)-n);n++;}
}
+ 1
Int n,sign;
for(int I=1;I<=n;I++)
{
sign=I ;
Sign=(sign%2==0) ? -sign : sign;
Printf ("%d",sign);
}
+ 1
Mirielle nah it works correctly as-is, except for the fact that I forgot to initialize to i=1 lol. Note that it prints the number *before* it flips the sign; I could have also put the sign flip before the printf if I initialized sign = (-1) instead.
0
Thanks .
but it's not working
Actually it's assignment , so I can't use if and for at a time either I'm use only one condition and only one printf for output
0
Thanks 😃
0
Thanks a lot😊
0
Ya it's working 👍 Thanks a lot all of you guys .
0
Hetal Chavda
Orin Cook used sign*=-1 😎
which I think is really creative.
Mirielle yes, I think of ternary operators as lazy if-else.