C Syntax
beginnerPart of C Fundamentals
Theory
Every C program follows a specific structure. Understanding C syntax is the first step to writing correct and efficient C code.
Structure of a C Program
A C program consists of preprocessor directives, global declarations, function definitions, and the mandatory main() function. The compiler processes the program from top to bottom.
#include <stdio.h> // Preprocessor directive
#define PI 3.14159 // Macro definition
int globalVar = 0; // Global variable
int main() { // Entry point
printf("Hello!\n");
return 0;
}The main() Function
main() is the entry point. It returns an int — return 0 means success, non-zero means error. It can accept command-line arguments via argc and argv[].
printf and scanf
printf()— formatted output:printf("Value: %d\n", x)scanf()— formatted input:scanf("%d", &x)(note the&address-of operator)
Common format specifiers: %d (int), %f (float), %c (char), %s (string), %p (pointer).
Header Files and Preprocessor
The preprocessor runs before compilation. #include inserts file contents. #define creates macros. The preprocessor also handles conditional compilation with #ifdef, #ifndef, #endif.
Practical Examples
Exercises
Temperature Converter
Write a C program that asks the user for a temperature in Celsius using scanf(), converts it to Fahrenheit using the formula F = C * 9/5 + 32, and prints the result using printf().
Starter Code:
#include <stdio.h>\n\nint main() {\n float celsius;\n // Your code here\n return 0;\n}Expected Output:
Enter temperature in Celsius: 25\n25.00°C = 77.00°F