Creating a C Program

Let’s create a simple C program step by step and explain each component.

  1. Open a text editor: To create a C program, you can use any text editor that allows you to save files as plain text. Notepad, Notepad++, Sublime Text, and Visual Studio Code are all popular choices.
  2. Write the code: Here’s an example of a simple C program that calculates the sum of two integers and prints the result:
    #include <stdio.h>
    
    int main() {
       int num1, num2, sum;
       
       printf("Enter two numbers: ");
       scanf("%d %d", &num1, &num2);
    
       sum = num1 + num2;
       
       printf("The sum of %d and %d is %d", num1, num2, sum);
       
       return 0;
    }

    Let’s break down each line:

    • #include <stdio.h>: This line includes the standard input/output library, which provides functions for printing to the console and reading user input.
    • int main() {: This line defines the main function, which is the entry point of the program. The int before main indicates that the function returns an integer value.
    • int num1, num2, sum;: This line declares three integer variables called num1, num2, and sum.
    • printf("Enter two numbers: ");: This line uses the printf function to print the message “Enter two numbers: ” to the console.
    • scanf("%d %d", &num1, &num2);: This line uses the scanf function to read two integers entered by the user and store them in the num1 and num2 variables.
    • sum = num1 + num2;: This line calculates the sum of num1 and num2 and stores the result in the sum variable.
    • printf("The sum of %d and %d is %d", num1, num2, sum);: This line uses the printf function to print the message “The sum of [num1] and [num2] is [sum]” to the console, where [num1], [num2], and [sum] are replaced with the values of the corresponding variables.
    • return 0;: This line exits the main function and returns a value of 0 to the operating system, indicating that the program executed successfully.
  3. Save the file: Save the file with a .c extension, such as sum.c.
  4. Compile the program: To run the program, you need to compile it first. Open a terminal or command prompt, navigate to the directory where the file is saved, and type the following command:
    gcc sum.c -o sum

    This command compiles the sum.c file and creates an executable file called sum.

  5. Run the program: To run the program, type the following command in the terminal:
    ./sum

    This will execute the sum program and print the message “Enter two numbers: ” to the console. Enter two integers, and the program will calculate their sum and print the result to the console.

And that’s it! You have created and run your first C program.

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial