dannylee dannylee - 3 months ago 11
C Question

Repetition using switch statement inside a for loop

I am trying to use a loop to print out a repetitive song, "this old man"
The first verse is:
This old man, he played one
He played knick-knack on my thumb
This old man came rolling home

This song repeats to ten, varying the two terms in italicize
one -> two++ and thumb -> another item such as shoe, knee, etc.
Here is my code so far:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

string change1 (int i);
int main (void)
{
for (int i = 1; ; 1 < 11; i++)
{
printf ("This old man, he played ");
change1(i);
printf("He played knick-knack on my %s\n\n", s1);
}

return 0;
}

string change1(int i)
{
string s1;

switch(i)
{
case 1:
{
printf("one\n");
s1 = "thumb";
}
break;
case 2:
{
printf("two\n");
s1 = "shoe";
}
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
printf("ill add these cases later");
}
}


This gives me an error message of: "control reaches end of non-void function"

I also got an undeclared variable s1 error but I declared it in the function.

Answer

In C++ variables have scope. A variable is generally visible inside the curly braces where it is declared; outside these brackets the variable does not exist.

That is why you cannot use s1 from change1 inside the loop: you need to return a value (best choice in your situation), or use a variable that is in scope in both change1 and main.

printf ("This old man, he played ");
printf("He played knick-knack on my %s\n\n", change1(i));
...
string change1 (int i) {
    string s1;
    switch (i) {
        ...
    }
    return s1;
}

Note that you do not need a switch statement to implement change1: when the code is so uniform, you may be better off with an array:

const char *strings[] = {"thumb", "shoe", ...};
Comments