C free
Created By: chatGPT
C is a general-purpose programming language that is widely used for system and application software. It was developed in the early 1970s at Bell Labs to improve upon the B programming language. C is known for its efficiency, portability, and flexibility. Here’s a simple example of a C program that prints
Hello, World!
to the console.#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
In the example above,
#include <stdio.h>
is a preprocessor directive that includes the standard input-output library. The main()
function is the entry point of every C program. Inside the main function, we have the printf
function, which is used to print text to the console.// Printing to console:
printf("Hello, World!\n");
C also supports variables, allowing you to store data. For instance, you can declare an
int
variable to store an integer value. Here’s an example that declares a variable, assigns it a value, and then prints it.int main() {
int number = 5;
printf("The number is: %d\n", number);
return 0;
}
In this code,
int number = 5;
declares an integer variable named number
and initializes it to 5. The printf
function is used again, utilizing the %d
format specifier to print the integer value.// Declaring and printing a variable:
int number = 5;
printf("The number is: %d\n", number);
C has powerful control structures such as loops and conditionals. Below is an example of a simple
for
loop that prints numbers from 1 to 5.int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
In this code, the
for
loop iterates from 1
to 5
, and the printf
function prints the current value of i
for each iteration. This illustrates how to execute a block of code multiple times.// For loop example:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
C also allows for the use of functions to organize code into reusable blocks. Below is a simple function that takes two integers and returns their sum.
int sum(int a, int b) {
return a + b;
}
int main() {
int result = sum(3, 4);
printf("Sum is: %d\n", result);
return 0;
}
The
sum
function takes two int
parameters and returns their total. In main
, the result of calling sum(3, 4)
is stored in the result
variable, which is then printed.// Using functions:
int sum(int a, int b) {
return a + b;
}