Guide on C Programming Syntax
1. Basic Structure of C Program
A simple C program includes the following basic structure:
#include <stdio.h>
int main() {
// Code goes here
return 0;
}
#include <stdio.h>: Includes the standard input/output library.
int main(): The main function where the program starts.
return 0;: Exits the program and returns 0, indicating successful execution.
2. Variables and Data Types
Variables store data, and C has several basic data types:
int: Integer numbers
float: Floating-point numbers
char: Characters
Example:
int age = 25;
float salary = 35000.50;
char grade = 'A';
3. Input and Output
C uses printf() to print output and scanf() to take input.
Output:
printf("Hello, World!\n");
Input:
scanf("%d", &age); // %d for integer input
4. Control Structures
C provides several control structures like if, else, while, for, etc.
if-else statement:
if (age > 18) {
printf("Adult");
} else {
printf("Minor");
}
for loop:
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
while loop:
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
5. Functions
Functions are blocks of code that perform a specific task.
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("Sum is: %d", result);
return 0;
}
6. Arrays
Arrays store multiple values of the same data type.
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d", numbers[2]); // Accesses the third element (index starts from 0)
7. Pointers
Pointers store the memory address of a variable.
int x = 10;
int *ptr = &x; // Pointer to variable x
printf("%d", *ptr); // Dereference pointer to access value
8. Structures
Structures allow grouping different data types under one name.
struct Person {
char name[50];
int age;
};
struct Person p1;
p1.age = 30;
strcpy(p1.name, "John");
9. Comments
Comments are used to explain the code and are ignored by the compiler.
Single-line comment: // This is a comment
Multi-line comment: /* This is a comment */