COMP1911 23T2 Introduction to Programming
  1. Consider the two code snippets below, what will be the output after execution of each of the programs for inputNum = 3.
    int inputNum, i; 
    
    printf("Enter a number: "); 
    scanf("%d", &inputNum); 
    
    i = inputNum; 
    
    if(i <= 5){
      printf("%d\n", i * i); 
      i++; 
    }
    
    int inputNum, i; 
    
    printf("Enter a number: "); 
    scanf("%d", &inputNum); 
    
    i = inputNum; 
    
    while(i <= 5){
      printf("%d\n", i * i); 
      i++; 
    }
    
    The output of the first program:
    9

    The output of the second program:
    9
    16
    25

    Therefore, remember the instructions in the if statements are executed just once, given the condition in the round brackets is true. Whereas, instructions can execute more than once in a while statement (hence the term loop, iteration, repetition...).
  2. Discuss the errors in these while loops
    int i;
    
    while (i < 100) {
        printf("%d\n", i);
        i = i + 1;
    }
    
    Explanation of error: i is not initialized. dcc should warn you about this (or gcc -O -Wall if you are using gcc on your own machine).
    int i = 0;
    int j = 0;
    
    while (j = 1 || i < 100) {
        printf("%d\n", i);
        i = i + 1;
    }
    
    Explanation of error: j = 1 is an assignment statement, not a comparison.

    dcc should warn you about accidental uses of assignment in if/while conditions.

    int i = 0;
    int n = 10;
    while (i < n) {
        printf("%d\n", i);
        n = n + i;
        i = i + 1;
    }
    
    Explanation of error: loop does not terminate because the assignment n = n + i results in n growing faster than i.
    int i = 0;
    while (i < 10)
        printf("%d\n", i);
        i = i + 1;
    
    Explanation of error: missing braces mean the update statement, i = i + 1, is not part of the loop regardless of the indentation, and the loop is an infinite loop.
    • Using pseudo code, write an algorithm for printing the numbers from k down to 1 together with their squares. You can assume k is 10

      //Declare and initialise counter to 10
          // While i is greater than or equal to 1
              // Print counter and its square
              // Decrement value of counter
      
    • Translate the pseudo code you have just written into a functioning C program. Use a while loop.
      #include <stdio.h>
      
      int main(void) {
          //Declare and initialise counter to 10
          int i = 10;
      
          // While i is greater than or equal to 1
          while (i >= 1) {
              // Print counter and its square
              printf("The square of %d is %d\n", i, i * i);
      
              // Decrement value of counter
              i = i - 1;
          }
      
          return 0;
      }
      
    • Modify your C code so that your program, after printing a number and its square on a line, prints the string "Number is even" if the number (not its square) is even and otherwise prints the string "Number is odd" if the number is odd.

      #include <stdio.h>
      
      // Let's use symbolic constants this time
      #define MAX     10
      #define MIN     1
      
      int main(void) {
          int i;
      
          i = MAX;
          while (i >= MIN) {
              printf("The square of %d is %d.", i, i * i);
              if ((i % 2) == 0) {
                  printf(" Number is even\n");
              } else {
                  printf(" Number is odd\n");
              }
      
              i = i - 1;
          }
      
          return 0;
      }
      
  3. Write a program that reads in an integers and prints out that many asterisks, each on a new line.
    ./asterisks
    Please enter an integer: 5
    *
    *
    *
    *
    *
    
    Sample solution for asterisks.c
    #include <stdio.h>
    
    int main(void) {
        int i, n;
    
        printf("Please enter an integer: ");
        scanf("%d", &n);
    
        i = 0;
        while (i < n) {
            printf("*\n");
            i =  i + 1;
        }
    
        return 0;
    }
    
    
  4. Write a program that repeatedly reads in integers until a negative integer is read in. Your program should print out how many integers were read in. For example:
    ./readInts
    Please enter some integers:
    10 100 999 78 -3
    You entered 4 integers
    
    ./readInts
    Please enter some integers:
    1 2 3 4 5 6 7 8 9 
    10 11 12 -9
    You entered 12 integers
    
    Sample solution for readInts0.c
    #include <stdio.h>
    
    
    int main(void) {
       int n;
       int count;
    
       printf("Please enter some integers:\n");
       count = 0;
       scanf("%d", &n);
       while (n >= 0) {
           count = count + 1;
           scanf("%d", &n);
       }
       printf("You entered %d positive integers\n", count);
    
       return 0;
    }
    
    
    Alternative sample solution for readInts1.c
    #include <stdio.h>
    
    #define FALSE 0
    #define TRUE 1
    
    int main(void) {
       int n;
       int count;
       int stopReading = FALSE;
    
       printf("Please enter some integers:\n");
       count = 0;
       
       while (stopReading == FALSE) {
           scanf("%d", &n);
           if(n < 0){
               stopReading = TRUE;
           } else {
               count = count + 1;      
           }
       }
       printf("You entered %d positive integers\n", count);
    
       return 0;
    }
    
    
  5. Write a C program multipleOfTen.c which reads 2 integers and then prints all multiples of ten between those numbers.
    Sample solution for multipleOfTen.c
    #include <stdio.h>
    
    int main(void) {
        int i, start, finish;
        printf("Enter start: ");
        scanf("%d", &start);
        printf("Enter finish: ");
        scanf("%d", &finish);
        i = start;
        while (i <= finish) {
            if (i % 10 == 0) {
                printf("%d\n", i);
            }
            i = i + 1;
        }
        return 0;
    }
    
    
  6. Write a C program log10.c which reads a positive integer, and calculates the integer part of its base 10 logarithm. Hint: repeatedly divide by 10.

    Sample solution for log10.c
    #include <stdio.h>
    
    int main(void) {
        int x, y, logTen;
        printf("Enter a positive integer: ");
        scanf("%d", &x);
        logTen = 0;
        y = x;
        while (y >= 10) {
            y = y / 10;
            logTen = logTen + 1;
        }
        printf("log10 of %d is %d\n", x, logTen);
        return 0;
    }
    
    
  7. Consider the following code
    #include <stdio.h>
    
    int main(void) {
        int number;
        int row, column;
    
        // Obtain input
        printf("Enter number: ");
        scanf("%d",&number);
    
        row = 1;
        while (row <= number) {
            column = 1;
            while (column <= number) {
                printf("*");
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
    What is the output if the user types in the number 5?
    Enter number: 5
    *****
    *****
    *****
    *****
    *****
    
    Modify the program so that it prints out a triangle that consists of number asterisks eg
    Enter number: 5
        *
       **
      ***
     ****
    *****
    

    Sample solution for triangle.c
    #include <stdio.h>
    
    int main(void) {
        int number;
        int row, column;
    
        // Obtain input
        printf("Enter number: ");
        scanf("%d",&number);
    
        row = 1;
        while (row <= number) {
            column = 1;
            while (column <= number) {
                if (column <= (number - row)) {
                    printf(" ");
                } else {
                    printf("*");
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
  8. Write a program diagonal.c that reads an integer and prints the following pattern:
    ./diagonal
    Enter an integer: 10
    *
     *
      *
       *
        *
         *
          *
           *
            *
             *
    
    Sample solution for diagonal.c
    #include <stdio.h>
    
    int main(void) {
       int n;
       int row, column;
    
       printf("Enter an integer:\n");
       scanf("%d", &n);
    
       row = 0;
       while (row < n) {
           column = 0;
           while (column < row) {
               printf(" ");
               column = column + 1;
           }
           printf("*\n");
           row = row + 1;
       }
       return 0;
    }
    
    
  9. Write a program cross.c that reads an integer and prints the following pattern. You may assume your input is a positive integer >= 5
    ./cross
    Enter size: 5
    *---*
    -*-*-
    --*--
    -*-*-
    *---* 
    
    Here is a solution
    
    // an example for COMP1911
    // Print an nxn "cross" pattern of asterisks and dashes
    
    #include <stdio.h>
    
    int main(void) {
        int size, n_numbers_read;
        int row, column;
    
        printf("Enter size: ");
        scanf("%d", &size);
    
    
        row = 0;
        while (row < size) {
            column = 0;
            while (column < size) {
                if (row == column || (row + column) == (size-1)) {
                    printf("*");
                } else {
                    printf("-");
                }
                column = column + 1;
            }
            printf("\n");
            row = row + 1;
        }
    
        return 0;
    }
    
    
  10. Write a program that reads two integers (height x length) and prints a rectangular, asterisk outline with the specified dimensions, for example:
    ./rectangle
    Enter rectangle height and length: 3 5
    *****
    *   *
    *****
    
    Sample solution for rectangle.c
    #include <stdio.h>
    
    int main(void){
        int height, length;
        int row, col;
    
        printf("Enter rectangle height and length: ");
        scanf("%d", &height);
        scanf("%d", &length);
    
        row = 0;
        while (row < height) {
            col = 0;
            while (col < length) {
    
                // If the index is on one of the edges, print *.
                // Otherwise, print a space.
                if (row == 0 || row == height - 1 || 
                    col == 0 || col == length - 1) {
                    printf("*");
                } else {
                    printf(" ");
                }
    
                col = col + 1;
             }
             printf("\n");
             row = row + 1;
        }
        return 0;
    }
    
    
  11. Design and write a program that an integers and prints a diamond, asterisk outline with the specified side length, for example:
    ./diamond
    Enter side length: 3
      *
     * *
    *   *
     * *
      *
    ./diamond
    Enter side length: 6
         *
        * *
       *   *
      *     *
     *       *
    *         *
     *       *
      *     *
       *   *
        * *
         *
    
    Sample solution for diamond.c
    #include <stdio.h>
    
    int main(void){
        int side;
        int row, column;
    
        printf("Enter side length: ");
        scanf("%d", &side);
    
        row = 0;
        while (row < side * 2 - 1) {
            column = 0;
            while (column < side * 2 - 1) {
                if (row <= (side - 1)) {
                    if (column == (side - 1) - row || column  == (side - 1) + row) {
                        printf("*");
                    } else {
                        printf(" ");
                    }
                } else {
                    if (column == row - (side - 1) || column  ==  3 * (side - 1) - row) {
                        printf("*");
                    } else {
                        printf(" ");
                    }
                }
                column = column + 1;
             }
             printf("\n");
             row = row + 1;
        }
        return 0;
    }
    
    
  12. Write a program that reads in an integer n, and then prints a nxn multiplication table. For example:
    ./multiplicationTable
    Enter multiplication table size: 5
     1|   1    2    3    4    5
     2|   2    4    6    8   10
     3|   3    6    9   12   15
     4|   4    8   12   16   20
     5|   5   10   15   20   25
    
    Sample solution for multiplicationTable.c
    
    #include <stdio.h>
    
    int main(void) {
    
        int row = 1, col = 1;
        int tableSize;
    
        printf("Enter multiplication table size: ");
        scanf("%d", &tableSize);
    
        while (row <= tableSize) {
            col = 1;
            while (col <= tableSize) {
                if (col == 1) {
                    printf("%2d|", row);
                }
                printf("%4d ", row * col);
                col++;
            }
            printf("\n");
    
            row++;
        }
        return 0;
    }
    
  13. What is a function? Discuss the main features of functions? What is the type of a function? What is a function prototype? What are some of the benefits of using functions?
    A function is a portion of code within a larger program, that performs a specific task and is relatively independent of the remaining code. Functions have an associated identifier (i.e., name) that is used when they are called. Functions may be parametrised via one or more arguments and may return a single value.

    The type of a function is made up of the type of its return value and the types of each of its arguments. A function prototype gives the type signature of a function and allows the compiler to check that function calls are type correct before the function definition is seen. For example

      double f(int x, int y);
      
    is a prototype for a function named f, that has two integer inputs and returns a double.
    • Functions facilitate code reuse;
    • Functions facilitate the separation of logic from implementation (i.e., abstraction);
    • Functions facilitate program structuring;
    • Functions facilitate testing and debugging;
    • Functions improve the readability of programs.
  14. A student wrote the following code to read in a number, n and print out n asterisks.
    void getSquare(void);
    
    int main(void){
        int n;
        printf("Enter a number ");
        scanf("%d",&n);    
        getSquare();
        printf("The square of %d is %d\n", n, sqr);
        return EXIT_SUCCESS;
    }
    
    int getSquare(void) {
        int i;
        int count = 1;
    
        i = 0;
        while ( i < n ) {
            count *= n
            i = i + 1;
        }
        printf("\n");    
    }
    

    It had the following compile time error:

    getSquare.c:17:17: error: use of undeclared identifier 'n'
        while ( i < n ) {
    

    What is wrong with the code? How can we fix it?

    getSquare does not have a variable n in its scope. The main function has a variable n but it is local and visible only to the main function.

    The getSquare function should be changed so the main function can pass the value of n into the function as follows:

    void getSquare(int n);
    
    int main(void){
        int n;
        printf("Enter a number ");
        scanf("%d",&n);    
        getSquare(int n);
        printf("The square of %d is %d\n", n, sqr);
        return EXIT_SUCCESS;
    }
    
    int getSquare(int n) {
        int i;
        int count = 1;
    
        i = 0;
        while ( i < n ) {
            count *= n
            i = i + 1;
        }
        printf("\n");    
    }