Change/add only one character and print ‘*’ exactly 20 times
In the below code, change/add only one character and print ‘*’ exactly 20 times.
int main()
{
int i, n = 20;
for (i = 0; i < n; i--)
printf("*");
getchar();
return 0;
}
Solutions:
1. Replace i by n in for loop’s third expression
C
#include <stdio.h> int main() { int i, n = 20; for (i = 0; i < n; n--) printf("*"); getchar(); return 0; } |
chevron_right
filter_none
Java
// Java code class GfG { public static void main(String[] args) { int i, n = 20; for (i = 0; i < n; n--) System.out.print("*"); } } |
chevron_right
filter_none
C#
// C# code using System; class GfG { public static void Main() { int i, n = 20; for (i = 0; i < n; n--) Console.Write("*"); } } // This code is contributed by SoumikMondal |
chevron_right
filter_none
2. Put ‘-‘ before i in for loop’s second expression
#include <stdio.h> int main() { int i, n = 20; for (i = 0; -i < n; i--) printf("*"); getchar(); return 0; } |
chevron_right
filter_none
3. Replace < by + in for loop's second expression
#include <stdio.h> int main() { int i, n = 20; for (i = 0; i + n; i--) printf("*"); getchar(); return 0; } |
chevron_right
filter_none
Let’s extend the problem little.
Change/add only one character and print ‘*’ exactly 21 times.
Solution: Put negation operator before i in for loop’s second expression.
Explanation: Negation operator converts the number into its one’s complement.
No. One's complement
0 (00000..00) -1 (1111..11)
-1 (11..1111) 0 (00..0000)
-2 (11..1110) 1 (00..0001)
-3 (11..1101) 2 (00..0010)
...............................................
-20 (11..01100) 19 (00..10011)
#include <stdio.h> int main() { int i, n = 20; for (i = 0; ~i < n; i--) printf("*"); getchar(); return 0; } |
chevron_right
filter_none
Please comment if you find more solutions of above problems.
Recommended Posts:
- Print a character n times without using loop, recursion or goto in C++
- How to print N times without using loops or recursion ?
- How to print a number 100 times without using loop and recursion in C?
- Print a number 100 times without using loop, recursion and macro expansion in C?
- Check input character is alphabet, digit or special character
- Character arithmetic in C and C++
- Character Classification in C++ : cctype
- Type difference of character literals in C and C++
- Storage of integer and character values in C
- How to convert a single character to string in C++?
- Data type of character constants in C and C++
- getline() function and character array
- Differentiate printable and control character in C ?
- Convert character array to string in C++
- Program to count occurrence of a given character in a string


