If-Else, While, Nested loops, functions and debugging in C - ALX SE week 3 Recap.

If-Else, While, Nested loops, functions and debugging in C - ALX SE week 3 Recap.

Surviving the probation phase

Last week, I mentioned how we started working with C programming language and how excited I was to show off my skills and creativity while learning.

This is where it gets interesting :)

We dug deeper into C programming language and concepts like Variables, if, else, while, functions, nested loops and debugging were covered.

In this article, I'll be explaining these concepts with different examples.

VARIABLES

A variable is a container for storing a value. It's a named memory location that can hold different types of values, such as numbers, characters, or pointers.

Here are some examples of variables with different types:

int age = 25;

Here, age is a variable of type int (integer) that stores the value 25. This means that the computer reserves a piece of memory with enough space to store an integer value, and assigns the name age to it.

float y = 3.14;

y is a floating-point variable that stores the value 3.14

char c = 'A';

c is a character variable that stores the value 'A'

char str[] = "Hello, world!";

str is a string variable that stores the value "Hello, world!".

Note: The string variable is declared as an array of characters, and initialized with a string literal enclosed in double quotes.

Variables can be used in many ways, such as performing arithmetic operations, comparing values, or passing arguments to functions. Understanding variables is an essential part of learning programming, as they are used extensively in writing code.

IF

The if statement is a control structure that allows you to execute a block of code only if a certain condition is true. The basic syntax of an if statement in C is:

if (condition) {
    // code to execute if condition is true
}

Here, the condition is a logical expression that evaluates to either true or false. If the condition is true, the code inside the block (i.e., the block after if) will be executed. If the condition is false, the code inside the block will be skipped and the program will continue with the next statement.

For example, the following code checks whether a given number is positive or negative using an if statement:

int num = -5;

if (num > 0) 
{
    printf("%d is positive.", num);
}

In the code above, the condition num > 0 checks whether num is greater than 0, which is true if num is positive. If the condition is true, the printf statement inside the block will be executed, which outputs that num is positive. If the condition is false (as in this case, where num is negative), the block is skipped and the program continues with the next statement.

You can also use logical operators such as && (and) and || (or) to combine multiple conditions in an if statement.

For example, the following code checks whether a given number is both positive and even:

int num = 4;

if (num > 0 && num % 2 == 0) {
    printf("%d is positive and even.", num);
}

In the code above, the condition num > 0 && num % 2 == 0 checks whether num is greater than 0 and it's remainder when divided by 2 is equal to 0, which is true if num is both positive and even. If the condition is true (as in this case, where num is positive and even), the printf statement inside the block will be executed, which outputs that num is positive and even. If the condition is false, the block is skipped and the program continues with the next statement.

ELSE

The ELSE statement is a control structure that works in conjunction with the IF statement. The ELSE statement allows you to specify an alternative block of code to execute when the IF condition is false. The basic syntax of an if-else statement in C is:

if (condition) {
    // code to execute if condition is true
}
else {
    // code to execute if condition is false
}

Here, condition is a logical expression that evaluates to either true or false. If the condition is true, the code inside the first block (i.e., the block after if) will be executed. If the condition is false, the code inside the second block (i.e., the block after else) will be executed.

For example, the following code checks whether a given number is positive or negative using an if-else statement:

int num = -5;

if (num > 0) {
    printf("%d is positive.", num);
}
else {
    printf("%d is negative.", num);
}

In this code, the condition num > 0 checks whether num is greater than 0, which is true if num is positive. If the condition is true, the printf statement inside the first block will be executed, which outputs that num is positive. If the condition is false (as in this case, where num is negative), the printf statement inside the block after else will be executed, which outputs that num is negative.

WHILE

The WHILE statement is a control structure that allows you to execute a block of code repeatedly while a certain condition is true. The basic syntax of a while statement in C is:

while (condition) {
    // code to execute while condition is true
}

Here, condition is a logical expression that evaluates to either true or false. The code inside the block will be executed repeatedly as long as the condition is true. The condition is checked at the beginning of each iteration of the loop, and if it is false, the loop terminates and the program continues with the next statement after the loop.

For example, the following code uses a while loop to print the first 5 positive integers:


int i = 1;

while (i <= 5) {
    printf("%d ", i);
    i++;
}

In this code, the condition i <= 5 checks whether i is less than or equal to 5, which is true for the first 5 positive integers. The printf statement inside the block outputs the current value of i. The i++ statement increments the value of i by 1 at the end of each iteration of the loop. As a result, the loop prints the values 1 2 3 4 5.

Logical operators such as && (and) and || (or) can be used to combine multiple conditions in a while statement.

For example, the code below uses a while loop to print all the even numbers between 1 and 10:

int i = 1;

while (i <= 10 && i % 2 == 0) {
    printf("%d ", i);
    i += 2;
}

In the code above, the condition i <= 10 && i % 2 == 0 checks whether i is less than or equal to 10 and it's remainder when divided by 2 is equal to 0, which is true for all even numbers between 1 and 10. The printf statement inside the block outputs the current value of i. The i += 2 statement increments the value of i by 2 at the end of each iteration of the loop. As a result, the loop prints the values 2 4 6 8 10.

FUNCTIONS

A function is a block of code that performs a specific task and can be called from other parts of the program. Functions allow you to organize your code and make it more organized, maintainable, and reusable. The basic syntax of a function in C is:

return_type function_name(parameter_list) {
    // code to perform the task
    return value;
}

return_type is the data type of the value that the function returns (such as int, float, char, or void if the function does not return any value).

function_name is the name of the function, which should be unique and descriptive.

parameter_list is a list of input parameters that the function expects, each parameter consisting of a data type and a parameter name.

The block of code inside the function's curly braces {} is the body of the function, where the actual task is performed using the input parameters and any other necessary variables.

For example, the following function calculates the sum of two integers:

int sum(int x, int y) {
    int result = x + y;
    return result;
}

In this code, the sum function takes two integer parameters x and y, adds them together, and assigns the result to a variable result. The return statement then returns the value of result as the output of the function.

To call a function from another part of the program, you simply use its name followed by the appropriate input arguments in parentheses.

example:

int main() {
    int a = 3;
    int b = 4;
    int c = sum(a, b);
    printf("The sum of %d and %d is %d\n", a, b, c);
    return 0;
}

In this code, the main function calls the sum function with the input arguments a and b, and assigns the output value to a variable c. The printf statement then outputs the result of the computation.

NESTED LOOPS

Nested loops are loops that are placed inside other loops. They allow you to perform repeated tasks on a two-dimensional or multi-dimensional array, matrix, or other data structures.

The basic syntax of a nested loop in C is:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        // code to perform the task
    }
}

Here, the outer loop controls the number of iterations that the inner loop will perform. The inner loop performs the actual task for each iteration of the outer loop.

For example, here is a code that uses nested loops to print a multiplication table:

for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= 10; j++) {
        printf("%d x %d = %d\n", i, j, i*j);
    }
}

In this code, the outer loop iterates over the values of i from 1 to 10, while the inner loop iterates over the values of j from 1 to 10 for each value of i. The printf statement inside the inner loop prints the product of i and j in a formatted way.

Other loop constructs such as while and do-while loops can be used inside other loops to create nested loops. However, you should be careful to avoid infinite loops and to ensure that the loops terminate correctly.

DEBUGGING

Debugging is the process of identifying and fixing errors or bugs in a program's source code. This is an important part of software engineering, because even experienced programmers can make mistakes when writing code. C programming language provides several tools and techniques for debugging code. One of the simplest and most effective ways to debug code in C is to use printf statements to print out the values of variables at various points in the program.

int main()
{
    int a = 3;
    int b = 4;

    printf("The value of a is %d and the value of b is %d\n", a, b);

    int c = a + b;

    printf("The sum of %d and %d is %d\n", a, b, c);

    return 0;
}

In this code, the printf statements are used to print the values of the variables a and b and the sum c after they have been computed. This can help you verify that the values are correct and identify any errors in the computation.

Another useful tool for debugging in C is the use of a debugger. A debugger is a program that allows you to step through your code line by line, set breakpoints, examine the values of variables, and perform other debugging tasks. Popular debuggers for C are gdb and lldb. This can help you identify errors and bugs in your code more easily than using printf statements alone.

For more tips on debugging, check this twitter thread:

CONCLUSION

In this article, we've covered some fundamental concepts of C programming like variables, if, else, while loops, functions, nested loops, and debugging with examples for better understanding. If you enjoy content like this, kindly follow me on Twitter, Linkedin, and Github.