The C programming language

The C programming language

week 1/4 - Chapter 1

  • In this series of articles I journal my C programming language learning journey through Dennis M Ritchie's book, The C Programming Language.
  • I have been dodging learning C for quite a while now but was left with no option when I realised I had it for the semester. Found out this kind of makes understanding quite easier , I don't know if its just me but you should maybe try it and see how it goes.
  • If one is already good at any statically typed programming language , preferably C++, this should be fairly easy.
  • The famous 'hello world' in C .
  • All you have to do here is write the code , save the file with a .c extension, compiile , load the program and voila.
    #include <stido.h>
    int main()
    {
    printf("hello world \n");
    return 0;
    }
    
  • To run a C program on any unix machine.
    cc program_name.c
    
  • This will create an executabe under the name a.out. Execute ./a.out to run it.
  • #include <stdio.h> tells the compiler to include the stdio.h header.
  • A header is file one with function declarations and macro definitions to be shared across various C source files, it could be likened to modules in python.
  • Every C program starts always it's execution from the main function. All other functions defined in the source file are then called from within it.
  • A function in C takes the format
    return_type function_name(function_parameters){
             function statements;
             return_statement;
    }
    
  • The main function by default has a return type of int but not explicitly defining it will result in a warning from the compiler.
  • A return statement serves to carry feedback to the calling function on whether the function was successfully run or not, or give back processed results to caller depending on how it was written.
  • The main function returns either 0 or 1 to the caller which is the system's operating system. 0 sugnifies the program was run without any errors and 1 is returned in case of any error in execution.
  • printf is a function for streaming data to the screen. In the hello program it takes on one argument, the text to be displayed.
  • All function calls take on the fn_name(arguments) format in a C program .
  • A function could be defined to take on no arguments.
  • Argumets are values passed on to the function by the caller, Parameters are names given to holders of arguments in function definitions .
  • Notice the argument passed on to printf which is a string , is enclosed in double and not single quotes. A character constant is one enclosed between single quotes , e.g. 'A' is an integer and would return the integer representation of 'A' in the machine's character set.
  • "A" on the other hand is an array of characters A and \0.
  • \0 is a nullbyte character used to tell the compiler where a string terminates.
  • A string is a sequence of 0 or more characters enclosed in double quotes.
  • Function statements are enclosed with in curly braces {} and each statement ends with a semi colon ;.
  • The escape sequence \n denotes a new line . C , unlike python ,does not automatically add newline characters at the end of lines and therefore not doing so would lead to cramping of all text printed out to the screen to one line.
  • It is also illegal to span a string over multiple lines without the right kind of formatting. For instance;
    int main(){
       printf(" Hello world
                    program\n");
      return 0;
    }
    
  • The right formatting for such a scenario would be;
    int main(){
       printf(" Hello world"
                    "program\n");
      return 0;
    }
    
  • Other escape sequences include;
    • \t for tab
    • \b for backspace
    • \v for vertical tab etc etc...

Screenshot from 2022-10-12 23-16-37.png

  • Comments in C are put between "forward slash asterisks" /* Comment */. Anything between these will be ignored by the compiler and not be run. The above format is used for multi line comments btw. For single line comments , double forward slashes are used i.e. // comment.
  • The above program converts temperature values from the Celcius degree scale to the fahrenheit scale with the formula oC=(5/9)(oF-32).
  • The format data_type variable[s]; is used when decalring variables in C.
    int num1, num2, num3; // declares 3 int type variables num1, num2 and num3
    
  • The alteration in the formula during the assignment operation on line 16 is to prevent data loss. This is because integer division in C would result in truncating of any floating point numbers in the quotient . For example 5/2 would result in 2 instead of 2.5.
  • However , if need be , the float data type is used for such kind of division.
  • Talking of data types, More data types in C include:
    • float with size of 4 bytes
    • double with twice the size of a float
    • char with size of 1 byte
    • int with size of 4 bytes and range (-2147483648, 2147483647)
    • long int [ double the size of an int, used for storing large integers]
    • short int [ half the negatives and positives in int]
    • unsinged int [ same size as int but only posotive integers , range is 4294967295] , long long, etc etc
  • Integer variables to be used are defined on lines 7 and 8, some are then assigned values on lines from 10 to 12.
  • The integer variable fahr is assigned the value stored in lower.
  • A while loop is then used for the rest of the program execution. Simple pseudo for while loop template;
    while (condition is true) {
           /*  run this code;
               run this code;*/
        }
    
  • The statements within the curly braces will only be run so long as the conditional check within the braces evaluates to True.
  • C programs don't care much about indentation but for readability issues it's a good practice to have some uniform indentation for C code.
  • The %d in the printf function on line 17 is used when displaying integer variables. It tells C the corresponding argument is an integer.
  • Other place holders like %d include:
    • %f for float
    • %p for pointer
    • %x for conversion to octal base
  • From line 17 , for every iteration of the while loop , the celcius value for the then current value of fahr will be caluculated and printed out along side its Fahrenheit value.
  • Output from the printf funtion in the while loop is in the format Fahrenheit_value Tab Celcius_value New_line.
  • If the condition evaluates to false in the while loop, the loop automatically breaks and the lines are executed if any.
  • Other loops in C include for loops do while loops.
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
      printf("%d is a leap year\n", year);
    else
       printf("%d is not a leap year\n", year);
    
  • The above program is used for determining if a year is leap or not.
  • A year is a leap year if it is divisible by 4 but not by 100, except that years divisible by 400 are leap years.
  • The operator % is used to get the remainder when a one number is divided by another. For example 5%2 would give 1 as the answer.
  • The == arithmetic operator is used to check for equality of the terms on its left and right. It returns True if they are equal and False if otherwise.
  • && is the AND operator only evalutes to true if both the checks on its left and right evaluate to True. Remember 0 carries a value of False and 1 a value of True in C . Therefore a check like 0 && 0 would evaluate to False and so would 1 && 0. 1 && 1 however would evaluate to True.
  • || is the OR operator . Unlike the AND operator , it evaluates to True if any of the conditions on its left and right are met . Take an example of 0 || 1 that would return a value of True. 0 || 0 however will return False.
  • More arithmetic operators in C include:
    • * for multiplication
    • + for addition
    • / for division
    • != for Not equal to
    • <= for less than or equal to etc etc
  • Back to the leap year code. Due to character precedence and associativity, the use of braces is used to direct the intended order of operation in most C programs . You could liken this to the use of braces in maths. The order of calculations follows a simple rule PEMDAS i.e. Parentheses, Exponentials, Multiplication, Division, Addition, Subtraction. More information on associativity and precedence here.
  • The code uses an if statement to check if the year is either (perfectly divisible by 4 AND is not perfectly divisible by 100) or (the year us perfectly divisible by 400).
  • If the condition evaluates to True, then the program prints to the message a screen saying the year is a leap year.
  • Otherwise (the else part of the if statement) ,the check has failed and therefore the year doesn't qualify as a leap year, which is printed to the screen.
  • Wheeew ..... what a long one ... more in the book, till we meet again in Chapter 2, drop that comment and reaction if you may😀... ✌️