C Programming Basic Notes
C is a powerful, general-purpose programming language developed by Dennis Ritchie at Bell
Labs in the early 1970s. It is a procedural language, meaning it provides a step-by-step
approach to problem-solving. C is widely used for system programming, embedded systems,
game development, and more.
1. Structure of a C Program
A typical C program has the following basic structure:
#include <stdio.h> // Header file inclusion
int main() { // Main function - program execution starts here
// Your code goes here
printf("Hello, World!\n"); // Example: print statement
return 0; // Indicates successful program execution
}
#include <stdio.h>: This is a preprocessor directive. It includes the standard
input/output library, which provides functions like printf() (for printing output) and
scanf() (for taking input).
int main(): This is the main function where program execution begins. Every C
program must have a main function. int signifies that the function returns an integer
value.
{ ... }: Curly braces define a block of code.
printf("Hello, World!\n");: This statement prints the string "Hello, World!" to
the console. \n is an escape sequence that moves the cursor to the next line.
return 0;: This statement indicates that the program executed successfully. It's good
practice to return 0 from main.
2. Comments
Comments are used to explain code and are ignored by the compiler.
Single-line comment: // This is a single-line comment
Multi-line comment:
/* This is a
* multi-line
* comment */
3. Variables
Variables are named storage locations that hold data. Before using a variable, it must be
declared.
Declaration Syntax: dataType variableName;
Initialization: dataType variableName = value;
Common Data Types:
int: Stores whole numbers (e.g., 10, -500).
float: Stores single-precision floating-point numbers (e.g., 3.14, -0.5).
char: Stores a single character (e.g., 'A', 'z', '5').
Example:
int age = 30;
float pi = 3.14159;
char initial = 'J';
5. Input and Output
printf(): Used to display output on the console.
o Format Specifiers: Used to tell printf() what type of data to expect.
%d for int
%f for float
%lf for double
%c for char
%s for string (character array)
o Example:
int num = 10;
printf("The number is: %d\n", num);
scanf(): Used to take input from the user.
o Syntax: scanf("formatSpecifier", &variableName);
o Important: Use the & (address-of) operator before the variable name.
o Example:
int inputNum;
printf("Enter a number: ");
scanf("%d", &inputNum);
printf("You entered: %d\n", inputNum);
6. Operators
Operators perform operations on variables and values.
Arithmetic Operators: +, -, *, /, % (modulus)
Relational Operators: == (equal to), != (not equal to), >, <, >=, <=
Logical Operators: && (AND), || (OR), ! (NOT)
Assignment Operators: =, +=, -=, *=, /=, %=
Increment/Decrement Operators: ++ (increment), -- (decrement)
Example:
int a = 10, b = 5;
int sum = a + b; // sum is 15
printf("Is a equal to b? %d\n", a == b); // 0 (false)