Patrick Resal
Patrick Resal

Reputation: 125

C for condition tricks

I found a challenge on the internet and I'm really stuck. The goal is to print 20 times _ by adding/changing only 1 character (only one operation performed in total):

#include <stdio.h>

int main(void)
{
    int i;
    int n=20;
    for(i=0;i<n;i--)
    {
        printf("_");
    }
    return 0;
}

I have already found 1 solution but I can't find the last one? Is there some tricks I need to know about for loops ?

Upvotes: 1

Views: 3328

Answers (3)

user3629249
user3629249

Reputation: 16540

to correct the posted code to only output 20 times, you could use:

#include <stdio.h>

int main(void)
{
    int i;
    int n=-20;   // note the minus 20
    for(i=0;i<n;i--)
    {
        printf("_");
    }
    return 0;
}

Upvotes: 0

manoliar
manoliar

Reputation: 182

Replace i by n

#include <stdio.h> 
int main() 
{ 
    int i, n = 20; 
    for (i = 0; i < n; n--) 
        printf("*"); 
    getchar();     
    return 0; 
}

Put - before i

#include <stdio.h> 
int main() 
{ 
    int i, n = 20; 
    for (i = 0; -i < n; i--) 
        printf("*");            
    getchar();     
    return 0; 
}

Replace < by +

#include <stdio.h> 
int main() 
{ 
    int i, n = 20; 
    for (i = 0; i + n; i--) 
       printf("*"); 
    getchar(); 
    return 0; 
} 

Source: https://www.geeksforgeeks.org/changeadd-only-one-character-and-print-exactly-20-times/

Upvotes: 2

Fral
Fral

Reputation: 31

If it is allowed you could write:

n=10; for(i=0;i<n;i++){printf("__");}

or

n=10; for(i=0;i<n;i++){printf("_");printf("_");}

Upvotes: -1

Related Questions