Monday, April 28, 2025

C Tutorial - 17 - Functions

What are Functions in Programming and why do we need them

Functions are blocks of code that are designed to perform a specific task. They are self-contained and can be used repeatedly within a program, which makes code more modular, easier to understand, and easier to maintain.

Functions in programming provide a way to break down complex problems into smaller, more manageable pieces. By using functions, a programmer can divide a program into smaller, more manageable pieces that can be developed, tested, and debugged independently. Functions can be used to improve the readability of code by breaking it up into smaller, more understandable parts.

Functions are also useful for code reuse. When a particular task needs to be performed multiple times, it is more efficient to create a function that can be called repeatedly rather than writing the same code over and over again. By using functions, a programmer can avoid duplicating code and reduce the chances of introducing errors.

Overall, functions are an essential part of programming because they allow programmers to create more organized, efficient, and reusable code.

 

Example of multiple Functions

#include <stdio.h>

void someFunction()
{
    printf("I am from Some Function \n");
}

void callerMITM()
{
    someFunction();
    someFunction();
    someFunction();
}

void simpleCalc()
{
    int x = 10;
    int y = 20;
    int result = x + y;

    printf("--------------------- \n");
    printf("Result: %d \n", result);
    printf("--------------------- \n");

}

void pingGoogle()
{
    system("ping google.com");
}

int main()
{

    //callerMITM();
    //simpleCalc();
    //system("calc");
    pingGoogle();

    return 0;
}

This program defines several functions, namely someFunction(), callerMITM(), simpleCalc(), and pingGoogle().

someFunction() simply prints a message to the console.

callerMITM() calls someFunction() three times.

simpleCalc() defines two integer variables, x and y, adds them together, and prints the result to the console.

pingGoogle() uses the system() function to execute the command ping google.com, which sends a ping request to Google's servers and displays the results in the console.

In main(), different functions are called by uncommenting the relevant lines of code. callerMITM() calls someFunction() three times, simpleCalc() adds two integers and prints the result to the console, and pingGoogle() sends a ping request to Google's servers and displays the results in the console.

 

Why do we need to use () while naming functions

In C programming, parentheses are used to denote a function. When we declare a function, we use parentheses to indicate that it's a function and not a variable or some other data type. For example, if we want to declare a function named "myFunction", we write it as:

void myFunction() {
    // code here
}

Here, the parentheses after "myFunction" indicates that it is a function. When we call a function, we also use parentheses to pass arguments to the function. For example:

myFunction(arg1, arg2);

Here, the parentheses after "myFunction" indicate that we are calling a function, and the arguments are enclosed within the parentheses.

Therefore, parentheses are an essential part of function declaration and calling in C programming.

 

What is void

In programming, void is a keyword used to indicate that a function does not return any value. When a function is declared with a void return type, it means that the function will perform some operations but will not return a value.

For example, the following function takes two integers as input and prints their sum, but does not return any value:

void sum(int a, int b) {
    int result = a + b;
    printf("The sum is: %d", result);
}

Since the return type is void, we know that the function will not return any value, but will only print the result on the console.

 

Does that mean "Direct Action Fuctions"

Void is a data type in C that is used to indicate the absence of a value. When a function's return type is void, it means that the function does not return any value. In other words, it is a direct action function that performs a task or operation without returning a value. This is useful for functions that perform actions such as printing output or modifying variables, but do not need to return a specific value to the caller.

 

What "Return from Function" means

A function in programming can return a value to the calling program or function using the return statement. When a function is called, the calling program or function may need to receive a value or information from the called function. This is where the return statement comes in.

The return statement in a function is used to return a value or information to the calling program or function. The value or information returned by the function can then be used by the calling program or function.

In some cases, a function may not need to return a value. In such cases, the void keyword is used in the function definition to indicate that the function does not return a value. The void keyword can also be used in place of a return type in function prototypes to indicate that the function does not return a value.

 

Do we need to be specific about data type that function returns

Yes, it is important to specify the data type that a function returns. The data type that a function returns indicates what kind of data the function will return to the caller. If a function does not return any data, you can use the void data type to indicate this. However, if a function does return a value, you should specify the data type of the returned value in the function declaration and definition, using the appropriate data type keyword (e.g., int, float, char, etc.). This helps to ensure that the data returned by the function is correctly interpreted and used by the calling code.

 

Can we define functions inside main() function

No, functions cannot be defined inside main() function in C programming language. All functions in C must be defined outside of main() function. It is possible to declare a function inside main() function, but the function definition must be outside of main().

For example, the following code is valid:

#include <stdio.h>

void myFunction(); // function declaration

int main() {
    myFunction(); // function call
    return 0;
}

void myFunction() { // function definition
    printf("Hello, world!");
}

However, defining a function inside main() function is not allowed in C.

 

What is function "declaration" and "definition"

In C programming, a function declaration tells the compiler about the existence of a function and the data types of its parameters and return value, but does not provide the actual implementation of the function.

A function definition, on the other hand, not only declares the function but also provides the actual code that implements the function.

In other words, a function declaration is a promise to the compiler that the function will be defined later in the program, while a function definition provides the actual implementation of the function.

Here's an example of a function declaration:

int addNumbers(int a, int b);

And here's an example of a function definition:

int addNumbers(int a, int b)
{
    return a + b;
}

In this example, the function addNumbers is declared with its parameter data types and return value data type in the declaration. Later, the function is defined with the actual code that adds the two input parameters and returns the result.

 

Can we have function declaration after main() function

Yes, we can have function declaration after the main() function, as long as the function is defined before it is called. This is because function declarations only provide the function prototype (the function signature with its parameter list and return type) to the compiler, allowing it to recognize the function's name and signature when it is called elsewhere in the program. The actual function definition can be located elsewhere in the program or even in a separate source file. However, it is generally considered good programming practice to declare functions before they are called to ensure that the program is properly organized and easy to read.

 

C Tutorial - 16 - Pointer to Pointer

#include <stdio.h>

int main()
{
    int original = 5;

    //Primary Pointer
    int * priPointer = &original;
    int ** secPointer = &priPointer;

    printf("Address with Pointer: %p \n", priPointer); //Address
    printf("Address without Pointer: %p \n", &original); //Address
    printf("Address of Primary Pointer: %p \n", secPointer); //Address of Address

    printf("------------------------------------------------ \n");

    printf("Value using Variable: %d \n", original);
    printf("Value using Primary Pointer: %d \n", *priPointer);
    printf("Value using Secondary Pointer: %d \n", **secPointer);

    return 0;
}

Result:

Address with Pointer: 000000000061FE14
Address without Pointer: 000000000061FE14
Address of Primary Pointer: 000000000061FE08
------------------------------------------------
Value using Variable: 5
Value using Primary Pointer: 5
Value using Secondary Pointer: 5

Process returned 0 (0x0)   execution time : 0.022 s
Press any key to continue.

This program demonstrates the use of multiple levels of pointers in C programming.

In this program, we have defined an integer variable original with a value of 5. Then, we have created a primary pointer priPointer which points to the address of original using the & operator.

After that, we have created a secondary pointer secPointer which points to the address of priPointer. This means that secPointer contains the address of priPointer.

We can print the addresses of original, priPointer, and secPointer using the %p format specifier in the printf() function.

To access the value of original through the pointers, we use the * operator. We can print the values of original, priPointer, and secPointer using the printf() function and the * operator.

Finally, we can access the value of original using the secondary pointer secPointer by dereferencing it twice with the ** operator.

Multiple levels of pointers are useful when dealing with complex data structures or when you need to pass a pointer to a pointer as an argument to a function. They allow you to modify the value of a pointer by using another pointer that points to it.

C Tutorial - 15 - Pointers

What are pointers in C Programming

Pointers are a fundamental feature of the C programming language. A pointer is a variable that stores the memory address of another variable. Pointers allow you to indirectly access and manipulate data in memory.

In C, you can declare a pointer using the * operator. The & operator can be used to obtain the memory address of a variable. Here's an example:

int x = 42;
int *p = &x;

In this example, we declare an integer variable x and assign it the value 42. We then declare a pointer variable p using the * operator, and initialize it to the memory address of x using the & operator.

You can dereference a pointer using the * operator, which allows you to access the value stored at the memory address pointed to by the pointer. Here's an example:

int y = *p;

In this example, we declare an integer variable y and assign it the value stored at the memory address pointed to by p. Since p points to x, which has the value 42, y is also assigned the value 42.

Pointers can be used for a variety of purposes, including dynamic memory allocation, passing arguments to functions by reference, and creating complex data structures such as linked lists and trees.

However, working with pointers can be error-prone, as it requires careful management of memory allocation and deallocation, and can lead to bugs such as segmentation faults and memory leaks. It is important to use pointers carefully and follow best practices for memory management in C.

 

Why are Pointers Important

Pointers are an important feature of the C programming language because they allow for efficient and flexible memory management. Here are a few reasons why pointers are important:

  1. Memory management: Pointers allow you to dynamically allocate memory at runtime. This means that you can allocate memory as needed and release it when it's no longer needed. This is important for programs that need to manage large amounts of data, as it allows them to use memory more efficiently.

  2. Function parameters: Pointers can be used to pass arguments to functions by reference. This means that a function can modify the value of a variable that was passed to it, rather than creating a copy of the variable. This is useful for functions that need to modify the value of a variable, but don't want to create a new copy of it.

  3. Complex data structures: Pointers allow you to create complex data structures such as linked lists, trees, and graphs. These data structures can be used to represent relationships between data, and are used in a wide variety of applications, from computer graphics to database management.

  4. Pointers and arrays: Arrays in C are implemented using pointers, which makes them a powerful and flexible data structure. You can use pointers to access individual elements of an array, and to manipulate the array itself.

  5. Low-level programming: Pointers are important in low-level programming, such as operating systems and device drivers. In these applications, it's necessary to have direct access to memory in order to interact with hardware devices and manage system resources.

 

Pointer Example

#include <stdio.h>

int main()
{
    //Real Value in Variable
    int number = 100;

    //Direct printing
    printf("Actual value %d: \n", number);

    //Real Hardware Address
    printf("Address: %p \n", &number);

    //Pointer Creation

    int * ptrNumber = &number;

    //Pointer is variable that holds address of other variable
    printf("Pointer : %p \n", ptrNumber);

    //Value of original variable using Pointer as Man in the Middle
    printf("Value using Pointer: %d \n", *ptrNumber);

    return 0;
}

Result:

Actual value 100:
Address: 000000000061FE14
Pointer : 000000000061FE14
Value using Pointer: 100

Process returned 0 (0x0)   execution time : 0.019 s
Press any key to continue.

Here's what this code does:

  1. It declares an integer variable called number and initializes it to the value 100.

  2. It prints the value of number using the printf() function.

  3. It prints the memory address of number using the %p format specifier with the printf() function. This is the actual hardware address where the variable is stored in memory.

  4. It declares a pointer variable called ptrNumber that holds the memory address of number. This is done using the & operator, which returns the address of the variable.

  5. It prints the value of ptrNumber using the %p format specifier with the printf() function. This is the memory address of number.

  6. It prints the value of number using the * operator with ptrNumber. This is called dereferencing the pointer, and it allows you to access the value stored at the memory address pointed to by the pointer.

This code demonstrates the basic concepts of pointers in C programming, including how to create and use them to access memory addresses and manipulate data.

 

Why do we need to use * and & while working with pointers

In C programming, the * (asterisk) and & (ampersand) operators are used in conjunction with pointers to manipulate memory addresses and data stored at those addresses.

The * operator is used to dereference a pointer, which means it allows you to access the data stored at the memory address pointed to by the pointer. For example, if you have a pointer variable ptr that points to an integer value stored at memory address 0x1000, you can access the value of that integer by dereferencing the pointer using the * operator like this: int x = *ptr;.

On the other hand, the & operator is used to get the memory address of a variable. For example, if you have an integer variable x with a value of 100, you can get its memory address using the & operator like this: int *ptr = &x;.

Therefore, the * and & operators are crucial in manipulating pointers and memory addresses in C programming. The & operator allows you to get the address of a variable, and the * operator allows you to access the value stored at that address through a pointer.

C Tutorial - 14 - Strings

What are Strings

In C programming, a string is a sequence of characters stored in contiguous memory locations, terminated by a null character ('\0'). Strings are represented as arrays of characters with a null character at the end.

Strings in C are typically declared using the char data type, and are enclosed in double quotes, like this:

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

Here, my_string is an array of characters that contains the string "Hello, world!".

Strings in C are commonly used for storing and manipulating textual data. There are many built-in functions in the C standard library that can be used to manipulate strings, such as strlen() for getting the length of a string, strcpy() for copying one string to another, and strcat() for concatenating two strings.

C strings are null-terminated, which means that the null character marks the end of the string. This allows C programs to handle strings of variable length, without having to specify the length of the string explicitly.

Here is an example of how to declare and print a string in C:

#include <stdio.h>

int main() {
    char my_string[] = "Hello, world!";
    printf("%s\n", my_string);
    return 0;
}

This program declares a string called my_string, and prints it to the console using the printf() function and the %s format specifier. The output of this program would be:

Hello, world!

 

C Strings and Individual Characters 

#include <stdio.h>

int main()
{

    char someString[] = "Hack The Planet";

    printf("Some String: %s \n", someString);

    //Indexes
    printf("Value: %c \n", someString[0]);
    printf("Value: %c \n", someString[3]);
    printf("Value: %c \n", someString[7]);

    //Change Char

    someString[0] = 'W';
    printf("Value: %c \n", someString[0]);
    printf("String Size: %d \n", sizeof(someString));

    int x = 0;

    for (x; x < sizeof(someString); x++)
    {
        printf("Char atm: %c \n", someString[x]);
    }

    return 0;
}

Result:

Some String: Hack The Planet
Value: H
Value: k
Value: e
Value: W
String Size: 16
Char atm: W
Char atm: a
Char atm: c
Char atm: k
Char atm:
Char atm: T
Char atm: h
Char atm: e
Char atm:
Char atm: P
Char atm: l
Char atm: a
Char atm: n
Char atm: e
Char atm: t
Char atm:

Process returned 0 (0x0)   execution time : 0.022 s
Press any key to continue.

This C source code demonstrates some basic operations that can be performed on strings.

The #include <stdio.h> line includes the standard input/output library, which contains the printf() function used for printing output to the console.

The int main() function is the entry point of the program, which returns an integer value to the operating system indicating whether the program executed successfully or not.

The program then declares a character array someString and initializes it with the string "Hack The Planet".

The program then uses the printf() function to print the entire string to the console using the format specifier %s.

The program then uses the array indexing operator [] to access individual characters of the string and prints their values to the console using the %c format specifier.

Next, the program modifies the value of the first character in the string by assigning it the value 'W'. The program then prints the new value of the first character to the console.

The program also prints the size of the someString array using the sizeof() operator, which returns the number of bytes occupied by the array in memory.

Finally, the program uses a for loop to iterate over all of the characters in someString and print their values to the console using the %c format specifier.

This program demonstrates how to declare and initialize a string in C, how to access individual characters of a string using array indexing, and how to modify the value of individual characters of a string. It also shows how to determine the size of a string using the sizeof() operator and how to iterate over all of the characters of a string using a for loop.

C Tutorial - 13 - Arrays

What are Arrays in C programming 

In C programming, an array is a collection of elements of the same data type, which are stored in contiguous memory locations. An array is a data structure that allows you to store multiple values of the same data type in a single variable.

Arrays are declared using the following syntax:

data_type array_name[array_size];

Here, data_type is the type of data that the array will store, array_name is the name of the array, and array_size is the number of elements that the array will store. For example, to declare an array of integers with 10 elements, you would use the following code:

int my_array[10];

Once an array is declared, you can access its individual elements by their index, which is a zero-based integer value that represents the position of the element in the array. For example, to access the first element of the my_array array, you would use the following code:

int first_element = my_array[0];

You can also assign values to array elements using the index notation, like this:

my_array[0] = 42;
my_array[1] = 21;

Arrays are a powerful tool for working with collections of data in C programming, and are used extensively in many applications.

 

C Array Example

#include <stdio.h>

int main()
{

    int someNumbers[] = {5, 25, 100, 500};
    char someChars[] = {'A', 'B', 'C'};

    printf("Number : %d \n", someNumbers[0]);
    printf("Number : %d \n", someNumbers[1]);
    printf("Number : %d \n", someNumbers[3]);
    printf("Char : %c \n", someChars[0]);

    someNumbers[0] = 888;
    printf("Number : %d \n", someNumbers[0]);

    return 0;
}

Result:

Number : 5
Number : 25
Number : 500
Char : A
Number : 888

Process returned 0 (0x0)   execution time : 0.011 s
Press any key to continue.

This C source code demonstrates the usage of arrays in C programming.

The #include <stdio.h> line includes the standard input/output library, which contains the printf() function used for printing output to the console.

The int main() function is the entry point of the program, which returns an integer value to the operating system indicating whether the program executed successfully or not.

The program then declares two arrays: someNumbers and someChars. someNumbers is an array of integers initialized with the values 5, 25, 100, and 500, and someChars is an array of characters initialized with the values 'A', 'B', and 'C'.

The program then uses the printf() function to print the values of the array elements. The first three lines of code print the first, second, and fourth elements of someNumbers using the format string "Number : %d \n", which prints an integer value followed by a newline character. The fourth line of code prints the first element of someChars using the format string "Char : %c \n", which prints a single character followed by a newline character.

The program then modifies the value of the first element of someNumbers by assigning the value 888 to it using the assignment operator =. The final printf() call prints the new value of the first element of someNumbers.

Finally, the return 0; statement indicates that the program executed successfully, and returns the value 0 to the operating system.

 

C Array Elements and For Loop

#include <stdio.h>

int main()
{

    int someNumbers[] = {5, 25, 100, 500};
    char someChars[] = {'A', 'B', 'C'};

    int x = 0;

    for (x; x < 4; x++)
    {
        printf("Number : %d \n", someNumbers[x]);
    }

    return 0;
}

Result:

Number : 5
Number : 25
Number : 100
Number : 500

Process returned 0 (0x0)   execution time : 0.004 s
Press any key to continue.

This C source code demonstrates the usage of a for loop to iterate over the elements of an array and print their values to the console.

The #include <stdio.h> line includes the standard input/output library, which contains the printf() function used for printing output to the console.

The int main() function is the entry point of the program, which returns an integer value to the operating system indicating whether the program executed successfully or not.

The program then declares two arrays: someNumbers and someChars. someNumbers is an array of integers initialized with the values 5, 25, 100, and 500, and someChars is an array of characters initialized with the values 'A', 'B', and 'C'.

The program then declares an integer variable x and initializes it to 0.

The program then enters a for loop, which iterates over the elements of someNumbers using the loop variable x. The loop runs as long as x is less than 4, which is the number of elements in someNumbers. The loop increments x by 1 after each iteration.

Within the loop, the program uses the printf() function to print the value of each element of someNumbers using the format string "Number : %d \n", which prints an integer value followed by a newline character.

After the loop completes, the program reaches the return 0; statement, which indicates that the program executed successfully, and returns the value 0 to the operating system.

This program demonstrates how to use a for loop to iterate over the elements of an array and perform a task on each element, such as printing its value to the console.

C Tutorial - 12 - Break and Continue

Break examples

In C programming, the break keyword is used to terminate a loop prematurely. It can be used inside the body of a for, while, or do-while loop to exit the loop immediately, even if the loop condition has not been fully satisfied.

When break is encountered inside a loop, the program jumps to the next statement immediately after the loop, effectively ending the loop's execution. This is often useful when you want to stop iterating over a set of data based on a certain condition, or if you want to stop a loop once a certain value has been reached. 

#include <stdio.h>

int main()
{

    int x;

    for (x = 0; x <= 10; x++)
    {
        if (x == 5)
        {
            break;
        }
        printf("X at this moment: %d \n", x);
    }

    return 0;
}

Result:

X at this moment: 0
X at this moment: 1
X at this moment: 2
X at this moment: 3
X at this moment: 4

Process returned 0 (0x0)   execution time : 0.060 s
Press any key to continue.

This is a simple C program that uses a for loop to print the value of a variable called x from 0 to 10. Inside the loop, there is an if statement that checks if the value of x is equal to 5. If it is, the loop is terminated using the break keyword.

Here is a step-by-step explanation of how the program works:

  1. The variable x is declared and initialized to 0.
  2. The for loop is executed, starting with x at 0 and incrementing it by 1 each time the loop runs, until x reaches 10.
  3. Inside the loop, the if statement checks if x is equal to 5.
  4. If x is equal to 5, the break statement is executed, which terminates the loop.
  5. If x is not equal to 5, the printf statement is executed, which prints the current value of x.
  6. After the loop is terminated, the program ends by returning 0.

Therefore, when the program runs, it prints the value of x at each iteration of the loop until it reaches 5, at which point the loop is terminated and the program ends.

#include <stdio.h>

int main()
{

    int x = 0;

    while (x <= 10 )
    {
        if (x == 5)
        {
            break;
        }
        printf("X atm: %d \n", x);
        x++;
    }

    return 0;
}

Result: 

X atm: 0
X atm: 1
X atm: 2
X atm: 3
X atm: 4

Process returned 0 (0x0)   execution time : 0.050 s
Press any key to continue.

 

Continue example

In C programming, the continue keyword is used to skip the current iteration of a loop and move on to the next iteration. It can be used inside the body of a for, while, or do-while loop to skip over specific parts of the loop's execution.

When continue is encountered inside a loop, the program skips the remaining statements inside the loop for the current iteration and jumps back to the beginning of the loop to start the next iteration. This is often useful when you want to skip certain iterations of a loop based on a certain condition.

#include <stdio.h>

int main()
{

    int x = 0;

    while (x <= 10 )
    {
        if (x == 5)
        {
            x++;
            continue;
        }
        printf("X atm: %d \n", x);
        x++;
    }

    return 0;
}

Result:

X atm: 0
X atm: 1
X atm: 2
X atm: 3
X atm: 4
X atm: 6
X atm: 7
X atm: 8
X atm: 9
X atm: 10

Process returned 0 (0x0)   execution time : 0.010 s
Press any key to continue.

This C program uses a while loop to print the value of a variable called x from 0 to 10, except for when x is equal to 5. Inside the loop, there is an if statement that checks if the value of x is equal to 5. If it is, the program increments x by 1 and skips the current iteration of the loop using the continue keyword. Otherwise, the program prints the value of x using printf, and increments x by 1.

Here's how the program works:

  1. The program starts by declaring and initializing an integer variable x to 0.
  2. The while loop is executed repeatedly as long as x is less than or equal to 10.
  3. Inside the loop, an if statement checks if the value of x is equal to 5. If it is, the program increments x by 1 and skips the current iteration of the loop using the continue keyword.
  4. If x is not equal to 5, the program prints the value of x using printf().
  5. The value of x is incremented by 1 in each iteration of the loop.
  6. Once x becomes greater than 10, the loop terminates and the program ends.

So the output of the program will be the sequence of numbers from 0 to 10, with the number 5 skipped

C Tutorial - 11 - While and Do..While Loop

While loop 

#include <stdio.h>

int main()
{
    int x = 0;

    while (x < 10)
    {
        printf("X in this moment in a loop: %d \n", x);
        x = x + 1;
    }

    return 0;
}

Result:

X in this moment in a loop: 0
X in this moment in a loop: 1
X in this moment in a loop: 2
X in this moment in a loop: 3
X in this moment in a loop: 4
X in this moment in a loop: 5
X in this moment in a loop: 6
X in this moment in a loop: 7
X in this moment in a loop: 8
X in this moment in a loop: 9

Process returned 0 (0x0)   execution time : 0.024 s
Press any key to continue.

This C program uses a while loop to print the value of variable x repeatedly until it reaches the value of 10.

The program starts by initializing x to 0, and then enters a while loop with the condition x < 10. Inside the loop, the program prints the value of x using the printf() function, and then increments x by 1 using the expression x = x + 1. This process is repeated until x is no longer less than 10, at which point the loop is exited and the program returns 0.

Therefore, when you run this program, it will print the values of x from 0 to 9, and then terminate.

 

Why do we need x = x + 1 inside while loop

The statement x = x + 1 inside the while loop is used to increment the value of x by 1 in each iteration of the loop. Without this statement, the value of x would remain the same and the loop would execute infinitely.

In the given example, the initial value of x is set to 0. The while loop checks whether x is less than 10. If x is less than 10, it prints the value of x and increments it by 1 using the statement x = x + 1. This process is repeated until x becomes greater than or equal to 10 and the loop terminates.

 

Do..While loop

#include <stdio.h>

int main()
{
    int x = 0;

    do
    {
        printf("X in this moment in a loop: %d \n", x);
        x = x + 1;
    }
    while (x < 5);

    return 0;
}

Result:

X in this moment in a loop: 0
X in this moment in a loop: 1
X in this moment in a loop: 2
X in this moment in a loop: 3
X in this moment in a loop: 4

Process returned 0 (0x0)   execution time : 0.034 s
Press any key to continue.

 

Why "while" is outside "do" block of code

In the syntax of the do-while loop, the while condition is written after the do block of code. This is because the do block of code is executed first, and then the condition is checked. If the condition is true, the loop will continue to execute the do block of code again, and if the condition is false, the loop will exit.

By contrast, in the while loop, the condition is checked before the first execution of the loop. If the condition is false, the loop is never executed. If the condition is true, the loop is executed, and then the condition is checked again. So, in the while loop, the condition comes before the block of code.

 

When do..while loops are useful

Do-while loops are useful when you want to execute a block of code at least once, regardless of whether the condition is true or false. This is because the condition is checked at the end of the loop rather than the beginning. This can be helpful in situations where you need to perform a task before testing a condition.

Another example where do-while loop can be useful is when you are prompting the user for input. You can use a do-while loop to keep asking the user for input until they provide a valid input.

C Tutorial - 10 - For Loop with User Input

Basic for loop in C:

#include <stdio.h>

int main()
{
    int x;

    for (x = 0; x <= 5; x++)
    {
        printf("X in this moment of loop: %d \n", x);
    }

    return 0;
}

Result:

X in this moment of loop: 0
X in this moment of loop: 1
X in this moment of loop: 2
X in this moment of loop: 3
X in this moment of loop: 4
X in this moment of loop: 5

Process returned 0 (0x0)   execution time : 0.030 s
Press any key to continue.

This C code demonstrates the use of a "for loop" to print the value of the variable "x" from 0 to 5. Here is what each line of the code does:

  • #include <stdio.h>: This line includes the standard input/output library in the program, which provides the necessary functions for input and output operations.
  • int main(): This line declares the main function, which is the entry point of the program.
  • int x;: This line declares an integer variable "x" without initializing it.
  • for (x = 0; x <= 5; x++): This line starts a "for loop" that initializes "x" to 0, continues as long as "x" is less than or equal to 5, and increments "x" by 1 after each iteration of the loop.
  • {: This brace starts the block of code that will be executed in the loop.
  • printf("X in this moment of loop: %d \n", x);: This line uses the printf function to print the current value of "x" in each iteration of the loop.
  • }: This brace ends the block of code that will be executed in the loop.
  • return 0;: This line indicates that the program has finished executing and returns a value of 0 to the operating system, which indicates that the program executed successfully.

 

For loop in C with User Input

#include <stdio.h>

int main()
{
    int x;
    int y;

    printf("Enter x: \n");
    scanf("%d", &x);

    printf("Enter y: \n");
    scanf("%d", &y);

    for (x; x < y; x++)
    {
        printf("X in this moment of loop: %d \n", x);
    }
    return 0;
}

Result:

Enter x:
0
Enter y:
5
X in this moment of loop: 0
X in this moment of loop: 1
X in this moment of loop: 2
X in this moment of loop: 3
X in this moment of loop: 4

Process returned 0 (0x0)   execution time : 2.490 s
Press any key to continue.

This code prompts the user to enter two integers x and y and then loops through all the integers between x and y (excluding y), printing the current value of x at each iteration.

C Tutorial - 9 - Switch Statement with User Input

#include <stdio.h>

int main()
{
    printf("1-Start Game \n");
    printf("2-Audio Settings \n");
    printf("3-Video Settings \n");
    printf("################ \n");

    int choice;

    printf("Enter Choice \n");
    scanf("%d", &choice);

    switch (choice)
    {
    case 1:
        printf("Start Game");
        break;
    case 2:
        printf("Audio Settings");
        break;
    case 3:
        printf("Video Settings");
        break;
    default:
        printf("Check Your Input:         \n");
        printf("1-Start, 2-Audio, 3-Video \n");
        printf("------------------------- \n");
    }

    return 0;
}

Result:

1-Start Game
2-Audio Settings
3-Video Settings
################
Enter Choice
3
Video Settings
Process returned 0 (0x0)   execution time : 2.090 s
Press any key to continue.

This C code presents a simple menu system for a game or application.

It starts by printing out a menu with options to start the game, access audio settings, and access video settings.

Then it prompts the user to enter their choice, reads the input using the scanf() function, and stores it in an integer variable called choice.

The program then uses a switch statement to check the value of choice and execute the corresponding code block. If the user enters 1, it prints "Start Game". If the user enters 2, it prints "Audio Settings". If the user enters 3, it prints "Video Settings". If the user enters any other value, it prints an error message asking the user to check their input and lists the available options.

Finally, the program ends by returning 0.

 

Why do we need "case" inside "switch"

The case keyword is used inside a switch statement to specify one of several possible paths of execution. When a switch statement is evaluated, the expression in the parentheses is compared to each of the case values in turn. If a match is found, the code block following that case is executed, and then control jumps to the end of the switch statement (unless a break statement is encountered, in which case control jumps to the end of the switch block).

If no match is found, the code block following the default keyword is executed. The default case is optional, and it is executed only if none of the other cases match.

Using a switch statement can be more efficient than using a series of if-else statements when there are multiple possible cases to consider. It can also make the code easier to read and understand, particularly when there are many possible cases.

 

Why do we need "default" inside "switch"

In a switch statement, default is used as a catch-all case for any value that does not match any of the case statements. If none of the case statements matches the value of the expression being tested, then the code inside the default block will be executed.

Having a default case is useful to handle unexpected or invalid values that may be input by the user or that may be generated during program execution. It can provide a way to gracefully handle unexpected behavior and prevent the program from crashing or producing unexpected results.

C Tutorial - 8 - If..Else with User Input

#include <stdio.h>

int main()
{
    int first;
    int second;

    printf("Enter First Number: \n");
    scanf("%d", &first);

    printf("Enter Second Number: \n");
    scanf("%d", &second);

    if (first < second)
    {
        printf("%d is smaller than %d \n", first, second);
    }
    else if (first > second)
    {
        printf("%d is bigger than %d \n", first, second);
    }
    else
        printf("%d and %d are equal \n", first, second);

    return 0;
}

Result:

Enter First Number:
10
Enter Second Number:
20
10 is smaller than 20

Process returned 0 (0x0)   execution time : 4.561 s
Press any key to continue.

This C code prompts the user to enter two integer values for the variables first and second, and then uses an if-else statement to compare the values of these variables.

First, the program prompts the user to enter the value of first and second using scanf() function. Then, it checks if first is smaller than second using the if statement. If this condition is true, the program prints a message stating that first is smaller than second using printf() function. If the if condition is false, the program moves to the else if statement, which checks if first is greater than second. If this condition is true, the program prints a message stating that first is bigger than second using printf() function. If both the if and else if conditions are false, the program executes the else statement and prints a message stating that both the numbers are equal using printf() function.

Finally, the program returns 0 to indicate that the program has executed successfully.

C Tutorial - 7 - If..Else

#include <stdio.h>

int main()
{
    if (10 < 999)
    {
        printf("left is smaller than right \n");
    }

    return 0;
}

Result:

left is smaller than right

Process returned 0 (0x0)   execution time : 0.048 s
Press any key to continue.

This C program demonstrates the use of an if statement to check whether the left-hand side of the comparison 10 < 999 is smaller than the right-hand side.

When the program is run, it will print "left is smaller than right" because the condition is true. If the condition were false, then the code inside the if block would not be executed.

Here's how the program works:

  • The program includes the standard input/output library stdio.h.
  • The main() function is defined, which returns an integer.
  • Inside the main() function, an if statement is used to check whether the condition 10 < 999 is true.
  • If the condition is true, then the code inside the curly braces {...} is executed. In this case, the code simply prints the message "left is smaller than right" to the console using printf() function.
  • The return statement is used to exit the program and return a value of 0 to the operating system.
#include <stdio.h>

int main()
{
    int first = 5;
    int second = 5;

    if (first < second)
    {
        printf("first is smaller than second \n");
    }
    else if (first > second)
    {
        printf("first is bigger than second \n");
    }
    else
        printf("numbers are equal \n");

    return 0;
}

Result:

numbers are equal

Process returned 0 (0x0)   execution time : 0.060 s
Press any key to continue.

This C program compares two integer variables first and second and prints a message depending on their values.

In the if statement, it checks whether first is less than second. If it is true, it prints the message "first is smaller than second".

If the if statement condition is not true, it moves to the else if block and checks whether first is greater than second. If it is true, it prints the message "first is bigger than second".

If neither the if statement nor the else if statement conditions are true, it moves to the else block and prints the message "numbers are equal".

At the end, the program returns 0, indicating successful execution.

 

C Tutorial - 6 - User Input

#include <stdio.h>

int main()
{
    int firstNumber;
    float secondNumber;
    char someWord[30];

    printf("Enter First Number: \n");
    scanf("%d", &firstNumber);

    printf("Enter Second Number: \n");
    scanf("%f", &secondNumber);

    printf("Enter Some Word: \n");
    scanf("%s", &someWord);

    printf("-------------------------- \n");

    printf("First Number: %d \n", firstNumber);
    printf("Second Number: %f \n", secondNumber);
    printf("Some Word: %s \n", someWord);

    printf("-------------------------- \n");

    return 0;
}

Result:

Enter First Number:
5
Enter Second Number:
20
Enter Some Word:
asdas
--------------------------
First Number: 5
Second Number: 20.000000
Some Word: asdas
--------------------------

Process returned 0 (0x0)   execution time : 5.460 s
Press any key to continue.

This code is a simple program that prompts the user to input three values (an integer, a float, and a string) using the scanf() function and then displays those values using the printf() function.

Here is how the code works:

  • The program includes the standard input/output library (stdio.h).
  • In the main() function, three variables are declared: firstNumber (an integer), secondNumber (a float), and someWord (a character array that can hold up to 30 characters).
  • The program then prompts the user to input the first number using the printf() function and reads in the input using the scanf() function with the %d format specifier.
  • Next, the program prompts the user to input the second number using the printf() function and reads in the input using the scanf() function with the %f format specifier.
  • Finally, the program prompts the user to input a string using the printf() function and reads in the input using the scanf() function with the %s format specifier.
  • The program then displays the values of the three variables using the printf() function with appropriate format specifiers.

Note that in the scanf() function, the & operator is used to get the memory address of each variable to read the input into. Also, the %s format specifier reads in a string of characters terminated by a whitespace character (space, tab, or newline), so it may not work as expected if the user enters a string with whitespace characters.

 

What is char someWord[30];

char someWord[30] is a character array in C, which is capable of holding 30 characters. In other words, it is a sequence of characters, represented as a contiguous block of memory, with each character taking one byte of memory. The size of the array is specified in square brackets, in this case 30.

This particular character array, someWord, can be used to store strings of up to 29 characters long, with one extra byte reserved for the null terminator character '\0'. The null terminator indicates the end of the string and is automatically added to the end of the string by C when you use string functions such as printf() or scanf().

So, char someWord[30] is used to declare a character array that can store a string of up to 29 characters in C.

 

Why do we need %s format specifier.

We use the %s format specifier in C to read input as a string of characters from the user using the scanf() function. The %s format specifier tells the scanf() function to read a string of characters from the user input until it encounters a whitespace character, such as space, tab or newline.

For example, consider the following code:

#include <stdio.h>

int main() {
    char name[20];
    printf("Enter your name: ");
    scanf("%s", name);
    printf("Hello, %s!\n", name);
    return 0;
}

Result:

Enter your name: Alan
Hello, Alan!

Process returned 0 (0x0)   execution time : 2.280 s
Press any key to continue.

In this program, we use %s format specifier to read a string of characters from the user and store it in the name character array. Then, we use the printf() function to print the string Hello, followed by the name variable, which contains the user's name.

So, %s format specifier is useful when we want to read a string of characters from the user input in C programming.

C Tutorial - 5 - Simple Calculator

#include <stdio.h>

int main()
{
    printf("############################# \n");
    printf("\n");
    printf("Welcome to Simple Calculator  \n");
    printf("\n");
    printf("############################# \n");
    printf("\n");

    int firstNumber = 13;
    int secondNumber = 5;

    int add = firstNumber + secondNumber;
    int sub = firstNumber - secondNumber;
    int mul = firstNumber * secondNumber;
    int div = firstNumber / secondNumber;
    int rem = firstNumber % secondNumber;

    printf("Add: %d \n", add);
    printf("Sub: %d \n", sub);
    printf("Mul: %d \n", mul);
    printf("Div: %d \n", div);
    printf("Rem: %d \n", rem);

    return 0;
}

Result:

#############################

Welcome to Simple Calculator

#############################

Add: 18
Sub: 8
Mul: 65
Div: 2
Rem: 3

Process returned 0 (0x0)   execution time : 0.160 s
Press any key to continue.

In programming, the modulo operation, denoted by the % symbol, is a mathematical operation that calculates the remainder when one integer is divided by another. For example, 7 % 3 would evaluate to 1 because 3 divides into 7 twice with a remainder of 1.

The modulo operation is useful in programming for a variety of tasks, such as determining whether a number is even or odd (even numbers will have a remainder of 0 when divided by 2), or determining whether a given number is a multiple of another number (a number is a multiple of another if its modulo operation with the other number results in 0).

 

Do we have modulo in other programming languages

Yes, modulo is a common operation in many programming languages. In fact, most programming languages provide a modulo operator. Here are some examples:

  • Python: % operator
  • Java: % operator
  • JavaScript: % operator
  • PHP: % operator
  • Ruby: % operator
  • C#: % operator
  • Perl: % operator

The syntax may vary slightly between programming languages, but the concept and functionality of the modulo operation remain the same.

C Tutorial - 4 - Constants and Comments

#include <stdio.h>

#define STATICNUMBER 500
#define PI 3.14

int main()
{  

    printf("Static Num: %d \n", STATICNUMBER);
    printf("PI: %f \n", PI);

    return 0;
}

This C code defines two constants using the #define preprocessor directive, then prints their values to the console using the printf() function.

The first line of the code includes the standard input/output library stdio.h.

The second line defines a constant named STATICNUMBER using the #define directive. It assigns the value 500 to STATICNUMBER, so wherever STATICNUMBER appears in the code, it will be replaced with the value 500 during compilation.

The third line defines a constant named PI using the #define directive. It assigns the value 3.14 to PI.

The main() function then prints the values of the two constants to the console using printf(). The first printf() statement prints the value of STATICNUMBER using the format specifier %d, which is used to format integer values. The second printf() statement prints the value of PI using the format specifier %f, which is used to format floating-point values.

When the program is executed, it will output the following text to the console:

Static Num: 500
PI: 3.140000

Note that the output for PI includes extra decimal places because the printf() function defaults to printing floating-point values with six decimal places.

 

What is "#define" preprocessor directive

#define is a preprocessor directive in the C programming language. It is used to define a macro, which is a piece of code that the compiler will substitute with the defined value before the program is compiled.

The syntax for #define is:

#define identifier value

Here, identifier is the name of the macro being defined, and value is the value that the macro will be replaced with.

For example, the following #define statement defines a macro called MAX_NUM with a value of 100:

#define MAX_NUM 100

When the compiler encounters MAX_NUM in the code, it will replace it with the value 100 before compiling the program.

#define can also be used to define functions-like macros, which can take arguments. Here's an example:

#define SQUARE(x) ((x) * (x))

This macro defines a function-like macro called SQUARE that takes a single argument x. When the compiler encounters a call to SQUARE(5), it will replace it with ((5) * (5)), which will evaluate to 25.

#define is a powerful tool for defining constants and macros in C programming. However, it is important to use it carefully, since macros can sometimes lead to unexpected behavior or errors if they are not used correctly.

 

Can i define constants inside main() function or outside

In C programming, constants can be defined both inside and outside the main() function using the const keyword or the #define preprocessor directive.

If you use the const keyword to define a constant inside the main() function, it will be a local constant and will only be accessible within the scope of the main() function. For example:

int main() {
    const int MAX_NUM = 100;
    printf("Max number is %d", MAX_NUM);
    return 0;
}

On the other hand, if you define a constant outside the main() function using either the const keyword or the #define preprocessor directive, it will be a global constant and can be accessed from anywhere in the program. For example:

#define MAX_NUM 100

int main() {
    printf("Max number is %d", MAX_NUM);
    return 0;
}

It is generally a good practice to define constants outside of the main() function, since it makes them more visible and accessible to the entire program.

 

Constants with "const" example

#include <stdio.h>

int main()
{
    const int staticNumber = 500;
    const float PI = 3.14;

    printf("Static Num: %d \n", staticNumber);
    printf("PI: %f \n", PI);

    return 0;
}

Result:

Static Num: 500
PI: 3.140000

Process returned 0 (0x0)   execution time : 0.020 s
Press any key to continue.

The above C code defines and initializes two constants, staticNumber and PI, using the const keyword.

The const keyword is used to define variables that cannot be modified or changed once they have been initialized. In other words, staticNumber and PI are read-only variables and any attempt to modify them later in the program will result in a compiler error.

The value of staticNumber is set to 500 and the value of PI is set to 3.14.

Then, the values of these constants are printed using the printf() function. The %d format specifier is used to print an integer value, and the %f format specifier is used to print a floating-point value.

Finally, the main() function returns 0, which indicates successful termination of the program.

The code defines and uses constants to store and print fixed values that are not supposed to change during program execution.

 

What are Comments in C programming and how to create them

Comments are explanatory statements in a program that are ignored by the compiler. They are used to make the code more readable and understandable to humans.

In C programming, there are two types of comments:

  1. Single-line comments: These comments start with two forward slashes (//) and end at the end of the line. They are used to comment on a single line of code.

    For example:

    // This is a single-line comment

     

  2. Multi-line comments: These comments start with a forward slash followed by an asterisk (/) and end with an asterisk followed by a forward slash (/). They can span multiple lines and are used to comment on multiple lines of code.

    For example:

    /* This is a 
       multi-line comment */
    

    Comments can be added to the code at any point, and they do not affect the execution of the program. They are simply ignored by the compiler.

C Tutorial - 3 - Variables, Data Types, Format Specifiers

#include <stdio.h>

int main()
{
    int firstNumber = 123;
    int secondNumber = 555;
    int thirdNumber = 5000;

    float preciseNumber = 523.897;

    char someChar = 'A';

    printf("Value : %d \n", firstNumber);
    printf("Value : %d \n", secondNumber);
    printf("Value : %d \n", thirdNumber);

    printf("Value : %f \n", preciseNumber);

    printf("Value : %c \n", someChar);
    return 0;
}

Result:

Value : 123
Value : 555
Value : 5000
Value : 523.896973
Value : A

Process returned 0 (0x0)   execution time : 0.088 s
Press any key to continue.

The program first declares three integer variables (firstNumber, secondNumber, and thirdNumber) and initializes them with the values 123, 555, and 5000, respectively.

It then declares a floating-point variable preciseNumber and initializes it with the value 523.897.

Finally, it declares a character variable someChar and initializes it with the character 'A'.

The program then uses the printf function to print the values of each variable to the console. %d is used to print integer values, %f is used to print floating-point values, and %c is used to print character values. The \n character is used to print a newline after each value, so that each value is printed on a separate line.

What are Integers and Floats and what is the difference

In programming, integers and floats are two types of numerical data types.

An integer is a whole number without a decimal point, such as 1, 2, 3, and so on. Integers can be either positive, negative, or zero.

A float, also known as a floating-point number, is a number with a decimal point, such as 1.23, 4.56, or -7.89. Floats can also be either positive, negative, or zero.

The main difference between integers and floats is their precision. Integers are precise, meaning that they are represented exactly as they are in memory, and they do not lose any information when performing arithmetic operations. Floats, on the other hand, are not always precise and can lose some precision due to the way they are stored in memory. This can cause rounding errors or other inaccuracies in certain calculations.

Another difference is the amount of memory they require. Integers typically require less memory than floats because they don't need to store decimal places. For example, an int variable in C usually takes up 4 bytes of memory, while a float variable usually takes up 4 or 8 bytes depending on the system.

In summary, integers and floats are both numerical data types, but integers are whole numbers without a decimal point, while floats are numbers with a decimal point. Integers are precise and require less memory, while floats can lose precision and require more memory.

Why do we need "char" datatype

The char data type is used in programming to represent single characters, such as letters, digits, punctuation marks, and special characters. It is a built-in data type in many programming languages, including C, C++, Java, and Python.

There are several reasons why we need the char data type:

  1. String manipulation: Strings in many programming languages are actually arrays of char values, where each element of the array represents a single character in the string. Therefore, the char data type is used extensively in string manipulation functions.

  2. Input/output: When reading input from a file or from the user, it is often necessary to read in single characters, which are stored in char variables. Similarly, when outputting text to a file or to the screen, it is often necessary to output single characters using functions such as printf or putchar.

  3. ASCII representation: The char data type is often used to represent ASCII characters, which are a standard set of 128 characters used in computing. Each ASCII character is assigned a unique code between 0 and 127, which can be represented using a char variable.

  4. Memory allocation: char data type is also used for allocating memory for storing characters in the form of strings.

The char data type is used to represent single characters, and is essential for string manipulation, input/output operations, ASCII representation, and memory allocation in programming.

How many datatypes are in C programming

C programming language provides several data types, which can be broadly classified into three categories:

  1. Basic data types:

    • int: used to store integer values.
    • float: used to store floating-point values (real numbers).
    • double: used to store double-precision floating-point values.
    • char: used to store a single character.
  2. Derived data types:

    • array: used to store a collection of data of the same data type.
    • structure: used to store a collection of data of different data types.
    • union: used to store a collection of data of different data types, but only one data item at a time can be stored in a union.
    • enum: used to define a set of named constants.
  3. Void data type:

    • void: used to indicate the absence of a data type. It is commonly used as a return type for functions that do not return a value, and as a pointer type.

In addition to the above data types, C programming language also provides several modifiers that can be applied to the basic data types to modify their storage size and range. These modifiers include short, long, and unsigned.

C programming language provides a rich set of data types to suit different needs of programmers.

Do we need to know all datatypes on top of our minds 

As a programmer, it is important to have a good understanding of the basic data types in C programming language and their appropriate use cases. These data types include int, float, double, and char.

It is also important to have a good understanding of the derived data types such as arrays, structures, unions, and enums, as well as the void data type.

However, it is not necessary to memorize all the data types and their syntax on top of your mind. As a programmer, you will typically have access to documentation and reference materials that can help you look up specific details as needed.

That being said, having a solid understanding of the most commonly used data types and their appropriate use cases will allow you to write more efficient and effective code, and will help you to avoid common mistakes and errors.

What are Format Specifiers in C

Format specifiers in C are special characters used in the printf() and scanf() functions to format the output or input of data. They tell the function what type of data is being passed as an argument and how to format it for output or input.

The most common format specifiers used in printf() are:

  • %d: used for integers
  • %f: used for floating-point numbers
  • %c: used for single characters
  • %s: used for strings
  • %p: used for pointers

The most common format specifiers used in scanf() are similar to printf():

  • %d: used for integers
  • %f: used for floating-point numbers
  • %c: used for single characters
  • %s: used for strings
  • %p: used for pointers

When using format specifiers, it is important to make sure that the type of data being passed as an argument matches the type expected by the function, otherwise the program may produce unexpected results or even crash.

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...