What's wrong with this C program [duplicate] - c

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--)

Related

While and for loops not giving the right answer

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;
}

How to stop the loop after printing one?

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;
}

Trying to print 10 lines of 100 array values in C

I have an array with 100 numbers in it, and I am trying to print it out with only 10 ints on each line, and a tab between each number. It is only printing the first 10 integers and then stopping, which makes sense because of my for loop. I am clearly missing part of it to allow for it to continue through the array. I was going to try to add the line
for(int line_num = 0; line_num < 10; line_num+=10)
before the for statement after the while loop
int array_value;
int length_of_array = 100;
while (length_of_array <= 100){
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
I was also thinking of including a line like
if (array_value % 10 == 0)
printf("\n");
I figured it out! Posted the answer below.
This might be what you're looking for:
/* test.c */
#include <stdio.h>
#define ELEMENTS 100
int main (void)
{
int array [ELEMENTS];
for ( int i = 0; i < ELEMENTS; ++i )
array [i] = i;
for ( int i = 0; i < ELEMENTS; ++i ) {
printf ("%i", array[i]);
if ( (i + 1) % 10 != 0 )
printf ("\t");
else
printf ("\n");
}
return 0;
}
edit: Because of the way the tab can extend to the next line at the end of the line you have to be careful with the tab and new line character.
For clarity, rename length_of_array to offset_in_array and then set it to zero at the start. I renamed array_value and corrected your length check. I also added a check to the inner loop in case the array length gets changed and doesn't divide by 10.
Something like:
int i;
#define ARRAY_LENGTH 100
int offset_in_array = 0;
while (offset_in_array < ARRAY_LENGTH){
for(i = 0; i < 10 && offset_in_array < ARRAY_LENGTH; ++i){
printf("%d ", A[offset_in_array]);
++offset_in_array;
}
}
I haven't tried running this but it should be closer.
Just print a newline every tenth number... If it's not a tenth number, then print a tab.
for (size_t i = 0; i < array_length; ++i) {
printf("%d%c", A[i], i % 10 != 9 ? '\t' : '\n');
}
Live code available at onlinedbg.
Just change the value of length_of_array to 0 and print \n after a for loop.
int array_value;
int length_of_array = 0;
while (length_of_array <= 100) {
for(array_value = 0; array_value < 10; ++array_value){
printf("%d ", A[array_value]);
++length_of_array;
}
printf("\n");
}
You can use the following solution to print 10 lines of 100 array values in C:
for (int i = 0; i < 100; ++i){
printf("%i\t", A[i]);
if ((i+1)%10 == 0){
printf("\n");
}
}

For Loop stops before condition (C)

I am very new to C language. I have a little problem that I can't figure out. I made a lottery program which generates 6 random numbers to each columns, and repeats according to the row value entered. The only problem I am having is the program stops after 9 succesful rows even though the input is higher.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int KURE_SIZE = 50;
int ROWS = 0;
int i, j, a;
int lottery[ i ][ j ];
int kure[ KURE_SIZE ];
for( a = 1; a <= KURE_SIZE; ++a )
kure[a] = a;
printf("How many games do you want to play? (MAX.500) ");
scanf("%d", &ROWS);
printf("\n");
for( i = 0; i < ROWS; i++ ){
printf("Game %d :", i + 1);
srand ( (unsigned int) time(NULL));
for( j = 0; j < 6; j++ ){
int x = 1 + rand() % KURE_SIZE;
lottery[ i ][ j ] = kure[ x ];
printf("%5d", lottery[ i ][ j ]);
kure[x] = kure[ KURE_SIZE-- ];
}
printf("\n");
}
printf("\n\n");
system("pause");
return 0;
}
What might be the reason for this problem? I thought it may be a memory issue, but I don't know.
I'd be appreciated for some help. I love this site and the helpful community.
This definition of a variable length array
int lottery[ i ][ j ];
is incorrect because variables i and j are not initialized.
Also this loop is invalid
for( a = 1; a <= `KURE_SIZE`; ++a )
kure[a] = a;
there ia an attempt to access memory beyond the array. The valid range of indices for this array is [0, KURE_SIZE-1]
Thus this statement
int x = 1 + rand() % KURE_SIZE;
must be changed to
int x = rand() % KURE_SIZE;
because variable x used as an index for the array kure

Fixing a broken loop by changing exactly one character

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;
}

Resources