GNU C tut - gpk2000/Wiki GitHub Wiki

GNU's C tutorial Solutions

Note: The online tutorial is present here in pdf format

Chapter-1

  1. Explain the distinction between high levels and low levels

    High levels are constructed from low level objects in order to supress
    the level of detail. We can think of high level objects as black boxes. 
    It is convienient to take the working of a black box for granted for our
    purpose of using it.
    
  2. What is a “black box”?

    A black box is supposed to be a magic object that does the things we
    need it to do without knowing how it does it. More simply if we have
    to achieve something, we send the input into the blackbox and get the 
    correct results. We are not concerned with how these results are arrived.
    
  3. Name a few advantages to programming in the C language.

    - C is a high-level language that can offer much to the programmer
      than assembly language
    - C programs are portable unlike assembly programs
    - C has clear and simple syntax
    - You can use every resource of computer using C
    - and many more...
    

Chapter-2

  1. What is a compiler?

    A compiler is a set of programs that convert the source code (written in text)
    into executable code that can be loaded into the computer in-order to run it
    
  2. How does one run C program?

    In order to run a C program on a GNU/Linux system we use GNU's C compiler called 
    gcc and invoke it. After compiling the program we get an executable as output,
    then we type ./executable_name in order to run it from the shell.
    
  3. How does one compile C program?

    We compile a C program under GNU/Linux system using gcc program.
    
    gcc filename.c
    
    This results in an executable called a.out, we then run this program 
    by typing ./a.out in the shell.
    
  4. Are upper and lower case equivalent in C?

    No Upper case and lower case are not equivalent in C as C is case sensitive
    
  5. What the two main kinds of error that can occur in a program?

    The two main kinds of error that can occur in a program are 
    
    1. Compile time errors
    2. Run time errors
    
  6. If you had some C source code that you wished to call “accounts”, under what name would you save it?

    I would save it as accounts.c
    
  7. What would be the name of the executable file for the program in the last question?

    The executable file name of the compiled program would be accounts,
    assuming it is compiled as follows
    
    gcc -o accounts accounts.c
    
  8. How would you run this program?

    We would type ./accounts in the shell in order to run it.
    

Chapter-3

  1. What is a block?

    A block in C is enclosed using { and } braces. These blocks include 
    declarations, statements and other complex commands
    
  2. Does a C program start at the beginning? Where is the beginning?

    Every C program should have a main function, this is the starting point.
    
  3. What happens when a program comes to a ‘}’ character? What does this character signify?

    It means that we have completed writing a block or function.
    
  4. What vital piece of punctuation goes at the end of every simple C statement?

    Semicolon goes at the end of every simple C statement, this is to
    indicate compiler that we have ended our statement and everything
    next is a new statement.
    
  5. What happens if a comment is not ended?

    We get a compile time error say 'unterminated comment'
    

Chapter 4

  1. Write a function that takes two values a and b, then returns the value of a * b

    int multiply (int a, int b)
    {
        int result;
    
        result = a * b;
        return result;
    }
  2. Is there anything wrong with a function that returns no value?

    No, if a function does some independent work without returning any value
    then there is nothing wrong with it.
    
    Some examples including initializing a data-structure, cleaning a
    data-structure, these do not require any return values
    
  3. What happens if a function returns a value but you do not assign that value to anything?

    If we do not require the value returned by a function then there is no problem,
    else the returned value is lost.
    
  4. What happens if a variable is assigned the result of a function, but the function does not return a value?

    This is not advised as the variable can contain garbage value, the compiler
    warns you when you compile it.
    
  5. How can you make a program terminate, anywhere in the program?

    You can use the function exit with a specified exit codes, usually 0
    means that your program ran without any errors.
    

Chapter-5

  1. What is an identifier?

    An identifier is used to uniquely identify a variable
    
  2. Which of the following are valid C variable names?

    1. Ralph23          - valid
    2. 80shillings      - invalid begins with a number
    3. mission_control  - valid
    4. A%               - invalid contains non alphanumeric character
    5. A$               - invalid contains non alphanumeric character
    6. _off             - valid
    
  3. Write a statement to declare two integers called start_temperature and end_temperature.

    int start_temperature;
    int end_temperature
  4. What is the difference between the types float and double?

    Both types store decimal values, but the main difference between
    them is the precision. Double type variables have larger precision
    than float type variables
    
  5. What is the difference between the types int and unsigned int?

    Normally when we declare the type as int it is signed int, which
    means it hold both negative, zero and positive values in some defined
    range. Whereas in unsigned int the values are strictly non-negative.
    
  6. Write a statement that assigns the value 1066 to the integer variable norman.

    int norman = 1066;
  7. What data type do C functions return by default?

    Integer(int)
    
  8. You must declare the data type a function returns at two places in a program. Where?

    Unclear question??????
    
  9. Write a statement, using the cast operator, to print out the integer part of the number 23.1256.

    printf("%d", (int) 23.1256);
  10. Is it possible to have an automatic global variable?

    No, global variables should be either declared static or extern
    

Chapter-6

  1. What is a global variable?

    A global variable is declared outside of main and any other function,
    these variables can be accessed anywhere in the program
    
  2. What is a local variable?

    A local variable is declared inside a block i.e { and }, these variables
    are only visible to the block and you can't access them outside of such
    block.
    
  3. Do parameters spoil functions by leaking the variables into other functions?

    the what?
    
  4. Write a program gnoahs_park that declares 4 variables. Two global integer variables called num_gnus and num_gnats, and two local floating point variables within the function main, called avg_gnu_mass, and avg_gnat_mass. Then add another function called calculate_park_biomass, and pass avg_gnu_mass and avg_gnat_mass to it. How many different storage spaces are used when this program runs? (Hint: are avg_gnu_mass and avg_gnat_mass and their copies the same?)

    #include <stdio.h>
    
    // 2 global variables here
    int num_gnus;
    int num_gnats;
    
    void calculate_park_biomass (float avg_gnu_mass, float_avg_gnat_mass)
    {
        // 2 local variables here
    }
    
    int main() 
    {
        // 2 local variables here
        float avg_gnu_mass;
        float avg_gnat_mass;
    
        calculate_park_biomass (avg_gnu_mass, avg_gnat_mass);
    }

Chapter-7

  1. What is an operand?

    Operand are the values that are used together with operator to
    output some result
    
  2. Write a short statement that assigns the remainder of 5 divided by 2 to a variable called remainder and prints it out.

    int remainder = 5 % 2;
    printf("%d", remainder);
  3. Write a statement that subtracts -5 from 10.

    int result = -5 - 10;

Chapter-8

  1. What is the difference between a value parameter and a variable parameter?

    A value parameter is just a literal being passed into the function, whereas
    a variable parameter is passing a variable declared earlier into the function
    
  2. What is the difference between a formal parameter and an actual parameter?

    Formal parameters are the parameters names defined in the function signature
    whereas actual parameter are the values passed into the function when it is
    called.
    
  3. What does passing by reference let you do that passing by value doesn’t?

    Using pass by reference lets you modify the contents of the actual parameters
    whereas when passing by value you create copies of that actual parameter.
    
  4. Can a function call be used as an actual parameter?

    Yes, a function call can be used as an actual parameter if it has the
    same return type as declared in the function signature.
    
  5. Do actual and formal parameters need to have the same names?

    There is no need for actual and formal parameters to have same name.
    But I think it is a good style to make them same.
    

Chapter-9

  1. What is a pointer?

    A pointer is a variable that point to some data, that is they hold
    memory address of the data
    
  2. How is a variable declared to be a pointer?

    by prepending the variable name with a *
    ex: int *x
    
  3. What data types can pointers point to?

    Pointers can point to any data type
    
  4. Write a statement which converts a pointer to an integer into a pointer to a double type.

    int *x;
    double *y = (double *) x;
    
  5. Why is it incorrect to write float *number = 2.65;?

    We are declaring number to be a floating variable pointer, and it points to
    any address that contains 2.65.
    

Chapter-10


Chapter-11

  1. How many kinds of loop does C offer, and what are they?

    C offers three kind of loops
    
    for
    while
    do-while
    
  2. When is the condition tested in each of the loops?

    After executing the while code between the block once the 
    condition is tested again
    
  3. Which of the loops is always executed at least once?

    The do while loop is guarenteed to be executed atleast once
    
  4. Write a program that copies all input to output line by line.

    #include <stdio.h>
    
    int main() 
    {
        char input[100];
        while (scanf("%s", input) != EOF) {
            printf("%s\n", input);
        }
        
        return 0;
    }
  5. Write a program to get 10 numbers from the user and add them together.

    #include <stdio.h>
    
    int main() 
    {
        int total_sum = 0;
        for (int i = 0; i < 10; i++) {
            int num;
            scanf("%d", &num);
            
            total_sum += num;
        }
        
        printf("%d\n", total_sum);
        return 0;
    }
  6. Rewrite the nested loops example to print a square with while loops instead of for loops.

    #include <stdio.h>
    
    #define SIZE 5
    
    int main() 
    {
        int i = 0;
        while (i < SIZE) {
            int j = 0;
            while (j < SIZE) {
                printf("%c", '*');
                j += 1;
            }
            printf("\n");
            i += 1;
        }
        
        return 0;
    }

Chapter-12

  1. Define a macro called BIRTHDAY which equals the day of the month upon which your birthday falls.

    #define BIRTHDAY "XX-XX-XXXX"
    
  2. Write an instruction to the preprocessor to include the math library ‘math.h’.

    #include <math.h>
    
  3. A macro is always a number. True or false?

    No, a macro can be a string or a float or an integer etc...
    

Chapter-13

  1. How do you incorporate a library file into a C program?

    We use the #include preprocessor command to include a library
    file, and then use -l option on the command line if needed
    
  2. Name the most commonly used library file in C.

    The most commonly used library in C is glibc
    
  3. Is it possible to define new functions with the same names as standard library functions?

    You can define new functions with the same names as standard library
    when you don't include the header files, if you do include the header
    files then you can't redefine the functions with the same names as
    standard library functions.
    
  4. What type of data is returned from mathematical functions?

    double or long float
    
  5. True or false? All mathematical calculations are performed using doubles.

    True
    
  6. Name five kinds of error which can occur in a mathematical function.

    I only know one currently which is division by zero
    

Chapter-14

  1. Declare an array of type double, measuring 4 by 5 elements.

    double my_double_array[5] = {4.0, 4.0, 4.0, 4.0, 4.0};
    
  2. How do you pass an array as a parameter?

    as a pointer or using the normal array declaration
    
    void fun(int *arr);
    
    void fun(int arr[]);
    
  3. When an array parameter is received by a function, does C allocate space for a local variable and copy the whole array to the new location?

    No since we are passing a pointer we are passing the array by
    reference so no copy of the whole array will be created
    
  4. What does it mean to say that one dimension of an array “varies fastest”?

    In writing nested for loops inner variable changes fast than the outer
    this is what we mean when one dimension of an arry varies fastest
    
  5. Which dimension of an array varies fastest, the first or the last?

    The innermost i.e the last one
    

Chapter-15

  1. What are the three main ways of initializing string variables?

    char string1[] = "This is a string";
    char *string2 = "This is a string";
    char string3[30] = "This is a string";
    
  2. How would you declare an array of strings?

    char *str_array[];
    
    or
    
    char str_array[][100] remember the last dimension should be specified
    
  3. What information is returned by strlen?

    The length of the string not including the terminating character
    
  4. What does the function strcat do? How about strncat?

    strcat concatenates the two string and store the result in 
    the first string that was passed onto it
    
    strncat does the same but has an extra parameter that only
    concatenates n characters of the second argument
    
  5. Rewrite the Morse coder program more efficiently, using static strings. (See Section 10.6 [Example 15], page 60, for the original version.)

    #include <stdio.h>
    
    char *morse_code[] = {
        "-----",
        ".----",
        "..---",
        "...--",
        "....-",
        ".....",
        "-....",
        "--...",
        "---..",
        "----."
    };
    
    int main()
    {
        int digit;
    
        printf("Enter any digit in the range 0 to 9:\n");
        scanf("%d", &digit);
    
        if (digit < 0 || digit > 9) {
            printf("Your digit was not in between 0 and 9\n");
            return 1;
        }
    
        printf("%s\n", morse_code[digit]);
        return 0;
    }

⚠️ **GitHub.com Fallback** ⚠️