Wednesday, April 30, 2025

C Program - How to Implement Bubble Sort in C Programming Language

Bubble sort is a simple sorting algorithm that repeatedly steps through the list of elements to be sorted, compares each adjacent pair of elements and swaps them if they are in the wrong order. This process is repeated multiple times until the entire list is sorted.

The algorithm works by starting at the beginning of the list and comparing the first two elements.

If the first element is greater than the second element, they are swapped. Then the algorithm compares the second and third elements, and so on, until the end of the list is reached. This is considered one pass through the list. After the first pass, the largest element in the list will be in its correct place.

The algorithm then starts again with the first element and performs the same process for the remaining elements until the list is fully sorted.

Bubble sort has a time complexity of O(n^2), which makes it less efficient than other sorting algorithms for larger lists. However, it is easy to understand and implement and can be useful for smaller datasets or as a learning exercise.

//buble sort

#include <stdio.h>

int main()          //temp = generic variable, container
{
    //pairs       1   2  3  4  5  6  7  8  9
    int arr[] = {2, 4, 3, 1, 6, 5, 8, 10, 7, 9};
    int num = 10; //we must know this in advance or calculate it
    int x, y; //for for loops, x, y are just positions where elements exists
    int temp; //used only for swaping, helper container

    for (x = 0; x < num - 1 ; x++)
    {
        for (y = 0; y < num - x - 1  ; y++)
        {
            if(arr[y] > arr[y + 1])
            {
                temp = arr[y];
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
        }
    }

    //this is just normal printing
    printf("Sorted Array: \n");

    for(x = 0; x < num; x++)
    {
        printf("%d  ", arr[x]);
    }

    return 0;

}

Result: 

Sorted Array:
1  2  3  4  5  6  7  8  9  10
Process returned 0 (0x0)   execution time : 0.035 s
Press any key to continue.

Here's a line-by-line explanation of the Bubble Sort code: 

#include <stdio.h>

This line includes the standard input/output library. 

int main()

This line defines the main function, which is the entry point of the program. 

int arr[] = {2, 4, 3, 1, 6, 5, 8, 10, 7, 9};

This line creates an integer array of size 10 and initializes it with unsorted values. 

int num = 10;

This line defines a variable to store the size of the array. 

int x, y, temp;

These lines define variables to be used as counters and a temporary variable to store values during swapping. 

for (x = 0; x < num - 1 ; x++)
{
    for (y = 0; y < num - x - 1  ; y++)
    {
        if(arr[y] > arr[y + 1])
        {
            temp = arr[y];
            arr[y] = arr[y + 1];
            arr[y + 1] = temp;
        }
    }
}

These lines of code implement the bubble sort algorithm.

The algorithm compares adjacent elements in an array and swaps them if they are in the wrong order. It repeats this process for each pair of adjacent elements until no more swaps are required.

The outer loop in this code iterates through the array from the first element (index 0) to the second to last element (index num-2). The inner loop iterates through the array from the first element (index 0) to the second to last element minus the number of iterations performed in the outer loop (index num-x-2).

The reason for this is that, after each iteration of the outer loop, the largest element is guaranteed to be in its correct position at the end of the array, so there is no need to compare it with any elements after that position.

Within the inner loop, the code compares the current element at index y with the next element at index y+1.

If the current element is greater than the next element, it means they are in the wrong order, and the code swaps them by assigning the value of the current element to a temporary variable, assigning the value of the next element to the current element, and assigning the value of the temporary variable to the next element.

After both loops complete, the array is sorted in ascending order. 

printf("Sorted Array: \n");
for(x = 0; x < num; x++)
{
    printf("%d  ", arr[x]);
}

These lines print out the sorted array. 

return 0;

This line indicates the end of the main function and returns a value of zero to the operating system to indicate that the program executed successfully.

How to Add gcc MinGW bin directory to System Path - Windows 10

To add the GCC MinGW bin directory to your system path on Windows 10, you can follow these steps:

  1. Open File Explorer and navigate to the MinGW installation directory. The default location for MinGW is C:\MinGW.

  2. Inside the MinGW directory, locate the bin folder. This folder contains the executables for GCC.

  3. Click on the address bar of the File Explorer window and copy the path to the bin folder. Alternatively, you can right-click on the bin folder and select Properties. In the Properties dialog box, copy the path in the Location field.

  4. Open the Start menu and search for "Environment Variables". Select the "Edit the system environment variables" option.

  5. In the System Properties dialog box, click on the "Environment Variables" button.

  6. Under the "System Variables" section, scroll down and locate the "Path" variable. Click on "Edit".

  7. In the Edit environment variable dialog box, click "New" and paste the path to the MinGW bin directory that you copied in step 3. Click "OK" to close all the dialog boxes.

  8. Restart any open command prompt or terminal windows for the changes to take effect.

After following these steps, you should be able to run GCC commands from any directory in your command prompt or terminal.

C Program - Check Leap Year with C Programming Language

 This C program determines whether a given year is a leap year or not.

#include <stdio.h>

int main()
{

    int year;

    while (1)
    {

        printf("Enter a Year: ");
        scanf("%d", &year);

        if (year % 4 != 0)
        {
            printf("NOT Leap Year \n");
        }
        else if (year % 100 != 0)
        {
            printf("Leap Year \n");
        }
        else if (year % 400 != 0)
        {
            printf("NOT Leap Year \n");
        }
        else
        {
            printf("Leap Year \n");
        }
    }

    return 0;
}

Result: 

Enter a Year: 2023
NOT Leap Year
Enter a Year: 2020
Leap Year
Enter a Year: 2025
NOT Leap Year
Enter a Year:

Here is a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library that allows the program to interact with the user through the console. 

int main()
{

This is the starting point of the program and the main function. 

    int year;

Declare an integer variable named year to hold the year to be checked. 

    while (1)
    {

This creates an infinite loop that will continue to ask the user for a year until the program is terminated. 

        printf("Enter a Year: ");
        scanf("%d", &year);

This line prints the prompt message to the console, waits for the user to input a value, and stores the value in the year variable. 

        if (year % 4 != 0)
        {
            printf("NOT Leap Year \n");
        }

If the remainder of year divided by 4 is not equal to 0, then the year is not divisible by 4 and, therefore, is not a leap year. In that case, the program prints "NOT Leap Year" to the console. 

        else if (year % 100 != 0)
        {
            printf("Leap Year \n");
        }

If the year is divisible by 4, but not by 100, it is a leap year. In that case, the program prints "Leap Year" to the console. 

        else if (year % 400 != 0)
        {
            printf("NOT Leap Year \n");
        }

If the year is divisible by 100 but not by 400, it is not a leap year. In that case, the program prints "NOT Leap Year" to the console. 

        else
        {
            printf("Leap Year \n");
        }

If the year is divisible by both 100 and 400, it is a leap year. In that case, the program prints "Leap Year" to the console. 

    }

The end of the while loop. 

    return 0;
}

The program ends and returns the integer value 0 to the operating system.

C Program - Print The Square Star Pattern

This C program prompts the user to input an integer value for the side length of a square and prints a square of asterisks with that side length.  

#include<stdio.h>

int main()
{

    int x, y, side_length;

    printf("Side Length: ");
    scanf("%d",&side_length);

    for(x = 0; x < side_length; x++)
    {

        for(y = 0; y < side_length; y++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}

Result: 

Side Length: 10
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********

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

Here is a line-by-line explanation: 

#include<stdio.h>

This line includes the standard input-output header file. 

int main()
{
    int x, y, side_length;

    printf("Side Length: ");
    scanf("%d",&side_length);

This block of code declares three integer variables: x, y, and side_length. It then prompts the user to enter the side length of the square, and the user's input is stored in the side_length variable using the scanf function. 

    for(x = 0; x < side_length; x++)
    {

        for(y = 0; y < side_length; y++)
        {
            printf("*");
        }
        printf("\n");
    }

This block of code uses two nested for loops to print a square of asterisks with side length side_length.

The outer for loop initializes the loop variable x to 0 and increments it by 1 on each iteration as long as it is less than side_length.

The inner for loop initializes the loop variable y to 0 and increments it by 1 on each iteration as long as it is less than side_length. On each iteration of the inner loop, an asterisk is printed using the printf function.

After the inner loop has finished iterating for a given value of x, a newline character is printed using the printf function to move the cursor to the next line. 

    return 0;
}

This line returns 0 to indicate successful execution of the program.

C Program - Store Information of Students Using Structure

 This code is an example of using structures in C to manage data about Students.

#include <stdio.h>

struct student
{
    int s_id;
    char first_name[50];
    char last_name[50];
    char grade [5];
} students[10];

int main()
{
    int total, x; // x to be used in a for loop

    printf("Total Number of Students to Enter: ");
    scanf("%d", &total);

    printf("Enter Data: \n");
    for (x = 0; x < total; x++)
    {
        printf("--------------------------------------------- \n");
        students[x].s_id = x + 1;
        printf("ID: %d \n", students[x].s_id);

        printf("First name: ");
        scanf("%s", students[x].first_name);

        printf("Last name: ");
        scanf("%s", students[x].last_name);

        printf("Grade: ");
        scanf("%s", students[x].grade);
    }

    printf("Print Data: \n");

    for (x = 0; x < total; x++)
    {
        printf("--------------------------------------------- \n");
        printf("ID: %d \n", x + 1);

        printf("First Name: ");
        puts(students[x].first_name);

        printf("Last Name: ");
        puts(students[x].last_name);

        printf("Grade: ");
        puts(students[x].grade);
        printf("\n");
    }
    return 0;
}

Result:

Total Number of Students to Enter: 2
Enter Data:
---------------------------------------------
ID: 1
First name: Michael
Last name: Smith
Grade: 10
---------------------------------------------
ID: 2
First name: Samantha
Last name: Fox
Grade: 10
Print Data:
---------------------------------------------
ID: 1
First Name: Michael
Last Name: Smith
Grade: 10

---------------------------------------------
ID: 2
First Name: Samantha
Last Name: Fox
Grade: 10


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

Here's a line-by-line explanation:

#include <stdio.h> - This is a preprocessor directive that includes the standard input-output library header file in the program. 

struct student
{
    int s_id;
    char first_name[50];
    char last_name[50];
    char grade [5];
} students[10];

This block of code defines a structure called student with four members: s_id, first_name, last_name, and grade. An array of 10 student structures is also defined. 

int main()
{
    int total, x;

This block declares two integer variables: total and x

printf("Total Number of Students to Enter: ");
scanf("%d", &total);

This block prints a message asking the user to enter the total number of students they want to input, then reads the input from the user and stores it in the variable total

printf("Enter Data: \n");
for (x = 0; x < total; x++)
{
    printf("--------------------------------------------- \n");
    students[x].s_id = x + 1;
    printf("ID: %d \n", students[x].s_id);

    printf("First name: ");
    scanf("%s", students[x].first_name);

    printf("Last name: ");
    scanf("%s", students[x].last_name);

    printf("Grade: ");
    scanf("%s", students[x].grade);
}

This block uses a for loop to iterate through the array of students and prompts the user to enter the data for each student. The student ID is automatically assigned to the index of the student in the array, starting from 1. 

printf("Print Data: \n");

for (x = 0; x < total; x++)
{
    printf("--------------------------------------------- \n");
    printf("ID: %d \n", x + 1);

    printf("First Name: ");
    puts(students[x].first_name);

    printf("Last Name: ");
    puts(students[x].last_name);

    printf("Grade: ");
    puts(students[x].grade);
    printf("\n");
}

This block prints out the data entered for each student in a user-friendly format using a for loop to iterate through the array of students

return 0;
}

This line signals to the operating system that the program has run successfully and the program ends.

C Program - Swap Two Numbers using Multiplication and Division

This C program swaps the values of two variables num1 and num2 without using a temporary variable.  

#include <stdio.h>

int main()
{

    int num1 = 6;
    int num2 = 3;

    printf("Initial State: %d, %d \n", num1, num2);

    num1 = num1 * num2;     //num1 = 6 * 3 = 18
    printf("Number 1: %d \n", num1);

    num2 = num1 / num2;     //num2 = 18 / 3 = 6 FINAL
    printf("Number 2: %d \n", num2);

    num1 = num1 / num2;     //num1 = 18 / 6 = 3 FINAL
    printf("Number 1: %d \n", num1);

    printf("Final State: %d, %d \n", num1, num2);

    return 0;
}

Result: 

Initial State: 6, 3
Number 1: 18
Number 2: 6
Number 1: 3
Final State: 3, 6

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

Here's a line-by-line explanation of the program: 

#include <stdio.h>

This line is a preprocessor directive that includes the standard input/output library in the program. This library contains functions for reading input and writing output. 

int main()
{

This is the starting point of the program. The main() function is the entry point of the program where the execution begins. The int before main() indicates that the function returns an integer value. 

    int num1 = 6;
    int num2 = 3;

These lines declare and initialize two integer variables named num1 and num2

    printf("Initial State: %d, %d \n", num1, num2);

This line prints out the initial state of the num1 and num2 variables. 

    num1 = num1 * num2;     //num1 = 6 * 3 = 18
    printf("Number 1: %d \n", num1);

These two lines multiply num1 and num2 and assign the result to num1. As a result, the value of num1 becomes 18. The new value of num1 is then printed. 

    num2 = num1 / num2;     //num2 = 18 / 3 = 6 FINAL
    printf("Number 2: %d \n", num2);

These two lines divide num1 by num2 and assign the result to num2. As a result, the value of num2 becomes 6. The new value of num2 is then printed. 

    num1 = num1 / num2;     //num1 = 18 / 6 = 3 FINAL
    printf("Number 1: %d \n", num1);

These two lines divide num1 by the new value of num2 and assign the result to num1. As a result, the value of num1 becomes 3. The new value of num1 is then printed. 

    printf("Final State: %d, %d \n", num1, num2);

This line prints out the final state of the num1 and num2 variables after the swapping operation. 

    return 0;
}

This line indicates the end of the main() function and returns an integer value of 0 to the operating system, indicating that the program has executed successfully.

C Program - Swap Two Numbers WITHOUT using the Third Variable

This C program swaps the values of two variables num1 and num2 without using a temporary variable. 

#include <stdio.h>

int main()
{

    int num1 = 10;
    int num2 = 30;

    printf("Initial State: %d, %d \n", num1, num2);

    //Swap
    num1 = num1 - num2;                          //num1 = 10 - 30 = -20
    //printf("Number 1: %d \n", num1);

    num2 = num1 + num2;                          //num2 = -20 + 30 = 10   FINAL
    //printf("Number 2: %d \n", num2);

    num1 = num2 - num1;                          //num1 = 10 - (-20) = 30 FINAL
    //printf("Number 1: %d \n", num1);

    printf("Final State: %d, %d \n", num1, num2);


    return 0;
}

Result: 

Initial State: 10, 30
Final State: 30, 10

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

Here's a line-by-line explanation of the program: 

#include <stdio.h>

This line is a preprocessor directive that includes the standard input/output library in the program. This library contains functions for reading input and writing output. 

int main()
{

This is the starting point of the program. The main() function is the entry point of the program where the execution begins. The int before main() indicates that the function returns an integer value. 

    int num1 = 10;
    int num2 = 30;

These lines declare and initialize two integer variables named num1 and num2

    printf("Initial State: %d, %d \n", num1, num2);

This line prints out the initial state of the num1 and num2 variables. 

    num1 = num1 - num2;  // num1 = 10 - 30 = -20
    num2 = num1 + num2;  // num2 = -20 + 30 = 10
    num1 = num2 - num1;  // num1 = 10 - (-20) = 30

These three lines perform the swapping operation without using a temporary variable. The value of num1 is updated to the difference between num1 and num2, i.e., num1 = 10 - 30 = -20. Then, the value of num2 is updated to the sum of num1 and the original value of num2, i.e., num2 = -20 + 30 = 10. Finally, the value of num1 is updated to the difference between num2 and the new value of num1, i.e., num1 = 10 - (-20) = 30. As a result, the values of num1 and num2 are swapped. 

    printf("Final State: %d, %d \n", num1, num2);

This line prints out the final state of the num1 and num2 variables after the swapping operation. 

    return 0;
}

This line indicates the end of the main() function and returns an integer value of 0 to the operating system, indicating that the program has executed successfully.

C Program - Swap Two Numbers using a Temporary Variable

This C program swaps the values of two variables first and second using a temporary variable temp_var.

#include <stdio.h>

int main()
{

    int first, second, temp_var;

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

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

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

    printf("Initial state: %d, %d \n", first, second);

    temp_var = first; // now first is "free" container

    first = second; // first is final, second is "free" now

    second = temp_var; // second is final, number swaped now

    printf("Final state:   %d, %d \n", first, second);

    return 0;
}

Result: 

First Number: 10
Second Number: 20
-----------------------------
Initial state: 10, 20
Final state:   20, 10

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

Here's a line-by-line explanation of the program: 

#include <stdio.h>

This line is a preprocessor directive that includes the standard input/output library in the program. This library contains functions for reading input and writing output. 

int main()
{

This is the starting point of the program. The main() function is the entry point of the program where the execution begins. The int before main() indicates that the function returns an integer value. 

    int first, second, temp_var;

This line declares three integer variables named first, second, and temp_var

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

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

These lines prompt the user to enter the values of first and second variables respectively using the printf() function to display a message and the scanf() function to read the user input. 

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

    printf("Initial state: %d, %d \n", first, second);

These lines print out a separator line and display the initial state of the first and second variables. 

    temp_var = first; // now first is "free" container

    first = second; // first is final, second is "free" now

    second = temp_var; // second is final, number swaped now

These three lines perform the swapping operation. The current value of first is stored in the temp_var variable. The value of second is then assigned to first, and the value of temp_var is assigned to second. As a result, the values of first and second are swapped. 

    printf("Final state:   %d, %d \n", first, second);

This line prints out the final state of the first and second variables after the swapping operation. 

    return 0;
}

This line indicates the end of the main() function and returns an integer value of 0 to the operating system, indicating that the program has executed successfully.

C Program - Calculate Area of an Equilateral Triangle

This program calculates the area and perimeter of an equilateral triangle, given its side length. It prompts the user to enter the side length of the triangle, reads in the value using scanf, and then calculates the area and perimeter.

//Equilateral Triangle Area:

#include <stdio.h>
#include <math.h> // for sqrt() function

int main()
{

    float side, area, parimeter, temp_var;

    printf("Triangle Side: \n");
    scanf("%f", &side);

    temp_var = (sqrt(3) / 4);

    area = temp_var * side * side;
    printf("Area of Triangle: %f \n", area);

    parimeter = 3 * side;
    printf("Parimeter: %f \n", parimeter);

    return 0;
}

Result: 

Triangle Side:
20
Area of Triangle: 173.205078
Parimeter: 60.000000

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

Here's a line-by-line explanation of the code: 

#include <stdio.h>
#include <math.h> // for sqrt() function

These are header files. The first one includes the standard input/output functions in C and the second one includes the math library which has the sqrt() function. 

int main()
{
    float side, area, parimeter, temp_var;

    printf("Triangle Side: \n");
    scanf("%f", &side);

This declares the main function and initializes some variables to hold the side length, area, perimeter, and a temporary variable. The program then prompts the user to enter the side length of the equilateral triangle and reads the value into the "side" variable using the scanf() function. 

    temp_var = (sqrt(3) / 4);

    area = temp_var * side * side;
    printf("Area of Triangle: %f \n", area);

    parimeter = 3 * side;
    printf("Parimeter: %f \n", parimeter);

    return 0;
}

This calculates the area and perimeter of the equilateral triangle using the given formulas:

  • Area = (sqrt(3) / 4) * side * side
  • Perimeter = 3 * side

The program then prints the values of the area and perimeter to the console using printf(). Finally, the program returns 0 to indicate successful program execution.

C Program - Multiple Circles inside C Array - Circumference and Area Calculator

This program calculates the area and circumference of a circle, given its radius. It prompts the user to enter the radius of the circle, reads in the value using scanf, and then calculates the area and circumference using the formulas "PI * radius * radius" and "2 * PI * radius", respectively, where PI is a constant value defined using the #define preprocessor directive.

After calculating the area and circumference, the program prints the values to the console using printf. Finally, the program returns 0 to indicate successful program execution.

In short, this program is a simple calculator for the area and circumference of a circle, given its radius. 

//calculate multiple circle area and circumference using c array

#include <stdio.h>

#define PI 3.14159
#define SEPARATOR "----------------------------------------- \n"

int main()
{

    float area, circumference;
    int x; // for for loop

    int radiuses[] = {20, 34, 50, 14}; //circles

    int number_of_circles = sizeof(radiuses)/sizeof(radiuses[0]);

    for (x = 0; x < number_of_circles; x++)
    {
        printf("\nCalculation for circle %d with radius %d: \n", x, radiuses[x]);

        area = PI * radiuses[x] * radiuses[x];
        printf("Area: %f \n", area);

        circumference = 2 * PI * radiuses[x];
        printf("Circumference: %f \n", circumference);
        printf(SEPARATOR);
    }

    return 0;

}

Result: 


Calculation for circle 0 with radius 20:
Area: 1256.635986
Circumference: 125.663597
-----------------------------------------

Calculation for circle 1 with radius 34:
Area: 3631.677979
Circumference: 213.628113
-----------------------------------------

Calculation for circle 2 with radius 50:
Area: 7853.975098
Circumference: 314.158997
-----------------------------------------

Calculation for circle 3 with radius 14:
Area: 615.751648
Circumference: 87.964523
-----------------------------------------

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

Here's a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library, which is needed for functions like printf and scanf. 

#define PI 3.14159
#define SEPARATOR "----------------------------------------- \n"

These lines define two constant values: "PI" and "SEPARATOR". PI is set equal to 3.14159, and SEPARATOR is set equal to a string of dashes that will be used to separate the calculations for each circle. 

int main()
{
    float area, circumference;
    int x; // for for loop

    int radiuses[] = {20, 34, 50, 14}; //circles

    int number_of_circles = sizeof(radiuses)/sizeof(radiuses[0]);

This is the "main" function of the program. It declares two float variables: "area" and "circumference". It also declares an integer variable "x" to use in a for loop. It then declares an integer array "radiuses" containing the radii of four circles.

The variable "number_of_circles" is set to the number of elements in the "radiuses" array using the sizeof operator. 

    for (x = 0; x < number_of_circles; x++)
    {
        printf("\nCalculation for circle %d with radius %d: \n", x, radiuses[x]);

        area = PI * radiuses[x] * radiuses[x];
        printf("Area: %f \n", area);

        circumference = 2 * PI * radiuses[x];
        printf("Circumference: %f \n", circumference);
        printf(SEPARATOR);
    }

This is a for loop that iterates through the "radiuses" array for each circle. It first prints a message using printf indicating which circle is being calculated, along with its radius. It then calculates the area and circumference of the circle using the formulas "PI * radius * radius" and "2 * PI * radius", respectively, and stores them in the "area" and "circumference" variables.

It then prints the calculated values of the area and circumference to the console using printf, along with the SEPARATOR string to separate the calculations for each circle. 

    return 0;
}

Finally, the main function returns 0 to indicate successful program execution.

In summary, this code calculates the area and circumference of multiple circles based on an array of radii using a for loop. It first defines constant values for PI and a separator string, then reads in the radii from an array and calculates the area and circumference of each circle using formulas. It then prints the calculated values of the area and circumference for each circle to the console, along with a separator string to make it clear which circle the calculations correspond to.

C Program - Calculate Area and Circumference of a Circle

This program calculates the area and circumference of a circle based on a user inputted radius.

It first defines the constant value of PI as 3.14159.

Then, it prompts the user to input the radius of the circle using printf and reads in the user's input using scanf.

It calculates the area of the circle using the formula "PI * radius * radius" and stores it in the "area" variable. It also calculates the circumference of the circle using the formula "2 * PI * radius" and stores it in the "circumference" variable.

Finally, it prints the calculated values of the area and circumference to the console using printf, and returns 0 to indicate successful program execution. 

//are and circumference of a circle
#include <stdio.h>

#define PI 3.14159

int main()
{

    float area, circumference, radius;

    printf("Circle Radius: \n");
    scanf("%f", &radius);

    area = PI * radius * radius;
    printf("Area: %f \n", area);

    circumference = 2 * PI * radius;
    printf("Circumference: %f \n", circumference);

    return 0;

}

Result: 

Circle Radius:
20
Area: 1256.635986
Circumference: 125.663597

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

Here's a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library, which is needed for functions like printf and scanf. 

#define PI 3.14159

This line defines a constant value called "PI" and sets it equal to 3.14159. This constant will be used to calculate the area and circumference of the circle. 

int main()
{
    float area, circumference, radius;

    printf("Circle Radius: \n");
    scanf("%f", &radius);

This is the "main" function of the program. It declares three float variables: "area", "circumference", and "radius". It then uses printf to ask the user to input the radius of the circle, and uses scanf to read in the user's input and store it in the "radius" variable. 

    area = PI * radius * radius;
    printf("Area: %f \n", area);

This calculates the area of the circle using the formula "PI * radius * radius" and stores it in the "area" variable. It then uses printf to print the calculated area to the console. 

    circumference = 2 * PI * radius;
    printf("Circumference: %f \n", circumference);

This calculates the circumference of the circle using the formula "2 * PI * radius" and stores it in the "circumference" variable. It then uses printf to print the calculated circumference to the console. 

    return 0;
}

Finally, the main function returns 0 to indicate successful program execution.

C Program - Find Largest Element of an Array

This code finds the largest element in an array of integers by iterating through the array and comparing each element to a variable called "largest_atm".

It starts by assuming that the first element in the array is the largest so far, and then it checks each subsequent element to see if it is larger. If it is, then it updates the value of "largest_atm" to be that element instead. After iterating through the entire array, it returns the value of "largest_atm".

In the "main" function, an array of integers is declared and initialized with some values.

The number of elements in the array is determined using the sizeof operator, which returns the total size of the array in bytes. Since each element in the array is an integer, and an integer takes up 4 bytes of memory, the total size of the array in bytes is equal to the number of elements multiplied by 4.

Therefore, the size of the array in bytes is divided by the size of one element in bytes to get the number of elements in the array. This value is then passed along with the array to the "find_largest" function, which returns the largest element in the array.

This value is then printed to the console using printf. Finally, the main function returns 0 to indicate successful program execution.

//largest elements

#include <stdio.h>

int find_largest(int some_array[], int number_of_elements)
{
    int x, largest_atm;

    largest_atm = some_array[0];

    for (x = 1; x < number_of_elements; x++)
        if (some_array[x] > largest_atm)
            largest_atm = some_array[x];

    return largest_atm;
}

int main()
{

    int some_array[] = {5, 25, 243, 1, -10, -5, 500};

    int number_of_elements = sizeof(some_array)/sizeof(some_array[0]);

    printf("Largest Element %d \n", find_largest(some_array, number_of_elements));

    return 0;
}

Result: 

Largest Element 500

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

Here's a line-by-line explanation of the code: 

#include <stdio.h>

This line includes the standard input/output library, which is needed for functions like printf. 

int find_largest(int some_array[], int number_of_elements)
{
    int x, largest_atm;

    largest_atm = some_array[0];

    for (x = 1; x < number_of_elements; x++)
        if (some_array[x] > largest_atm)
            largest_atm = some_array[x];

    return largest_atm;
}

This is the implementation of the "find_largest" function. It takes two arguments: an array of integers "some_array" and the number of elements in the array "number_of_elements". It declares two integer variables, "x" and "largest_atm", and initializes "largest_atm" to the first element in the array.

It then loops through the rest of the elements in the array, comparing each element to "largest_atm" and updating "largest_atm" if the element is larger.

After iterating through the entire array, it returns the value of "largest_atm". 

int main()
{

    int some_array[] = {5, 25, 243, 1, -10, -5, 500};

    int number_of_elements = sizeof(some_array)/sizeof(some_array[0]);

    printf("Largest Element %d \n", find_largest(some_array, number_of_elements));

    return 0;
}

This is the "main" function of the program. It first declares an array of integers called "some_array" and initializes it with some values.

It then determines the number of elements in the array by dividing the total size of the array in bytes (which is given by "sizeof(some_array)") by the size of one element in bytes (which is given by "sizeof(some_array[0])"). It then calls the "find_largest" function, passing in "some_array" and "number_of_elements" as arguments, and prints the result to the console using printf.

Finally, it returns 0 to indicate successful program execution.

C Program - How do you Add Elements to a 2D Array in C

This C program reads input from the user and stores it in a 2-dimensional integer array called number_arr. It then prints the contents of the array to the console. 

//get stuff into 2d array
#include <stdio.h>

int main()
{

    int a, b; //insertion of elements
    int x, y; //extraction - printing

    int number_arr[2][4];

    //Insertion of elements into 2d array

    for (a = 0; a < 2; a++)
    {
        for (b = 0; b < 4; b++)
        {
            printf("Enter value for number_arr[%d][%d] ", a, b);
            scanf("%d", &number_arr[a][b]);
        }
    }

    //Printing

    for (x = 0; x < 2; x++)
    {
        if (x == 1)
        {
            printf("\n");
        }
        for (y = 0; y < 4; y++)
        {
            printf("%d ", number_arr[x][y]);
        }
    }

    return 0;
}

Result: 

Enter value for number_arr[0][0] 1
Enter value for number_arr[0][1] 2
Enter value for number_arr[0][2] 3
Enter value for number_arr[0][3] 4
Enter value for number_arr[1][0] 5
Enter value for number_arr[1][1] 6
Enter value for number_arr[1][2] 7
Enter value for number_arr[1][3] 8
1 2 3 4
5 6 7 8
Process returned 0 (0x0)   execution time : 20.221 s
Press any key to continue.

Code explanation: 

#include <stdio.h>

This line includes the standard input/output library, which provides the necessary functions for input and output operations in C programs. 

int main()
{

This line declares the main function, which is the entry point for the program. The int before main indicates that the function returns an integer value to the operating system when it terminates. 

    int a, b; //insertion of elements
    int x, y; //extraction - printing

    int number_arr[2][4];

These lines declare the integer variables a, b, x, and y, which will be used to iterate over the rows and columns of the 2-dimensional array number_arr. The array is initialized with 2 rows and 4 columns. 

    //Insertion of elements into 2d array

    for (a = 0; a < 2; a++)
    {
        for (b = 0; b < 4; b++)
        {
            printf("Enter value for number_arr[%d][%d] ", a, b);
            scanf("%d", &number_arr[a][b]);
        }
    }

These lines begin a nested for loop that iterates over the rows and columns of the number_arr array. Inside the loop, the printf function is called to prompt the user to enter a value for the current element of the array, and the scanf function is called to read the user's input and store it in the array. 

    //Printing

    for (x = 0; x < 2; x++)
    {
        if (x == 1)
        {
            printf("\n");
        }
        for (y = 0; y < 4; y++)
        {
            printf("%d ", number_arr[x][y]);
        }
    }

These lines begin a nested for loop that iterates over the rows and columns of the number_arr array. Inside the loop, the printf function is called to print the current element of the array to the console.

If the current row x is equal to 1, a newline character (\n) is printed to the console to start a new line before printing the elements of the second row. 

    return 0;
}

This line ends the main function and returns the integer value 0 to the operating system, indicating that the program has terminated successfully.

Monday, April 28, 2025

C Program - How to Print 2D Array in C with For Loops

This program creates a 2-dimensional integer array number_arr with 2 rows and 4 columns. It then uses a nested for loop to iterate through each element in the array and print its value to the console.

The outer loop iterates through the rows of the array (x), while the inner loop iterates through the columns of the array (y). The if statement inside the outer loop checks if x is equal to 1, and if so, prints a newline character to the console to separate the two rows of the array.

The program then prints each element in the array using the printf() function with the %d format specifier to print integers.

When run, this program will output the following to the console: 

1 2 3 4 
5 6 7 8 

Note that the two commented-out printf() statements at the bottom of the program demonstrate how to access individual elements of the array by their row and column indices. For example, number_arr[0][0] would access the element in the first row and first column of the array, which has a value of 1

#include <stdio.h>

int main()
{

    int x, y;

    int number_arr[2][4] =
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };

    for (x = 0; x < 2; x++)
    {
        if (x == 1)
        {
            printf("\n");
        }
        for (y = 0; y < 4; y++)
        {
            printf("%d ", number_arr[x][y]);
        }
    }

    return 0;
}

//printf("%d \n", number_arr[0][0]);
//printf("%d \n", number_arr[1][0]);

Result: 

1 2 3 4
5 6 7 8
Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

Let's break down the C program line by line: 

#include <stdio.h>

This line includes the standard input/output library, which provides the necessary functions for input and output operations in C programs. 

int main()
{

This line declares the main function, which is the entry point for the program. The int before main indicates that the function returns an integer value to the operating system when it terminates. 

    int x, y;

This line declares two integer variables x and y, which will be used to iterate over the rows and columns of the 2-dimensional array number_arr

    int number_arr[2][4] =
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };

This line initializes a 2-dimensional integer array number_arr with 2 rows and 4 columns. The first row contains the values 1, 2, 3, and 4, while the second row contains the values 5, 6, 7, and 8

    for (x = 0; x < 2; x++)
    {

This line begins a for loop that iterates over the rows of the number_arr array. The loop starts with x equal to 0 and continues until x is less than 2

        if (x == 1)
        {
            printf("\n");
        }

This line checks if the current row x is equal to 1. If it is, a newline character (\n) is printed to the console to start a new line before printing the elements of the second row. 

        for (y = 0; y < 4; y++)
        {
            printf("%d ", number_arr[x][y]);
        }

This line begins a nested for loop that iterates over the columns of the number_arr array. The loop starts with y equal to 0 and continues until y is less than 4.

Inside the nested loop, the printf function is called to print the current element of the array, which is accessed using the indexes x and y. The format specifier %d is used to print an integer value, followed by a space character to separate the values. 

    }

This line ends the nested for loop. 

    return 0;
}

This line ends the main function and returns the integer value 0 to the operating system, indicating that the program has terminated successfully.

C Program - Find Quotient and Remainder - Modulo Operator

This program prompts the user to enter a dividend and a divisor, then performs integer division on them and displays the quotient and remainder of the division operation.

The program uses the % (modulus) operator to calculate the remainder and the / (division) operator to calculate the quotient. It then displays the result using printf().

Note that this program assumes that the user enters valid integer values for the dividend and divisor, and does not perform any input validation or error checking.

In arithmetic, the modulo operation finds the remainder after division of one number by another. Given two positive integers, a (the dividend) and n (the divisor), the modulo operation (denoted by the symbol %) returns the integer remainder of the division a/n.

For example, the expression 13 % 5 would evaluate to 3, because when 13 is divided by 5, the remainder is 3. Similarly, 24 % 7 would evaluate to 3, because 24 divided by 7 is 3 with a remainder of 3.

#include <stdio.h>

int main()
{

    int dividend_num, divisor_num, quotient, remainder;

    printf("Enter Dividend: ");
    scanf("%d", &dividend_num);

    printf("Enter Divisor: ");
    scanf("%d", &divisor_num);

    quotient = dividend_num / divisor_num;

    remainder = dividend_num % divisor_num;

    printf("----------------------- \n");
    printf("Quotient: %d  \n", quotient);
    printf("Remainder: %d \n", remainder);
    printf("----------------------- \n");

    return 0;
}

Result: 

Enter Dividend: 10
Enter Divisor: 3
-----------------------
Quotient: 3
Remainder: 1
-----------------------

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

Here's an explanation of each block of code in the program: 

#include <stdio.h>

This line includes the standard input-output library header file.

int main()
{

This line declares the main function that runs when the program is executed. The int keyword specifies that the function returns an integer value (0 in this case). 

int dividend_num, divisor_num, quotient, remainder;

This block of code declares four integer variables:

  • dividend_num: the number that will be divided by the divisor_num
  • divisor_num: the number that dividend_num will be divided by
  • quotient: the result of the division operation, which is the whole number part of the answer
  • remainder: the result of the division operation, which is the remainder part of the answer 
printf("Enter Dividend: ");
scanf("%d", &dividend_num);

printf("Enter Divisor: ");
scanf("%d", &divisor_num);

These lines prompt the user to enter the dividend_num and divisor_num values and read them into the corresponding integer variables using scanf()

quotient = dividend_num / divisor_num;

remainder = dividend_num % divisor_num;

These lines perform the division operation on dividend_num and divisor_num and store the results in quotient and remainder respectively. The / operator is used for the division operation, which returns the whole number part of the answer, while the % operator is used for the modulus operation, which returns the remainder part of the answer. 

printf("----------------------- \n");
printf("Quotient: %d  \n", quotient);
printf("Remainder: %d \n", remainder);
printf("----------------------- \n");

These lines use printf() to display the quotient and remainder values, along with some additional formatting. The ----------------------- string is used to separate the output for visual clarity. 

return 0;

This line returns an integer value of 0 to the operating system to indicate that the program executed successfully.

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 .  ...