Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

Thursday, May 1, 2025

C Tutorial

  1. C Tutorial - Setup and First Compilation
  2. C Tutorial - Line by Line - Detailed Explanations
  3. C Tutoria - Variables, Data Types, Format Specifiers
  4. C Tutoria - Constants and Comments
  5. C Tutorial - Simple Calculator
  6. C Tutorial - User Input
  7. C Tutorial - If..Else
  8. C Tutorial - If..Else with User Input
  9. C Tutorial - Switch Statement with User Input
  10. C Tutorial - For Loop with User Input
  11. C Tutorial - While and Do..While Loop
  12. C Tutorial - Break and Continue
  13. C Tutorial - Arrays
  14. C Tutorial - Strings
  15. C Tutorial - Pointers
  16. C Tutorial - Pointer to Pointer
  17. C Tutorial - Functions
  18. C Tutorial - Function Parameters
  19. C Tutorial - Return from Function
  20. C Tutorial - Structures
  21. C Tutorial - Typedef
  22. C Tutorial - Unions
  23. C Tutorial - getchar() and putchar() Functions
  24. C Tutorial - gets() and puts() Functions
  25. C Tutorial - How to Write to a File in C
  26. C Tutorial - How to Read from a File in C
  27. C Tutorial - Read Integer Values from a Text File in C
  28. C Tutorial - Write a Structure to a Text File with C

C Examples:

 

  1. C Program - Copy the Content of One File to Another File with User Input
  2. C Program - Print the Sum of All Elements in an Array
  3. C Program - Check Whether a Number is Positive or Negative using If Statement
  4. C Program - Nested If in C Programming Example
  5. C Program - Find ASCII Value of a Character Entered by User
  6. C Program - Print ASCII Value of a Characters inside C Array or String using a For Loop
  7. C Program - Find the Size of int, float, double and char
  8. C Program - Find the Average of Two Numbers with User Input
  9. C Program - Find the Average of Integers using a Function with Return Value
  10. C Program - Find Greatest of Three Numbers using If Statement
  11. C Program - Generate Multiplication Table with User Input
  12. C Program - Multiplication Table of a Numbers in a Given Range
  13. C Program - Display Characters from A to Z Using For Loop
  14. C Program - Check if Number is Even or Odd
  15. C Program - Check if Numbers are Even in Range from 1 to n
  16. C Program - Check whether an Alphabet is Vowel or Consonant
  17. C Program - Convert Lowercase String to Uppercase String
  18. C Program - Convert Uppercase String to Lowercase String
  19. C Program - Display All Alphabets And SKIP Special Characters
  20. C Program - Calculate Power of a Number using While Loop
  21. C Program - Calculate Power of a Number using pow() function
  22. C Program - Power of a Number for Elements inside C Array
  23. C Program – Find Length of a String without strlen() Function
  24. C Program - Get the String Length with While Loop
  25. C Program - Find Frequency of a Character in a String
  26. C Program - Find Quotient and Remainder - Modulo Operator
  27. C Program - How to Print 2D Array in C with For Loops
  28. C Program - How do you Add Elements to a 2D Array in C
  29. C Program - Find Largest Element of an Array
  30. C Program - Calculate Area and Circumference of a Circle
  31. C Program - Multiple Circles inside C Array - Circumference and Area Calculator
  32. C Program - Calculate Area of an Equilateral Triangle
  33. C Program - Swap Two Numbers using a Temporary Variable
  34. C Program - Swap Two Numbers WITHOUT using the Third Variable
  35. C Program - Swap Two Numbers using Multiplication and Division
  36. C Program - Store Information of Students Using Structure
  37. C Program - Print The Square Star Pattern
  38. C Program - Check Leap Year with C Programming Language
  39. How to Add gcc MinGW bin directory to System Path - Windows 10
  40. C Program - How to Implement Bubble Sort in C Programming Language
  41. C Program - Bubble Sort Algorithm using Function in C
  42. C Program - Bubble Sort In C using Nested While Loops
  43. C Program - Tile Calculator - The Total Number of Tiles Necessary to Cover a Surface
  44. C Program - Rectangle Calculator - Diagonal, Area, Parimeter
  45. C Program - Display its Own Source Code as Output
  46. C Program - strlen() Function Example - Find the Length of a String
  47. C Program - strcat() Function - How to Concatenate Strings in C
  48. C Program - strcpy() Function - Copy Content of One String into Another String
  49. C Program - strncpy() Function - Copy Specific Number of Characters from a String to Another String
  50. C Program - strcmp() Function - Compares Two Strings Character by Character

Wednesday, April 30, 2025

C Program - strcmp() Function - Compares Two Strings Character by Character

This is a C program that demonstrates how to compare two strings using the strcmp() function. 

#include <stdio.h>
#include <string.h>

int main()
{

    char left[] = "aaa";
    char right[] = "aaa";

    int compare_strings;

    compare_strings = strcmp(left, right);

    //printf("%d", compare_strings);

    if (compare_strings == 0)
    {
        printf("Same");
    }
    else if (compare_strings < 0)
    {
        printf("Left Positionaly Smaller");
    }
    else if (compare_strings > 0)
    {
        printf("Left Positionaly Bigger");
    }

    return 0;

}

Result: 

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

Here's a breakdown of the code block by block: 

#include <stdio.h>
#include <string.h>

These are header files that are included in the program to provide definitions for functions used later in the code. stdio.h is included for standard input/output functions, while string.h is included for string manipulation functions. 

int main()
{

This is the main function of the program, where execution begins. The function returns an integer value (in this case, 0) to indicate the status of the program when it exits. 

    char left[] = "aaa";
    char right[] = "aaa";

    int compare_strings;

    compare_strings = strcmp(left, right);

This declares two character arrays, left and right, and initializes them both with the same string "aaa". It also declares an integer variable compare_strings.

The strcmp() function is used to compare the two strings. The function returns an integer value that indicates the lexicographic relation between the two strings. The value 0 indicates that the strings are equal, a negative value indicates that left is lexicographically smaller than right, and a positive value indicates that left is lexicographically larger than right

    if (compare_strings == 0)
    {
        printf("Same");
    }
    else if (compare_strings < 0)
    {
        printf("Left Positionaly Smaller");
    }
    else if (compare_strings > 0)
    {
        printf("Left Positionaly Bigger");
    }

This uses a series of if statements to check the value of compare_strings and print out a message based on the result.

If compare_strings is 0, it means that the two strings are equal, so the program prints "Same".

If compare_strings is negative, it means that left is lexicographically smaller than right, so the program prints "Left Positionaly Smaller".

If compare_strings is positive, it means that left is lexicographically larger than right, so the program prints "Left Positionaly Bigger"

    return 0;
}

This statement ends the main() function and returns the value 0 to indicate successful program execution.

C Program - strncpy() Function - Copy Specific Number of Characters from a String to Another String

This is a C program that demonstrates how to copy a specific number of characters from one string to another using the strncpy() function. 

//copy just specific number of charactes from string

#include <stdio.h>
#include <string.h>

int main()
{

    char some_string[] = "Hack The Planet, coz it's fun.";

    char target_string[20]; //ako stavis vise onda je garbage

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

    strncpy(target_string, some_string, 10); //150, 5

    printf("Final Target String: %s \n", target_string);

    return 0;

}

Result: 

Some String: Hack The Planet, coz it's fun.
Initial Target String:
Final Target String: Hack The P

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

Here's a breakdown of the code block by block: 

#include <stdio.h>
#include <string.h>

These are header files that are included in the program to provide definitions for functions used later in the code. stdio.h is included for standard input/output functions, while string.h is included for string manipulation functions. 

int main()
{

This is the main function of the program, where execution begins. The function returns an integer value (in this case, 0) to indicate the status of the program when it exits. 

    char some_string[] = "Hack The Planet, coz it's fun.";

    char target_string[20];

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

This declares two character arrays: some_string and target_string. The former is initialized with a string literal, while the latter is left uninitialized.

The program then uses printf() to display the original input string some_string and an initial value of target_string on the console. 

    strncpy(target_string, some_string, 10);

    printf("Final Target String: %s \n", target_string);

The strncpy() function is used to copy the first 10 characters of some_string into target_string. The strncpy() function is similar to strcpy(), but it takes an additional argument that specifies the maximum number of characters to copy.

If the source string is shorter than the specified length, the remaining characters in the destination string are padded with null characters.

Finally, the program uses printf() to display the final value of target_string

    return 0;
}

This statement ends the main() function and returns the value 0 to indicate successful program execution.

C Program - strcpy() Function - Copy Content of One String into Another String

This is a C program that demonstrates the use of the string manipulation functions in the C standard library. The program prompts the user to input a string using the gets() function and then copies the string into a new character array using the strcpy() function. 

#include <stdio.h>
#include <string.h>

int main()
{

    //char some_string[] = "This is some string.";

    char some_string[100];

    printf("Enter Some String: \n");
    gets(some_string);

    char target_string[10];

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

    strcpy(target_string, some_string);

    printf("Final Target String: %s \n", target_string);

    /*
    for (int x = 0; x < strlen(target_string); x++) {
        printf("%c \n", target_string[x]);
    }
    */

    return 0;

}

Result: 

Enter Some String:
this is original string
Some String: this is original string
Initial Target String:
Final Target String: this is original string

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

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

#include <stdio.h>
#include <string.h>

These are header files that are included in the program to provide definitions for functions used later in the code. stdio.h is included for standard input/output functions, while string.h is included for string manipulation functions. 

int main()
{

This is the main function of the program, where execution begins. The function returns an integer value (in this case, 0) to indicate the status of the program when it exits. 

    char some_string[100];

    printf("Enter Some String: \n");
    gets(some_string);

This declares a character array called some_string with a size of 100 and prompts the user to input a string using the gets() function. The gets() function reads a line of text from standard input and stores it in the some_string array. However, as mentioned earlier, using gets() is not recommended due to potential buffer overflow vulnerabilities. 

    char target_string[10];

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

    strcpy(target_string, some_string);

    printf("Final Target String: %s \n", target_string);

This declares a new character array called target_string with a size of 10 and then uses the printf() function to display the original input string some_string and an initial value of target_string on the console.

The strcpy() function is then used to copy the contents of some_string into target_string. This replaces the original contents of target_string with the input string.

Finally, the program uses printf() to display the final value of target_string

    return 0;
}

This statement ends the main() function and returns the value 0 to indicate successful program execution.

C Program - strcat() Function - How to Concatenate Strings in C

This code combines two input strings entered by the user using the strcat() function from the string.h library. 

#include <stdio.h>
#include <string.h> //strcat() function

int main()
{

    char first_string[100];
    char second_string[100];

    printf("First String: ");
    gets(first_string);

    printf("Second String: ");
    gets(second_string);

    strcat(first_string, second_string);
    printf("Combination: %s \n", first_string);

    return 0;

}

Result: 

First String: some
Second String:  string
Combination: some string

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

Here's a line-by-line explanation: 

#include <stdio.h>
#include <string.h> //strcat() function

int main()
{

    char first_string[100];
    char second_string[100];

The program includes the necessary header files, and defines two character arrays with a size of 100 each. 

    printf("First String: ");
    gets(first_string);

    printf("Second String: ");
    gets(second_string);

The program prompts the user to enter two strings using printf() function and reads them using the gets() function.

Note: gets() function is considered unsafe and is deprecated in modern C. It is recommended to use fgets() instead. 

    strcat(first_string, second_string);
    printf("Combination: %s \n", first_string);

    return 0;

}

The program uses the strcat() function to concatenate the two strings, storing the result in the first_string variable. The concatenated string is then printed to the console using printf() function. Finally, the program returns 0 to indicate successful completion.

C Program - strlen() Function Example - Find the Length of a String

This program prompts the user to enter a string and then calculates and displays the length of the entered string. The program continues to prompt the user for input until the program is terminated. 

#include <stdio.h>
#include <string.h>

int main()
{

    char some_string[100];
    int length;

    while (1)
    {
        printf("Enter String: \n");
        gets(some_string);

        length = strlen(some_string);
        printf("String Length for %s is %d: \n", some_string, length);
        printf("-------------------------------------- \n");
    }

    return 0;
}

Result: 

Enter String:
some string
String Length for some string is 11:
--------------------------------------
Enter String:
test
String Length for test is 4:
--------------------------------------
Enter String:

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

#include <stdio.h>
#include <string.h>

This program includes the standard input/output library and the string library. 

int main()
{
    char some_string[100];
    int length;

This declares a character array some_string of size 100 to store the user input and an integer length to store the length of the input string. 

    while (1)
    {
        printf("Enter String: \n");
        gets(some_string);

This is a loop that prompts the user to enter a string and reads it from the console using gets() function. gets() reads the input as a character string, which is then stored in some_string.

Note: gets() is not safe to use, as it does not check the length of the input, so it can cause a buffer overflow if the input string is larger than the size of the array. 

        length = strlen(some_string);
        printf("String Length for %s is %d: \n", some_string, length);
        printf("-------------------------------------- \n");
    }

This calculates the length of the input string using the strlen() function and stores it in the length variable. The length is then printed to the console using printf() function. 

    return 0;
}

This ends the main function and returns 0, indicating successful execution of the program.

C Program - Display its Own Source Code as Output

This code opens the source code file itself using the fopen() function and reads its contents character by character using the getc() function, and then prints each character to the console using the putchar() function.

#include <stdio.h>

int main()
{

    FILE *file_pointer;
    char some_char;

    file_pointer = fopen(__FILE__, "r");

    while (some_char != EOF)
    {
        some_char = getc(file_pointer);
        putchar(some_char);
    }

    fclose(file_pointer);

    return 0;
}

Result: 

#include <stdio.h>

int main()
{

    FILE *file_pointer;
    char some_char;

    file_pointer = fopen(__FILE__, "r");

    while (some_char != EOF)
    {
        some_char = getc(file_pointer);
        putchar(some_char);
    }

    fclose(file_pointer);

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

Here is a line-by-line explanation: 

#include <stdio.h>

This line includes the standard input/output library. 

int main()
{

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

    FILE *file_pointer;
    char some_char;

This declares a file pointer file_pointer of type FILE, and a variable some_char of type char

    file_pointer = fopen(__FILE__, "r");

This line opens the current source code file (__FILE__) in read-only mode ("r") and assigns the resulting file pointer to file_pointer

    while (some_char != EOF)
    {
        some_char = getc(file_pointer);
        putchar(some_char);
    }

This block of code loops through the file pointed to by file_pointer until the end of the file (EOF) is reached. Each character of the file is read and assigned to some_char using getc(), and then printed to the console using putchar()

    fclose(file_pointer);

This line closes the file pointed to by file_pointer

    return 0;
}

This line signals the end of the main function and returns 0 to indicate successful program execution.

C Program - Rectangle Calculator - Diagonal, Area, Parimeter

This program calculates the area, perimeter, and diagonal of a rectangle based on its width and height. 

#include <stdio.h>
#include <math.h>

int main()
{

    float width, height, area, parimeter, diagonal;

    printf("Rectangle Calculator:  \n\n");
    printf("--------width--------- \n");
    printf("|                    | \n");
    printf("|                    | height\n");
    printf("|                    | \n");
    printf("|                    | \n");
    printf("---------------------- \n");

    printf("Width: ");
    scanf("%f", &width);

    printf("Height: ");
    scanf("%f", &height);

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

    area = width * height;
    parimeter = (2 * width) + (2 * height);
    diagonal = sqrt((width*width) + (height*height));

    printf("Area: %.2f \n", area);
    printf("Parimeter: %.2f \n", parimeter);
    printf("Diagonal: %.2f \n", diagonal);

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

    return 0;
}

Result: 

Rectangle Calculator:

--------width---------
|                    |
|                    | height
|                    |
|                    |
----------------------
Width: 100
Height: 50
---------------------
Area: 5000.00
Parimeter: 300.00
Diagonal: 111.80
---------------------

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

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

#include <stdio.h>
#include <math.h>

int main()
{

This code defines the standard library header files that will be used in the program, including stdio.h and math.h. It also defines the main function, which is the entry point of the program. 

    float width, height, area, parimeter, diagonal;

This code declares five float variables, namely width, height, area, perimeter, and diagonal. These variables will be used to store the input values for the width and height of the rectangle and the calculated values of its area, perimeter, and diagonal. 

    printf("Rectangle Calculator:  \n\n");
    printf("--------width--------- \n");
    printf("|                    | \n");
    printf("|                    | height\n");
    printf("|                    | \n");
    printf("|                    | \n");
    printf("---------------------- \n");

This code displays a prompt to the user asking for the width and height of the rectangle, and also shows a visual representation of the rectangle. 

    printf("Width: ");
    scanf("%f", &width);

    printf("Height: ");
    scanf("%f", &height);

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

This code prompts the user to input the width and height of the rectangle, and then stores these values in the width and height variables. 

    area = width * height;
    perimeter = (2 * width) + (2 * height);
    diagonal = sqrt((width*width) + (height*height));

This code calculates the area, perimeter, and diagonal of the rectangle based on its width and height, and stores the results in the area, perimeter, and diagonal variables, respectively. 

    printf("Area: %.2f \n", area);
    printf("Perimeter: %.2f \n", perimeter);
    printf("Diagonal: %.2f \n", diagonal);

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

    return 0;
}

This code displays the calculated values of the area, perimeter, and diagonal of the rectangle using the printf function. The %.2f format specifier is used to display the floating-point numbers with two decimal places. Finally, the function returns 0 to indicate successful execution of the program.

C Program - Tile Calculator - The Total Number of Tiles Necessary to Cover a Surface

This program calculates the total number of small elements required to cover a specified number of walls, given the dimensions of the walls and the dimensions of the small elements.

The main() function initializes integer variables big_width, big_height, small_width, small_height, and wall_number.

The program prompts the user to input the dimensions of the big wall (big_width and big_height), the dimensions of the small element (small_width and small_height), and the number of walls (wall_number).

The program then calculates the total surface area of the big wall (big_surface) and the small element (small_surface). It uses these values to calculate the number of small elements required to cover one wall (element_per_wall) and the total number of small elements required to cover all the walls (element_total).

Finally, the program prints the number of small elements required per wall and the total number of small elements required to cover all the walls to the console, and returns 0 to indicate successful program execution.

Note that the program assumes that the small elements will be arranged in a grid and that they will completely cover each wall without any overlap. It also assumes that the dimensions provided by the user are valid and that the division operations do not result in a divide-by-zero error. 

#include <stdio.h>

int main()
{

    int big_width, big_height;
    int small_width, small_height;
    int wall_number;

    printf("Big Width: ");
    scanf("%d", &big_width);

    printf("Big Height: ");
    scanf("%d", &big_height);

    printf("Small Width: ");
    scanf("%d", &small_width);

    printf("Small Height: ");
    scanf("%d", &small_height);

    printf("Number of Walls: ");
    scanf("%d", &wall_number);

    int big_surface = big_width * big_height;
    int small_surface = small_width * small_height;

    int element_per_wall = big_surface / small_surface;
    int element_total = wall_number * element_per_wall;

    printf("----------------------------- \n");
    printf("Element Number per Wall: %d   \n", element_per_wall);
    printf("Total Number of Elements: %d  \n", element_total);
    printf("----------------------------- \n");

    return 0;
}

Result: 

Big Width: 100
Big Height: 50
Small Width: 10
Small Height: 5
Number of Walls: 4
-----------------------------
Element Number per Wall: 100
Total Number of Elements: 400
-----------------------------

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

Here is a detailed explanation of each line and block of code in the program: 

#include <stdio.h>

This line includes the standard input-output library in the program. 

int main()
{

This line indicates the start of the main() function, which is the entry point of the program. 

    int big_width, big_height;
    int small_width, small_height;
    int wall_number;

These lines declare integer variables for the dimensions of the big wall (big_width and big_height), the dimensions of the small element (small_width and small_height), and the number of walls (wall_number). 

    printf("Big Width: ");
    scanf("%d", &big_width);

    printf("Big Height: ");
    scanf("%d", &big_height);

    printf("Small Width: ");
    scanf("%d", &small_width);

    printf("Small Height: ");
    scanf("%d", &small_height);

    printf("Number of Walls: ");
    scanf("%d", &wall_number);

These lines prompt the user to input the dimensions of the big wall (big_width and big_height), the dimensions of the small element (small_width and small_height), and the number of walls (wall_number) using printf() and scanf() functions. 

    int big_surface = big_width * big_height;
    int small_surface = small_width * small_height;

These lines calculate the surface area of the big wall (big_surface) and the small element (small_surface) by multiplying their respective dimensions. 

    int element_per_wall = big_surface / small_surface;
    int element_total = wall_number * element_per_wall;

These lines calculate the number of small elements required to cover one wall (element_per_wall) and the total number of small elements required to cover all the walls (element_total) using the surface area of the big wall and the small element. 

    printf("----------------------------- \n");
    printf("Element Number per Wall: %d   \n", element_per_wall);
    printf("Total Number of Elements: %d  \n", element_total);
    printf("----------------------------- \n");

These lines print the number of small elements required per wall (element_per_wall) and the total number of small elements required to cover all the walls (element_total) to the console using printf()

    return 0;
}

This line indicates the end of the main() function, and the program returns 0 to indicate successful program execution.

C Program - Bubble Sort In C using Nested While Loops

This code sorts an array of integers using the Bubble Sort algorithm and prints the sorted array to the console.

The array to be sorted is initialized at the beginning of the program, and the main() function contains a nested while loop that implements the Bubble Sort algorithm.

The algorithm works by repeatedly swapping adjacent elements if they are in the wrong order, and it continues doing this until the array is fully sorted.

Once the array is sorted, the program uses a for loop to iterate through the sorted array and print each element to the console. The program then returns 0 to indicate successful program execution. 

#include <stdio.h>

int main()
{

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

    while (x < num - 1)
    {
        int y = 0;
        while (y < num - 1 - x)
        {
            if (arr[y] > arr[y + 1])
            {
                temp = arr[y]; //helper variable
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
            y++;
        }
        x++;
    }

    printf("Sorted Array: \n");

    for (int 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 program: 

#include <stdio.h>

int main()
{

The program starts with the standard main() function and includes the standard library header stdio.h

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

The program initializes an integer array arr with 10 integers and initializes integer variables num, x, and temp

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

The program uses a nested while loop to implement the Bubble Sort algorithm. The outer loop executes num - 1 times and the inner loop executes num - 1 - x times. The variable y is used to iterate through the array. Inside the inner loop, the algorithm compares the current element with the next element of the array. If the current element is greater than the next element, they are swapped using a helper variable temp

    printf("Sorted Array: \n");

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

    return 0;
}

Finally, the program prints the sorted array using a for loop and returns 0 to indicate successful program execution.

C Program - Bubble Sort Algorithm using Function in C

This is a C program that sorts an array of integers in ascending order using the Bubble Sort algorithm. 

#include <stdio.h>

int main()
{

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

    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;
            }
        }
    }

    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.031 s
Press any key to continue.

Here's a detailed explanation of each line of the code: 

#include <stdio.h>

This line includes the standard input-output header file in the program. 

int main()
{

This is the main function of the program. 

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

This declares an array of integers with 10 elements and initializes it with some values. 

    int num = 10;

This sets the value of num to 10, which is the number of elements in the array. 

    int x, y;

These are integer variables used as loop counters. 

    int temp;

This is a temporary integer variable used for swapping the values of array elements during the sorting process. 

    for (x = 0; x < num - 1; x++)

This is the outer loop that iterates through the array elements from the first element to the second last element. 

        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 the inner loop that iterates through the array elements from the first element to the second last element of the unsorted portion of the array. It compares each adjacent pair of elements and swaps them if they are not in the correct order (i.e., the first element is greater than the second element). 

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

This prints the sorted array elements in ascending order. 

    return 0;
}

This statement ends the program and returns 0 to the operating system to indicate successful execution of the program.

Bubble Sort using Functions: 

#include <stdio.h> //include standard input-output library

void bubble_sort(int arr[], int num) //declare a function named bubble_sort with parameters: array of integers and size of the array
{
    int x, y; //declare two integer variables to be used in loops
    int temp; //declare a temporary variable to be used for swapping elements in the array

    for (x = 0; x < num - 1; x++) //outer loop for iterating over all elements in the array except the last one
    {
        for (y = 0; y < num - x - 1; y++) //inner loop for comparing adjacent elements in the array
        {
            if (arr[y] > arr[y + 1]) //check if the current element is greater than the next element
            {
                temp = arr[y]; //swap elements if the condition is true using a temporary variable
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
        }
    }

    printf("Sorted Array: \n"); //print a message indicating that the array is sorted
    for (x = 0; x < num; x++) //iterate over all elements in the sorted array
    {
        printf("%d ", arr[x]); //print each element of the sorted array
    }
}

int main() //start of the main function
{

    int arr[] = {2, 4, 3, 1, 6, 5, 8, 10, 7, 9}; //initialize an array of integers
    int num = sizeof(arr)/sizeof(arr[0]); //get the number of elements in the array

    bubble_sort(arr, num); //call the bubble_sort function with the array and its size as arguments

    return 0; //return 0 to indicate successful program execution
}

Result: 

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

INDEX

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.

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