Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I found a site with some complicated C puzzles. Right now I'm dealing with this:
The following is a piece of C code, whose intention was to print a minus sign 20 times. But you can notice that, it doesn't work.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
Well fixing the above code is straight-forward. To make the problem interesting, you have to fix the above code, by changing exactly one character. There are three known solutions. See if you can get all those three.
I cannot figure out how to solve. I know that it can be fixed by changing -- to ++, but I can't figure out what single character to change to make it work.
Here is one solution:
for( i = 0; -i < n; i-- )
printf("-");
Here is a second one, thanks to Mark for helping me!
for( i = 0; i + n; i-- )
printf("-");
And Mark also had the third one which is
for( i = 0; i < n; n-- )
printf("-");
Change i-- to n-- is another.
Okay - Gab made the fix, so I removed the other solution. He wins!
Third answer:
for( i = 0; i + n; i-- )
printf("-");
Thanks to Gab Royer for inspiration.
Explanation: Eventually , i + n will result in -20 + 20 = 0 which is false.
for( i = 0; i < n; n-- )
printf("-");
Changed i-- to n--
Here's one of them, I think:
for( i = 0; i < n; n-- )
The comparison in the for loop can be any expression - you can negate i.
for (i = 0; -i < n ; i--)
Solution 1
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; n-- ) // Change i-- to n--
printf("-");
return 0;
}
Solution 2
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; -i < n; i-- ) // Compare to -i
printf("-");
return 0;
}
Haven't figured a third.
Here is another one:
#include <stdio.h>
int main()
{
int i;
int n = -20; //make n negative
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
Related
My code is supposed to make a pyramid as such, but just gives me a line, why? I've tried changing the conditions of the for and while loops and haven't found any solution. Any help would be appreciated!!
#
##
###
####
#####
######
#######
########
#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n = get_int("Add the height of the pyramid: ");
int j = 0;
for(int i = 0; i < n ; i++) {
while (j <= i) {
printf("#");
j = j + 1;
}
printf("\n");
}
Declare j inside the for loop so it starts at 0 on each iteration.
for(int i = 0; i < n; i++) {
int j = 0;
while (j <= i) {
printf("#");
j = j + 1;
}
printf("\n");
}
The inner loop could also be rewritten as a for loop.
for(int i = 0; i < n; i++) {
for (int j = i; j >= 0; j--) printf("#");
printf("\n");
}
While the answer from #Unmitigated is correct, this would be a great place to break out some functionality into a function.
void print_n_ln(char *str, int n) {
for (; n > 0; n--) {
printf("%s", str);
}
printf("\n");
}
Then:
int main(void) {
int n = get_int("Add the height of the pyramid: ");
for (int i = 1; i <= n; i++)
print_n_ln("#", i);
return 0;
}
While an iterative solution (nested for() loops) would be simplest, this might be a good time to discover recursion. As long as the pyramid is not so tall as to risk stack overflow, the following works (leaving gathering/validating user input as an exercise.)
#include <stdio.h>
#include <cs50.h>
void print( int n ) {
if( n > 1 )
print( n - 1 );
while( n-- )
putchar( '#' );
putchar( '\n' );
}
int main() {
print( 7 );
return 0;
}
putchar() is a much simpler function than printf() and should be used when outputting a simple single character (for speed and efficiency.)
If you think your way through the operation presented, you will come to understand recursion and how it may sometimes be used to solve problems.
Another (albeit 'limited') solution follows:
int main() {
char wrk[] = "################";
int i = sizeof wrk - 1; // 'i' starts as the 'length' of the string
int want = 7;
while( want-- )
puts( wrk + --i ); // adding decreasing values of 'i' prints longer strings
return 0;
}
puts() will output a string to stdout while appending a 'newline'.
NB: Its more general sibling function (fputs()) works in a similar fashion, but does NOT append the LF for you.
There are often many ways to do things.
EDIT:
Here's another minimalist solution using pointers. This one uses a "compile time" string, so is not easily amenable to influence by a user (but it could be made so, if you're clever.)
#include <stdio.h>
#include <string.h>
int main() {
char want[] = "#######";
char *p = want + strlen( want );
while( --p >= want) puts( p );
return 0;
}
So here is the problem: Write a program that accept an integer n, print out the largest number but smaller or equal n that is the product of two consecutive even number. Example: Input: 12, Output: 8 ( 2x4 )
Here is my code :
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d ", i);
break;
}
}
}
return 0;
}
So if i input 20, it will print out 8 and 0 instead of 8, if i input 30, it will print out 24,8 and 0 instead of just 24. How do i make it stop after printing out the first number that appropriate ?
You need to stop an outer loop from processing, for example by using a boolean flag (meaning "solution found, we finish work") or a goto statement.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int solutionFound = 0;
for (int i = n; i >= 0; i--) {
// this could also be put into for's condition i.e. "i >= 0 && !solutionFound"
if (solutionFound) {
break;
}
for (int j = 0; j <= n; j = j + 2) {
if ( i == j * (j+2) ) {
printf("%d ", i);
solutionFound = 1;
break;
}
}
}
return 0;
}
EDIT: immediate return as noted in the comments is also a nice idea, if you don't need to do anything later.
Your problem is that you are nested - in a for loop which is inside another for loop - when you want to stop processing.
Some languages would let you code break 2; to indicate that you want to break out of 2 loops. Alas, C i snot such a language.
I would recommend that you code a function. That would serve a few porpoises: 1) your main should be "lean & mean" 2) as your programs get larger, you will learn the benefits of putting individual coding tasks into functions 3) you can use return; instead of break; and it will exit the function immediately.
Something like this:
#include <stdio.h>
void FindNeighbouringDivisors(int n)
{
for (int i = n; i >= 0; i--)
{
for (int j = 0; j <= n; j = j + 2)
{
if ( i == j * (j+2) )
{
printf("%d times %d = %d", j, j + 2, i);
return;
}
}
}
printf("There are no two adjacent even numbers which can be multiplied to give %d", n);
}
int main()
{
int n;
scanf("%d", &n); /* could get from comamnd line */
FindNeighbouringDivisors(n);
return 0; /* should be EXIT_SUCCESS */
}
Btw, when you have a problem with your code, ask a question here. When you have it working, consider posting it at our code review site where more experienced programmers can give you advice on how to improve it. It's a great way to learn
Break only breaks you out of immediate loop, so either use flags or just use return to terminate the execution. Or you can even use following code:
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
for (int j = 0; j <= n; j = j + 2)
{
if ( n < j * (j+2) )
{
printf("%d ", j*(j-2));
break;
}
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[10], greatest = 0, i;
a[0] = greatest;
for (i = 0 ; i < 10 ; i++)
{
scanf("%d", a[i]);
}
for (i = 0 ; i < 10 ; i++)
{
if (a[0] < a[i])
{
greatest = a[i];
}
}
printf("%d", a[i]);
return 0;
}
For starters (apart from other logical errors) this statement
a[0] = greatest;
does not make sense.
The program can look like
#include <stdio.h>
#define N 10
int main( void )
^^^^^
{
int a[N];
int greatest;
int i;
for ( i = 0 ; i < N ; i++ ) scanf( "%d", &a[i] );
^^^^^
greatest = a[0];
^^^^^^^^^^^^^^^^
for ( i = 1 ; i < N ; i++ )
{
if ( greatest < a[i] ) greatest = a[i];
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
}
printf( "%d\n", greatest );
^^^^^^^^
return 0;
}
There are many issues with your code. Lets take it one by one
1)
scanf() needs an address.
scanf("%d", &a[i]);
^
add an ampersand.
2)
You do not reset the value of i before using it in the last printf().
printf("%d", a[i]);
Therefore, i = 10, which is out of bound fro the array a[], therefore leading to undefined behavior.
3)
Since you are storing the values in the variable greatest in the for loop here,
for (i = 0 ; i < 10 ; i++)
{
if (a[0] < a[i])
{
greatest = a[i];
}
}
while comparing for the greatest number, you should also compare with the variable greatest. Because it would contain the the updated greatest value always. And better store the first value in the variable greatest before you start with this loop
greatest = a[0];
for (i = 1 ; i < 10 ; i++)
{
if (greatest < a[i])
{
greatest = a[i];
}
}
And later also, print the value in the greatest variable.
printf("%d", greatest);
NOTE:
Use the standard definition of main()
int main(void) //if no command line arguments.
I have for loop doubt that I need to ask .
once i saw in coding something like
for(i = 0; i<10; i+)
My doubt is why &when in for loop we use say i+ or i- rather than i++ or i--
Thanks in advance
It won't work, doesn't the compiler return an error if you do? ( or atleast a warning.. )
Just use ++i or i++
Using i+ instead of i++ should not work. As I think you know, i++ increases the value of i by one. When the compiler sees i+, it is expecting something after the +, which causes it to not compile.
The line in question is not valid C
for(i = 0; i<10; i+)
Some valid, equivalent (between themselves) options are
for(i = 0; i < 10; i++)
for(i = 0; i < 10; ++i)
for(i = 0; i < 10; i += 1)
for(i = 0; i < 10; ) { /*...*/ i++; }
You cannot use i+ or i- because if doesn’t work i.e doesn’t increase or decrease value of i for increment you have may use i++,++i,i+=1,i=i+1 and for decrement you can use these by changing sign to negtive
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Help with C puzzle
The intention of the program was to print a minus sign 20 times, but it doesn't work.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
This is a classic puzzle!
The way I saw it was
"You can only change/insert/delete one character in the code to make the - print 20 times".
Some answers are (if I remember them correctly)
1)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; -i < n; i-- )
printf("-");
return 0;
}
Here you change the i < n to -i < n
2)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; n-- )
printf("-");
return 0;
}
Here you change the i-- to n--
3)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i + n; i-- )
printf("-");
return 0;
}
You change the i < n to i+n.
For a challenge, try changing/inserting/deleting one character to make it print the - 21 times. (Don't read the comments to this answer if you want to try it!)
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i++ )
printf("-");
return 0;
}
You had -- instead of ++
Replace i-- with i++.
int main() {
int i;
int n = 20;
for( i = 0; i < n; i++)
printf("-");
return 0;
}
You had decrement instead of increment.
Have you tried changing the
i--
to
i++
You have the loop to print out a "-" for as long as "i" is less than 20.
After every loop you reduce the value of i by 1, it will continue to print
for a very long time. Changing the final part of the for loop to "i++" means it will perform one iteration each loop and stop once the twentieth iteration finished.
Change i-- to i++.
i-- decrements the value which at start is 0 and with subsequent reductions won't ever reach 20 (or +20).
the i-- needs to be i++
you could also do
int n = -20;
for( i = 0; i > n; i-- )
but that is bad coding practice
What exactly are you trying to do with this problem???
Here you are trying to decrement the value of a variable..a variable whose value will never reach the condition (i<20) you have provided... hence it will keep on printing '-' until what jamie wong specified, i.e. i= -2^31. It will become +ve. I just tried this program.
#include <stdio.h>
int main()
{
int i;
int n = 20;
for( i = 0; i < n; i-- )
printf("-");
return 0;
}
According to the question you asked, i should be incremented, i.e. i++ instead of i--.
#jamie wong: thanx man..learnt a new thing about tht a wraparound....
You'll print no dashes. You can either go with Jaime Wong's solution or do this:
for (i = n; i >= 0; i--)