COMP1911 23T2 Introduction to Programming
  1. Write a function to find the factorial of a given integer. Because factorial grows very quickly we want our result to be a long long.

    Use the function your wrote to write a program that prompts the user for a positive integer less than 45 (otherwise it will overflow our long long variable) and prints out the factorial of that number.

    Add error checking, so that if the user does not enter an integer the program prints "Invalid input" and exits. You should also print "Invalid input" and exit if the user enters a negative number or a number of 45 or more.

  2. Another student wrote the following code to read in a number and print out its reciprocal.
    // This program allows a user to enter a number
    // and prints out its reciprocal (ie. 1 divided by the number)
    
    void reciprocal(double x);
    
    int main(void){
    
        double x;
        printf("Enter a number ");
        
        scanf("%lf",&x);
        reciprocal(x);
        
        printf("The reciprocal is %lf\n",x);
        return EXIT_SUCCESS;
    }
    
    void reciprocal(double x){
        if ( x != 0 ){
            x = 1.0/x;
        }
    }
    

    However the function did not seem to work as intended and gave incorrect output as shown below

    Enter a number 3
    The reciprocal is 3.000000
    
    What is wrong with the code? How can we modify the code to make our function work as intended and in this case get
    Enter a number 3
    The reciprocal is 0.333333
    

  3. What is an array?

  4. Give an expression that sums the first and third element of an array called numbers?

  5. If an array is declared as int numbers[20]; and your program assigns a value to each element in the array, what is the problem with the statement x = numbers[20]; ?

  6. How would you declare a variable squares to be an array of integers with 15 elements?

    Write a C code fragment to store, in each element of this array, the square of the index of that element, e.g., squares[5] would contain the value 25.

  7. This C code:
        int x;
        int a[6];
    
        x = 10;
        a[3 * 2] = 2 * 3 * 7;
        printf("%d\n", x);
    
    mysteriously printed 42. How could this happen when x is clearly assigned only the value 10?

    How can you easily detect such errors before they have mysterious effects?

  8. Write a C program which reads numbers until non-numeric data is entered and then prints the middle number.

    So if 9 numbers were entered the program should print the 5th number entered. And if 27 numbers were entered the program should print the 14th number entered.

    If an even number of numbers is entered there are two middle numbers, print the first of them.

    For example if 8 numbers are entered, prints the 4th.

    You can assume at most 10,000 numbers will be entered.

    • Which Tim Tam rules potentially apply to this dice roll 6 6 6 6 6 6 and what scores do they produce.

    • What about this dice roll 1 1 2 2 3 9

    • Assignment 1 has 20% marks based on style. What are some things you can do to get good marks for this?

  9. What would the following fragment of code print out
    int x,y;
    int numValuesRead = scanf("%d %d",&x,&y);
    printf("I read in %d values : x = %d y = %d\n",numValuesRead,x,y);
    
    with the following inputs
    1. 3 4

    2. three 4

    3. 3.1 4

    4. ctrl^d

    5. 3
      ctrl^d

  10. A student has written this program to read ints until the end-of-input. It counts how many numbers it reads categorized by their last digit: Consider the following code
    #include <stdio.h>
    
    #define N 10
    
    int main(void) {
        int digitCount[N];
        int x, lastDigit;
    
        while (scanf("%d", &x) == 1) {
            lastDigit = x % N;
            digitCount[lastDigit] = digitCount[lastDigit] + 1;
        }
    
        lastDigit = 0;
        while (lastDigit < N) {
            printf("%d numbers with last digit %d read\n", digitCount[lastDigit], lastDigit);
            lastDigit = lastDigit + 1;
        }
    
        return 0;
    }
    
    
    It works on the students laptop:
    gcc -Werror -Wall -O -o last_digit last_digit.c
    ./last_digit
    42 121 100 11
    <ctrl-d>
    1 numbers with last digit 0 read
    2 numbers with last digit 1 read
    1 numbers with last digit 2 read
    0 numbers with last digit 3 read
    0 numbers with last digit 4 read
    0 numbers with last digit 5 read
    0 numbers with last digit 6 read
    0 numbers with last digit 7 read
    0 numbers with last digit 8 read
    1 numbers with last digit 9 read
    
    
    print counts of how many numbers read with each possible last digit.

    But when run at uni fails

    dcc -o last_digit last_digit.c
    ./last_digit
    42 121 100 11
    <ctrl-d>
    778121076 numbers with last digit 0 read
    7632239 numbers with last digit 1 read
    -2032569224 numbers with last digit 2 read
    32727 numbers with last digit 3 read
    0 numbers with last digit 4 read
    0 numbers with last digit 5 read
    -2032409578 numbers with last digit 6 read
    32727 numbers with last digit 7 read
    -21600000 numbers with last digit 8 read
    32767 numbers with last digit 9 read
    
    
    Why doesn't the code work at uni .

    Why doesn't dcc detect an error?

    Fix the code (make sure you understand how it works - its a common & useful programming pattern).

  11. Write a C program occur.c which reads 6 numbers then reads another number and prints how many times that number occurred in the first 6. For example:
    ./occur
    Enter 6 numbers: 1 3 1 3 1 9
    Enter a number: 1
    1 occurred 3 times in the 6 numbers read
    
    Make sure you make you make it very easy to change how many numbers the program reads. Note: For now let's do this without creating any functions.

  12. Repeat the previous question, but break it down into functions. It should behave the same way.

  13. Write a function with this prototype
    int arrayLength(int nums[])
    
    which returns the number of elements in the array nums.

  14. Write a function with this prototype
    int testAllInitialised(int nums[], int size)
    
    which returns 1 if all elements of array nums are initialized, otherwise returns 0.

  15. Write a function
    void sqrtIndex( double a[], int n )
    
    which takes an array a[] of n double values and sets each values to be the square root of their index.

    Hint: Use the math.h library function double sqrt(double) . How would you compile this if you were using gcc?

  16. Write a C function that returns 1 if an array of ints is in non-decreasing (ie increasing but potentially with duplicates) order, 0 otherwise,

    It should have this prototype:

    int nonDecreasing(double array[], int length)
    

  17. Write a C function dotProduct, that calculates the dot-product of two vectors of integers. Assume it has the following prototype
    int dotProduct(int vector1[VECTOR_LENGTH], int vector2[VECTOR_LENGTH])
    

    Reminder you calculate the dot product by multiplying corresponding elements and summing the result. For example the dot product of vector 1,3,1,3,2 and 2,1,2,1,2 would be 14

    1. What is the effect of each of the following statements? What are the initial values in the arrays?
      int nums1[10];
      

      int nums2[] = {0,1,2,3,4,5,6,7,8,9};
      

      int nums3[10] = {0,2,4,6,8,-2};
      

      int nums4[10] = {0};
      

      int nums5[2][10] = {{0,1,2,3,4,5,6,7,8,9},
                          {10,20,30,40,50,60,70,80,90,100}};
      

       int nums6[][10] = {{0},{9},{1}};
      

  18. What would the output of the following fragment of code be - given the array definitions above?
    int i;
    printf("%d\n",nums2[3]); 

    printf("%d\n",nums3[5]);

    printf("%d\n",nums5[0][1]);

    printf("%d\n",nums5[1][0]);

    nums1[0] = nums2[1] + 10 ; printf("%d\n",nums1[0]);

    i = 0; printf("%d\n",nums1[i]);

  19. What is wrong with the following piece of code - given the above array definitions?
    printf("%d\n",nums2[10]);   

    printf("%d\n",nums5[2][0]);

    printf("%d\n",nums5[1][10]);

  20. How many ints can the array matrix below hold?
    #include <stdio.h>
    
    #define N_ROWS 12
    #define N_COLUMNS 15
    
    int main(void) {
        int matrix[N_ROWS][N_COLUMNS];
    

    Write a function with the following prototype
    void initialiseMatrix(int matrix[N_ROWS][N_COLUMNS]);
    
    that uses nested while loops to set every element of matrix. Each element should be set to the product of its two indices.

    Write a function with the following prototype

    void printMatrix(int matrix[N_ROWS][N_COLUMNS]);
    
    that uses nested while loops to print the elements of matrix plus sums of each row and sums of each column.

    Write a main program that uses these functions

    The output of your code should look like this:

    ./a.out
        0    0    0    0    0    0    0    0    0    0    0    0    0    0    0 |    0  
        0    1    2    3    4    5    6    7    8    9   10   11   12   13   14 |  105
        0    2    4    6    8   10   12   14   16   18   20   22   24   26   28 |  210
        0    3    6    9   12   15   18   21   24   27   30   33   36   39   42 |  315
        0    4    8   12   16   20   24   28   32   36   40   44   48   52   56 |  420
        0    5   10   15   20   25   30   35   40   45   50   55   60   65   70 |  525
        0    6   12   18   24   30   36   42   48   54   60   66   72   78   84 |  630
        0    7   14   21   28   35   42   49   56   63   70   77   84   91   98 |  735
        0    8   16   24   32   40   48   56   64   72   80   88   96  104  112 |  840
        0    9   18   27   36   45   54   63   72   81   90   99  108  117  126 |  945
        0   10   20   30   40   50   60   70   80   90  100  110  120  130  140 | 1050
        0   11   22   33   44   55   66   77   88   99  110  121  132  143  154 | 1155
    ---------------------------------------------------------------------------
        0   66  132  198  264  330  396  462  528  594  660  726  792  858  924
    
  21. In lectures we wrote the following code but we only wrote code to check that all rows added up to the magic number. Complete the code to check the columns and the two major diagonals as well.
    // Read  SIZE x SIZE numbers and test if
    // they form a magic square http://en.wikipedia.org/wiki/Magic_square
    //
    //
    // Andrew Taylor - andrewt@cse.unsw.edu.au
    // 10/4/13
    
    /*
    //  Lo Shu Square
    // 4  9  2
    // 3  5  7
    // 8  1  6
    //
    // Magic square of primes
    //  17  89  71
    // 113  59   5
    //  47  29 101
    */
    
    #include <stdio.h>
    
    #define SIZE 3
    
    void readSquare(int square[SIZE][SIZE]);
    void printSquare(int square[SIZE][SIZE]);
    int sumFirstRow(int square[SIZE][SIZE]);
    int checkMagic(int square[SIZE][SIZE], int magicValue);
    
    int main(void) {
        int square[SIZE][SIZE];
        int row,col;
        int magicValue;
        int isMagic = 1;
        
        // read potential magic square
        printf("Enter %d numbers please:\n", SIZE*SIZE);
        readSquare(square);
        
        // print potential magic square
        printf("Numbers are:\n");
        printSquare(square);
        
        // Find magic value
        magicValue = sumFirstRow(square);
        
        
        isMagic = checkMagic(square,magicValue);
       
        
        if(isMagic == 1){
            printf("It is magic\n");
        } else {
            printf("It is NOT magic\n");
        }
        return 0;
    }
    
    
    void readSquare(int square[SIZE][SIZE]){
        int row,col;
        row = 0;
        while(row < SIZE){
            col = 0;
            while(col < SIZE){
                 scanf("%d",&square[row][col]);
                 col = col + 1;
            }    
            row = row + 1;
        }
    
    }
    
    void printSquare(int square[SIZE][SIZE]){
        int row,col;
        row = 0;
        while(row < SIZE){
            col = 0;
            while(col < SIZE){
                 printf("%d ",square[row][col]);
                 col = col + 1;
            }   
            printf("\n"); 
            row = row + 1;
        }
    
    }
    
    int sumFirstRow(int square[SIZE][SIZE]){
        int col;
        int sum = 0;
        
        col = 0;
        while(col < SIZE){
           sum = sum + square[0][col];
           col  = col + 1;
        }
        return sum;
    }
    
    
    int checkMagic(int square[SIZE][SIZE], int magicValue){
        int row,col;
        int isMagic = 1;
        int sumRow;
       
        //Check all other rows. We have already checked the first.
        row = 1;
        while(row < SIZE){
            //check the sum of the row
            col = 0;
            sumRow = 0;
            while(col < SIZE){
               sumRow = sumRow + square[row][col];
               col = col + 1;
            }
            if(sumRow != magicValue){
               isMagic = 0;
            }
            row = row + 1;
        }
        return isMagic;
    }