#includeint main() { printf("Hello, World!\n"); int a = 10; int b = 20; printf("Sum = %d\n", a + b); return 0; }
To start programming in C, you need to set up an environment. You can choose from several IDEs (Integrated Development Environments) such as:
A simple C program consists of functions and statements. The basic structure is as follows:
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // Output a message
return 0; // Indicate that the program ended successfully
}
For a more in-depth understanding, check out Learn C - Hello, World!.
C supports several built-in data types:
Declaring variables:
int age = 25;
float salary = 50000.50;
char grade = 'A';
Control structures dictate the flow of execution in a program:
if (age > 18) {
printf("Adult\n");
} else {
printf("Minor\n");
}
Loops allow repetitive execution of code:
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
Functions enable code reuse and organization. Here’s how to define and call a function:
void greet() {
printf("Hello!\n");
}
int main() {
greet(); // Calling the function
return 0;
}
Arrays are collections of variables of the same type:
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
Pointers store memory addresses, allowing for dynamic memory management:
int a = 10;
int *p = &a; // Pointer to variable a
printf("%d\n", *p); // Dereference the pointer to get the value of a
To understand pointers better, check out Learn C - Pointers.
Structures allow grouping of different data types:
struct Person {
char name[50];
int age;
};
struct Person p1 = {"Alice", 30};
printf("Name: %s, Age: %d\n", p1.name, p1.age);
Reading from and writing to files in C:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
fprintf(file, "Hello, File I/O!\n");
fclose(file);
return 0;
}
Dynamic memory allocation is done using malloc and free:
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int));
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
free(arr); // Always free allocated memory
return 0;
}
Handle errors gracefully to avoid program crashes:
#include <stdio.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (!file) {
perror("File opening failed");
return EXIT_FAILURE;
}
fclose(file);
return 0;
}
C is an essential language for system-level programming and offers powerful features that require careful management. With this guide, you now have a solid foundation to explore more advanced topics and projects.