Introduction to Programming: A Beginner's Guide to Loops, Functions, and Conditional Statements

Photo by KOBU Agency on Unsplash

Introduction to Programming: A Beginner's Guide to Loops, Functions, and Conditional Statements

Subtitle: Mastering the Building Blocks of Programming for Novice Coders

Introduction

The purpose of this article is to provide a brief introduction to programming for beginners or those looking to gain a basic understanding of the subject matter. This course explores fundamental concepts and ideas related to programming and is intended for individuals who have little or no programming experience. At the end of this article, I hope to get you buzzing about running your first program.

What is Programming?

Programming involves creating a set of instructions that tell a computer what to do and how to do it. The instructions are called programs. An individual who instructs a computer to perform a task is referred to as a programmer. Computers only understand machine language, also known as binary code, so programmers use programming languages to communicate with computers. Programming languages are classified based on their level of abstraction and proximity to machine language, including low-level and high-level languages:

Low-Level Language

Low-level languages(LLL) are more similar to machine language than human language, making them more challenging to comprehend than high-level languages. They are constructed to be more abstract and effective in communicating with computer hardware systems. Low-level languages offer programmers greater precision and control over hardware components. Some examples of low-level languages include Machine language and Assembly Assembly Language:

  1. Machine code

    Also known as machine language is the most fundamental language that a computer can comprehend. It is the original language used by computer software and hardware. All languages must be converted to machine code for the computer to perform any operation. Machine code comprises binary codes corresponding to specific instructions to be executed by the hardware.

  2. Assembly language

    This is another type of low-level language. Assembly language is a step above machine language and employs specific mnemonics such as ADD, JMP, MOV, etc. to interact with the computer. Assembly language is more precise and efficient than higher-level languages but remains challenging to comprehend. However, it is easier to read than machine code. As the computer only understands binary code, assembly language must be translated to machine code by an assembler.

Due to the complexity of low-level languages and issues such as portability, higher-level languages were developed to enable programmers to interact with computers more easily.

High-Level Language

High-Level Language(HLL) is later than low-level languages. They are programming languages that reduce the abstraction and complexity of working with Low-Level language. HLLs are designed in such ways that humans can easily write programs and solve problems without having to focus on LLL implementation details such as memory management or hardware-specific operation. HLL provides features such as advanced data structures, frameworks, libraries, Object-Oriented Programming, and standard error-handling mechanisms HLL also supports unique syntax and constructs for solving logical problems and algorithms. Some examples of HLL are:

  • JavaScript

  • C

  • Python

  • PHP

  • Ruby etc

However, as the level of abstraction of these languages is high, humans can easily understand them. However the computer cannot understand these languages, therefore they must be compiled or interpreted into machine code that the computer processor can understand.

Programming Concepts

Similar to the diversity of human languages, computer programming languages also vary in how they convey messages and instructions. While the specific syntax and structure differ between languages, they share common underlying concepts. This can be likened to the way different languages express the same instruction, such as how "come" is said differently in Chinese and French. Programming languages exhibit similar variations in their expression of instructions, yet adhere to shared principles and concepts.

Fundamental concepts adhered to by all programming language includes:

  • Loops

  • Function

  • Conditional Statements

Loops

A loop is a programmed sequence of instructions that is repeated until or while a particular condition is satisfied. This concept of repetition and iteration is fundamental to understanding loops in programming.

To explain loops, let's consider the act of counting the number of apples in a basket. Imagine you have an empty basket and you went to a farm to pick all apples from the soil, and you want to continue picking until there are no apples left on the soil. likewise, you want to count how many apples you picked. You can use a loop to systematically go through each apple and keep track of the count.

1. Initial setup:

  • I declare a variable called count and set the value to zero. A variable is an address used to store a value in the computer memory This variable will keep track of the number of apples counted.
  1. Looping through the apples:

  2. Picking up the first apple and putting it into the basket.

  3. Increment the count by one to signify that you have counted one apple.

  4. Move to the next apple and repeat number 1 above.

  5. Repeat the process of incrementing the count variable and moving to the next apple until there are no more apples on the soil.

3. Loop termination:

  • The loop will terminate when you have picked up every apple from the soil.

  • At this point, you can check the value of the count to know how many apples were counted.

Every programming language provides the concept of a loop although their syntax may differ. There are three general forms of loop:

  • for

  • while

  • do-while

  1. For-loop: The "for" loop is recognized by its initial "for" expression, which includes three expressions separated by semicolons. These expressions are as follows:
for (expression1; expression2; expression3) 
{
   // Statement;
}
  • Expression 1: This expression initializes a variable, such as a counter in the case of counting apples.

  • Expression 2: This expression is a condition that must be true for the loop to continue. For example, the loop will continue as long as there are apples on the floor.

  • Statement: If expression 2 is true, the statement is executed, and then the flow moves to expression 3. In the apple analogy, the statement would be to put the apples in the basket.

  • Expression 3: This expression is an increment or decrement expression. After executing the statement, this expression is executed, and then the flow returns to expression 1. For instance, in our example, expression 3 would increase the count variable's value.

The code below is a Javascript program for for-loop.

#include <stdio.h>
int main(void)
{
    int count = 0;
    int num_of_Apples_on_Soil;
    num_of_Apples_on_Soil = 10;    

    for (count = 0; num_of_Apples_Soil != 0; count+=1) {
        num_of_Apples-=1;
     }

    printf("%d", count);
    return (0);
}
  1. The code begins with #include <stdio.h>, which is a preprocessor directive that includes the standard input/output library. This library provides functions like printf for displaying output on the screen.

  2. The main function is the entry point of the program.

  3. int count: initializes a count variable of int data type.

  4. num_of_Apples_on_Soil: Declared the variable num_of_Apples_on_Soil and initialize it to store value 10.

  5. Count = 0: Initialises the count to 0 because we haven't started picking mangoes and putting them in the basket.

  6. num_of_Apples_on_Soil is not equal != 0: The second expression implies - As long as num_of_Apples_on_Soil is not equal ( != ) 0

  7. num_of_Apples_on_Soil += 1: Subtract one apple (Pick up 1 apple from the soil).

  8. count+= 1: Add 1 to Increase count.

This loop is done repeatedly until number 4 above becomes false.

Here's a flow chart that illustrates the execution of an if-else statement:

While loop: The while loop is another method of iteration and would continue iterating until the condition becomes false. The general format for the while loop is:

while (expression) {
     //Statement;
}

The idea is that the code inside the loop, (statement; above) will eventually cause the expression to be logically false the next time it is evaluated, thus terminating the loop.

Here, expression is the condition of the whole statement. This expression is evaluated first. If the expression evaluates to a nonzero value, then the statement is executed. After that, the expression is evaluated once again. The statement is then executed one more time if the expression still evaluates to a nonzero value. This process is repeated over and over until the expression evaluates to zero, or logically false.

Below is a C program using the while-loop:

#include <stdio.h>
int main(void)
{
    int count;
    count = 0;
    int num_of_Apples_on_Soil
    num_of_Apples_on_Soil = 10;  

    while (num_of_Apples_on_Soil != 0) {
        num_of_Apples_on_Soil -= 1;
        count+=1
}
    printf("%d", count);
    return (0);
}
  1. int count: We declared a variable count with a special keyword let.

  2. int num_of_Apples_on_Soil: Declare a variable called num_of_Apples_on_Soil and initialize it to store value 10.

  3. while ( num_of_Apples_on_Soil != 0): This condition demands that as long as the num_of_Apples_on_Soil does not equal 0.

  4. num_of_Apples_on_Soil -= 1: Decrement the number of Apples by 1

  5. Count += 1: Put 1 apple in the basket, Increment count by 1.

  6. while loop: The while loop is used in cases where we may not know the amount of time to iterate but we want the iteration to continue until something happens.

Here's a flow chart that illustrates the execution of a while-loop:

  1. do-while: The do-while loop has a structure similar to the while-loop. In a while loop, the statement is executed only if the condition is true. The key difference with the do-while loop is that the statement is executed at least once before the condition is evaluated for iteration. The general format for the do-while loop is as follows:
do 
{
 statement. . .
} while (expression);

In this format, the code statements within the curly braces are executed first, and then the condition is evaluated. If the condition is true, the loop continues to iterate, executing the code statements again. This process continues until the condition becomes false, at which point the loop terminates and the program continues with the next statement after the loop.

Below is the javascript code for the do-while loop:

#include <stdio.h>

int main(void)
{
    int count;
    count = 0;
    int num_of_Apples_on_Soil;
    num_of_Apples_on_Soil = 10;

    do {
        num_of_Apples_on_Soil -= 1;
        count += 1;
    } while (num_of_Apples_on_Soil != 0)

    printf("%d", count);
}
  1. int count: We initialized a count variable to store value 0

  2. int num_of_Apples_on_Soil: initialized variable num_of_Apples_on_Soil to store value 10.

  3. do {....}: First perform the operations inside the curly brace. Here, the number of apples is decremented by 1 and the count is incremented by 1.

  4. while (num of apples != 0): number 3 above is executed again, as long as this condition remains true.

Here's a flow chart that illustrates the execution of a do-while loop:

Conditional Statements

Programming languages also incorporate conditional statements as a fundamental principle. These statements are executed only when specific conditions are met. The three primary types of conditional statements are:

  • the if-else statement

  • Ternary operation

  • switch statement

  1. If-else statement: The if-else statement is a conditional statement that allows for the execution of different statements depending on a given condition. The structure of an if-else statement is as follows:
if (condition) {
    // Code statements executed if the condition is true
} else {
    // Code statements executed if the condition is false
}

In this structure, the condition is evaluated. If the condition is true, the code statements within the first set of curly braces are executed. If the condition is false, the code statements within the second set of curly braces (else block) are executed.

The if-else statement provides a way to control the flow of execution in a program based on specific conditions. It allows for branching behaviour, enabling different code paths to be followed depending on the outcome of the condition evaluation.

Let’s create a program that allows only people 18 years and above to vote. Here is a C program for it:

#include <stdio.h>
int main(void)
{
    int age;
    printf(“Enter your age: “);
    scanf(“% d, & age);
    if (age >= 18)
        printf(“Thanks for voting!!”);
    else
        printf(“Go home!! You are not at the age of franchise”);
    return 0;
}

The following components are included in the program:

  • int age: declares a variable of integer data type named age.

  • printf: displays a message asking the user to input their age.

  • scanf: retrieves and stores the user's age input to the age variable.

  • The if condition checks if the age variable is greater than or equal to 18.

  • If true: a message indicating successful voting is displayed.

  • If false: the statement in the else block is executed.

Here's a flow chart that illustrates the execution of a conditional statement:

  1. Ternary operation: The ternary operation follows the same flow as the if-else statement, but it is a more concise and modern version of the conditional statement. It allows you to assign a value to a variable based on a condition.

It offers better readability and scalability than the if-else statement. The syntax of a ternary conditional statement typically follows this format:

(variable condition) ? value_if_true : value_if_false

Here's how it works:

  1. The condition is evaluated. If the condition(value) is true, the expression returns value_if_true.

  2. If the condition is false, the expression returns value_if_false.

Here's an example in C:

    #include <stdio.h>
    int main(void)
    {
        int age;
        age = 35;
        (age >= 18) ? printf("You are qualified to vote!") : (printf("Go home kiddo!"); 
        return (0);
    }

In this example,

  • the variable age is assigned 35

  • if the age is greater than or equal to 18; print You are qualified to vote!

  • otherwise, print Go home kiddo! .

Ternary conditional statements are particularly useful when you need to assign a simple value based on a condition without writing a full if-else statement. However, it's important to use them judiciously to maintain code readability and avoid nesting complex expressions within the ternary operator.

  1. Switch Statement: The switches statement is another form of a conditional statement that operates based on an expected value. The switch statement allows you to select one of several code blocks to execute based on the value of a given expression. It provides a more concise and structured way to handle multiple possible cases than using multiple if-else statements.
    switch (expression) {
        case constant1:
            // Code block executed when expression matches constant1
            break;
        case constant2:
            // Code block executed when expression matches constant2
            break;
        case constant3:
            // Code block executed when expression matches constant3
            break;
            // Add more cases as needed
        default:
        // Code block executed when expression does not match any of the constants
        break;
}

Here's how the switch statement works:

  1. The expression is evaluated once and its value is compared to each case constant.

  2. If the value of the expression matches a case constant, the code block associated with that case is executed. The break statement is used to exit the switch statement and prevent the execution of subsequent cases.

  3. If the value of the expression does not match any case constant, the code block associated with the default case (optional) is executed. The default case is used as a catch-all for values that don't match any specific case.

Note that the expression in the switch statement must be an integral type (such as int, char, enum) or a compatible data type. Likewise, If the value of an expression matches a case constant and the break statement is omitted from the switch statement, the code block associated with the case constant and the subsequent ones would be executed.

The switch statement is a valuable tool when dealing with scenarios that require multiple condition checks. Its primary advantage lies in its ability to streamline code and eliminate the need for repetitive if-else structures.

One practical application of the switch statement is in determining the day of the week based on numerical inputs.

To illustrate this, consider the following example:

#include <stdio.h>
int main(void) {
    int day;
    scanf("%d", &day);
    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        default:
            printf("Invalid day\n");
            break;
    }
    return 0;
}

In this code snippet, the switch statement efficiently determines the corresponding day of the week based on the value of the day variable. The scanf retrieves input from the user and stores the value in the age. By comparing the value against predefined cases, the appropriate day is identified and displayed. The default case handles situations where the input does not match any of the expected values, ensuring that "Invalid day" is printed as a fallback.

Using the switch statement in such cases promotes cleaner and more concise code, enhancing code readability and maintainability. Its ease of use and effectiveness make it a powerful tool in modern programming practices.

Functions

Functions serve as the foundation of a program, as they are essentially blocks of code that execute a specific task. Large programs, such as Facebook, Twitter, and Google, are comprised of thousands of lines of code, which are constructed using functions that call upon one another. It's important to note that these complex codebases didn't just materialize overnight. Instead, they began with a simple line of code that was encapsulated within a function and then expanded to include thousands of lines.

As such, understanding functions is crucial for programmers. Utilizing functions is a best practice for writing shorter, cleaner, and more scalable code.

Below is a simple program that checks whether an integer variable a is divisible by 12 or not. Here's a breakdown of the code:

#include <stdio.h>
//a program that tells us if a number is divisible by 12 or not.
int main(void)
{
    int a;
    a = 120;

    if ( a % 12 == 0)
        printf("Yes it divisible by 12");
    else
        printf("No it is divisible by 12");
    return (0);
}
  1. An integer variable a is declared using the int keyword.

  2. The value 120 is assigned to a using the assignment operator =.

  3. The if statement is used to check if a is divisible by 12. The condition a % 12 == 0 checks whether the remainder of the division of a by 12 is equal to 0. If the condition is true, the code inside the if block will execute. Otherwise, the code inside the else block will execute.

  4. If a is divisible by 12 (remainder is 0), the program prints "Yes, it is divisible by 12" using the printf function.

  5. If a is not divisible by 12 (remainder is not 0), the program prints "No, it is not divisible by 12" using the printf function.

  6. The return (0) statement indicates the end of the main function and returns the value 0 to the operating system, indicating that the program executed without errors.

The program we wrote was interesting because it can check if a number is divisible by 12 without a remainder. But what if we want to check many numbers, like 34, 60, 12, 89, and 132? We might think to repeat the same thing we did before for each number. However, in programming, there's a popular acronym called DRY (Don't Repeat Yourself).

Functions allow us to do a task many times with different values without writing the same program again. In the example below, we use a function called void div_by_12 to check if 34, 60, 120, and 132 are divisible by 12 without a remainder.

#include <stdio.h>
//a program that tells us if a number is divisible by 12 or not.
void div_by_12(int x);

void div_by_12(int x)
{
    if (x % 12 == 0)
        printf("Yes it divisible by 12");
    else
        printf("No it is divisible by 12");
    return (0);
}

int main(void)
{
    int a, b, c, d;
    a = 120;
    b = 34;
    c = 60;
    d = 132;
    // call the functions
    div_by_12(a);  //output: Yes it divisible by 12
    div_by_12(b);  // output: No it is divisible by 12
    div_by_12(c);  //output: Yes it divisible by 12
    div_by_12(d); // output: Yes it divisible by 12
    return (0);
}

Let's break it down step by step:

  1. There's a function declaration: void div_by_12(int x);. This line tells the compiler that there is a function named div_by_12 that takes an integer parameter x and doesn't return any value (void).

  2. The actual implementation of the div_by_12 function is provided after its declaration. The function takes an integer input x and performs a check to see if x is divisible by 12. It uses the modulus operator % to calculate the remainder of dividing x by 12. If the remainder is 0, it means x is divisible by 12, so it prints "Yes, it is divisible by 12". Otherwise, it prints "No, it is not divisible by 12".

  3. In the main function, four integer variables a, b, c, and d are declared and assigned some values.

  4. The div_by_12 function is called four times with different variables as arguments: div_by_12(a), div_by_12(b), div_by_12(c), and div_by_12(d). This means that the function will be executed four times, each time with a different number.

  5. Finally, the return (0); statement indicates the end of the main function and returns the value 0 to the operating system, indicating the successful execution of the program.

When you run this program, it will check each of the four numbers (a, b, c, d) and print whether they are divisible by 12 or not. This allows you to see the result for multiple numbers without duplicating the code.

Further Concepts

Some other concepts include Operations such as:

Relational Operation: Relational operators compare numeric, character string, or logical data. The result of the comparison, either true ( 1 ) or false ( 0 ), can be used to make a decision regarding program flow.

Logical operation: The logical operators evaluate the logical expression and return a result. The result is always a Boolean value. A Boolean value determines whether the expression is true or false.

Bitwise Operation: Bitwise operators like the NOT(~) operator, which changes each 0 bit to 1 and each 1 bit to 0.

Arithmetic operation: An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values.

Summary

The journey of a thousand miles begins with a single step

-Anonymous

This saying also applies to becoming a programmer. As you start your journey as a programmer, don't worry too much about the technical words you hear. Although It's a big, exciting, and competitive field, it takes hard work to succeed. But once you learn the basics, things become easier. Even if you have to learn a new programming language, you just have to make small adjustments.