Let’s create a simple C program step by step and explain each component.
- 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.
- 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. Theintbeforemainindicates that the function returns an integer value.int num1, num2, sum;: This line declares three integer variables callednum1,num2, andsum.printf("Enter two numbers: ");: This line uses theprintffunction to print the message “Enter two numbers: ” to the console.scanf("%d %d", &num1, &num2);: This line uses thescanffunction to read two integers entered by the user and store them in thenum1andnum2variables.sum = num1 + num2;: This line calculates the sum ofnum1andnum2and stores the result in thesumvariable.printf("The sum of %d and %d is %d", num1, num2, sum);: This line uses theprintffunction 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 themainfunction and returns a value of 0 to the operating system, indicating that the program executed successfully.
- Save the file: Save the file with a
.cextension, such assum.c. - 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.cfile and creates an executable file calledsum. - Run the program: To run the program, type the following command in the terminal:
./sum
This will execute the
sumprogram 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.