Skip to main content

Section 10.6 Common Errors With Branching

Subsection 10.6.1 Practice 5

Activity 10.8.

What’s wrong here? Why is this not printing a list of factorials? Can you fix it?

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void)
{
    int N, i, fact;
    
    
    for (N=1; N<=10; N++) 
        fact = 1;
        for (i=1; i<=N; i++)
            fact = fact*i;
    
        printf("%d! = %d\n", N, fact);
    
    return(0);
}

Subsection 10.6.2 Practice 6

Activity 10.9.

What’s wrong with this now?
You’d like to print out a rectangle of stars that is 8 stars wide and 3 stars tall, just as in the output below:
********
********
********
Something is wrong with your code however. Can you fix it?

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void)
{
    int i;
    
    for (i=0; i<3; i++) {
        for (i=0; i<8; i++)
            printf("*");
        printf("\n");
    }
    printf("\n");
    return(0);
}

Subsection 10.6.3 Practice 7

Activity 10.10.

What’s wrong with this code? Why is it not printing the equation you expect?

Compile and run the code below in your own C environment.

#include <stdio.h>

int main(void) {
    int a = 10;
    int b = 3;
    int c;
    int okay = 1;
    
    char op = '+';
    
    switch(op) {
        case '+': 
            c = a+b;
        case '-':
            c = a-b;
        case '*':
            c = a*b;
        case '%':
            c = a%b;
        case '/':
            c = a/b;
        default:
            printf("Unknown operator.\n");
            okay = 0;
            c = 0;
    }
    
    if (okay) printf("\n%d %c %d = %d\n", a, op, b, c);
    return(0);
}
What is wrong here?