Introduction to C Programming
Introduction to C Language
C is a general-purpose programming language developed by Dennis Ritchie at Bell Labs in the early 1970s. Ritchie created C as a low-level language that could be used to write efficient and portable system software.
Variables
Variable: A variable is an identifier or a name which is used to refer a value and this value varies or changes during the program execution.
Example: name = "tomba", surname = "laisharam", age = 25
Declaring Variables
We use a data type specifier along with the variable name:
int age; // int is a data type for integer and age is the name of variable
Types of Variables
Global Variable
Variables which are declared outside the main function block, and they can be used in the main program block and sub program block like functions.
Local Variable
Variables which are declared inside the main function block, and they are used only in the block in which they are declared. Sub programs or functions can also have local variables.
Initialization and Assignment
Initialization
When we declare a variable and give it a value at the same time, it's called initialization.
Example:
int age = 32; // Declaration and initialization
Assignment
When we give a new value to an already declared variable, it's called assignment.
Example:
age = 25; // Assigning a new value
Assignment is not limited to changing values. If a variable was declared but not initialized, we can assign a value to it later.
int age; // Declaration without initialization
age = 30; // Assignment after declaration
Constants
Constant: Any unchanged value in a program during program execution is called a constant.
Types of Constants
Numeric Constants
-
Integer Constant: An integer constant is a signed or unsigned whole number.
Example:
-24, 52, 102
-
Real or Floating Point Constant: Any signed or unsigned number with fractional part.
Example:
3.14, 0.234, 0.42e-32
String or Character Constants
-
Single character string constant: Any letter or character enclosed in single quotes.
Example:
'h', 'a', '+'
-
String of characters constant: Any string of characters consisting of letters, digits, and symbols enclosed in double quotes.
Example:
"letters", "number02", "person+name+$"
Libraries
Library: A library in C is a collection of pre-compiled functions and routines that can be used in programs to perform common tasks, such as input/output, string handling, or math operations.
Common Libraries
-
stdio.h
: Provides functions for input/output operations (e.g., printf, scanf) -
conio.h
: Console input/output (older compilers like Turbo C++) -
math.h
: Mathematical functions (e.g., sqrt, pow) -
string.h
: String manipulation functions (e.g., strcpy, strcmp) -
stdlib.h
: System-related functions (e.g., malloc, free)
Sometimes programmers write their own libraries for their specific needs.
Preprocessor Directives
Preprocessor directives in C are instructions that are processed by the C preprocessor before the actual compilation of the program begins. These directives begin with the symbol #
and are used to include files, define constants or macros, and control the compilation process conditionally.
Types of Preprocessor Directives
-
File Inclusion
: Used to include contents of another fileSyntax:
#include <file>
-
Macro Definition
: Used to define symbolic constant or macroExample:
#define MONTH 30
More preprocessor directives are available at GeeksforGeeks
C Keywords
There are 32 available Keywords in C (version C98/C90)
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
Structure of C Program
<Header files>
<Global declaration of variables>
main()
{
<Local declaration of variables>
--------------
<Statements>
--------------
}
<Sub programs - function blocks>
- The header files tell compiler to include required files to run the program, define macros substitution etc.
- Global declaration of variable declares the variable outside the main block meaning the declared variable can be use by any function or also by the main function.
- Local declaration of variable means that the variable is declared inside the main block and cannot be used in other sub blocks.
- The statements which are written inside the main function will only execute other statements which are written outside the main block will not be executed
- Functions are just like another main block which will not be executed but which can be called in the main block to do certain actions, work, etc.
Basic Data Types
-
int
: Refers to integer. It can hold a signed or unsigned whole number within specific range. -
char
: Refers to character. It can hold one letter/symbol. In fact, char in C language is associated with integers refers to a letter/symbol as per ASCII which has assigned integer value for all letters/symbol used in programming. -
float
: Refers to floating point or real number. It can hold a real number like 3.174813 or 4.53e6 with six decimal digits in decimal or exponential form. -
double
: Also refers to floating or real number. It can hold a real number in double precision. A double precision number uses 12 decimal digit like 3.42134421232 or 4.2324452423e12.
More data types are available at GeeksforGeeks
Operators
Arithmetic Operators
+ : addition
, 1 + 1 = 2- : subtraction
, 2 - 1 = 1* : multiplication
, 2 * 3 = 6/ : division
, 8 / 2 = 4
Relational Operators
< : less than
: 5 < 2 : FALSE> : greater than
: 5 > 2 : TRUE<= : less than or equal to
: 5 <= 2 : FALSE>= : greater than or equal to
: 5 >= 2 : TRUE== : equal to
: 5 == 2 : FALSE or 5 == 5 : TRUE!= : not equal to
: 5 != 2 : TRUE
Logical Operators
&& : AND
: Returns TRUE if all the given condition or statement are true, if any statement is false, it will always return FALSE
Example: (5<2) && (5>2) : FALSE
|| : OR
: Return TRUE if any of the given condition or statement are true, if none of the condition is TRUE, it will always return FALSE
Example: (5<2) || (5>3) : TRUE
! : NOT
: Return TRUE if the condition is FALSE, if the condition is TRUE, it will always return FALSE
Example: !(5<2) : TRUE
Truth Tables
AND (&&) Operator
OPERAND 1 | OPERAND 2 | RESULT |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
OR (||) Operator
OPERAND 1 | OPERAND 2 | RESULT |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
NOT (!) Operator
OPERAND | RESULT |
---|---|
true | false |
false | true |
Increment and Decrement
Increment
The increment operator in C is represented by the ++
symbol.
-
Pre-increment:
++variable
The value of the variable is incremented by 1 before it is used in the expression.
Example:
x = ++y;
(first incrementsy
by 1, then assigns the new value ofy
tox
) -
Post-increment:
variable++
The value of the variable is used in the expression first, and then it is incremented by 1.
Example:
x = y++;
(first assigns the current value ofy
tox
, then incrementsy
by 1)
Decrement
The decrement operator in C is represented by the --
symbol.
-
Pre-decrement:
--variable
The value of the variable is decremented by 1 before it is used in the expression.
Example:
x = --y;
(first decrementsy
by 1, then assigns the new value ofy
tox
) -
Post-decrement:
variable--
The value of the variable is used in the expression first, and then it is decremented by 1.
Example:
x = y--;
(first assigns the current value ofy
tox
, then decrementsy
by 1)
Example
int x = 5;
int y = 10;
// Pre-increment
x = ++y; // x = 11, y = 11
// Post-increment
x = y++; // x = 11, y = 12
// Pre-decrement
x = --y; // x = 11, y = 11
// Post-decrement
x = y--; // x = 12, y = 11
Assignment Operators
In C programming, assignment operators are used to assign values to variables.
Simple Assignment (=)
Assigns the value on the right to the variable on the left.
int x = 10; // x is now 10
Addition Assignment (+=)
Adds the right operand to the left operand and assigns the result to the left operand.
int x = 10;
x += 5; // x is now 15 (10 + 5)
Subtraction Assignment (-=)
int x = 10;
x -= 3; // x is now 7 (10 - 3)
Multiplication Assignment (*=)
int x = 10;
x *= 2; // x is now 20 (10 * 2)
Division Assignment (/=)
int x = 10;
x /= 2; // x is now 5 (10 / 2)
Modulus Assignment (%=)
int x = 10;
x %= 3; // x is now 1 (10 % 3)
Conditional (Ternary) Operator
Conditional Operator or Ternary operator is used to check a condition and select a value depending on the condition. It's a shorter version of if-else statement.
Syntax: (condition) ? value1 : value2;
If the condition is TRUE it will execute the value1
and if the condition is FALSE it will execute the value2
.
Comparison: Ternary vs If-Else
Ternary
int a = 10;
int b = 15;
int big;
big = (a > b) ? a : b;
If-Else
int a = 10;
int b = 15;
int big;
if (a > b) {
big = a;
} else {
big = b;
}
Bitwise Operators
Recommended not to focus much on these as they are for advanced programmers who manages data at bit level.
Some research on Binary numbers and Base 2 number system will help understand these better!
Bitwise Operators in C
Operator | Name | Description |
---|---|---|
& |
AND | 1 if both bits are 1 |
| |
OR | 1 if at least one bit is 1 |
^ |
XOR | 1 if only one of the bits is 1 |
~ |
NOT | Flips all bits (0 becomes 1, and 1 becomes 0) |
<< |
Left Shift | Shifts bits left, fills 0s on the right |
>> |
Right Shift | Shifts bits right, removes bits from the end |
Example
#include <stdio.h>
int main() {
int a = 5; // Binary: 00000101
int b = 3; // Binary: 00000011
printf("a & b = %d\n", a & b); // 00000001 → 1
printf("a | b = %d\n", a | b); // 00000111 → 7
printf("a ^ b = %d\n", a ^ b); // 00000110 → 6
printf("~a = %d\n", ~a); // In 8-bit: 11111010 → -6 (2's complement)
printf("a << 1 = %d\n", a << 1); // 00001010 → 10
printf("a >> 1 = %d\n", a >> 1); // 00000010 → 2
return 0;
}
Frequently Asked Questions
We include header files because they contain pre-defined functions, macros which will help us write a program without making complex functions.
We can also write a program without including a header file but we need to write our own functions. For example, if we don't include the stdio.h header file we need to make custom functions for printing and getting user input like printf and scanf ourselves.
TL;DR
We include header files to use pre-defined functions and macros. If we don't include them, we need to make the functions ourselves.
Using void is also discouraged for large projects.
Main function is the only function which is executed by the program. A function needs a type, so we specify the type of our main function. 'int' means it has an integer return type and 'void' means no return type. The OS also checks for return type to determine what happened to the program.
- For every function there should be a type and the types can be our choice whether int/void - it totally depends on us
- If we want to debug our code we specify the return type to
int
for main because when the main program executes successfully it returns 0 and when it has an error it returns 1 - If we don't want to debug or bother with returns we specify
void
to main because when it executes it will not return anything - The OS or the system checks the program running via the return type - if return was 1 it knows the program has run into an error and will notify you
TL;DR
We use int/void for main because main is also a function and every function needs its type to determine return type. We use int when we need to debug code because it returns 0 when it works and 1 when it gives error. We use void to specify no return type meaning nothing will return and the OS also checks the program condition using return values.
Then why can't we use char main() or float main()?
We can use char or float type with main but it is highly discouraged because the OS or the system checking the program condition via the return value will not be able to understand char return and float return as said in the above that 0 and 1 are used for success and error and there are no known values for char and float return.
TL;DR
We can use char or float main but it is highly discouraged as the OS will not know the return values because the OS does not have any idea what a char or float return means as it works on 0 and 1 for return.
Examples
Variable Declaration
// Declaring a variable
// We use a type specifier to declare a variable [int, char, float, double] choose the required type
int age = 25; // int for age as it is integer
char name[20] = "tomba"; // We are using array - it's just a collection of many char
float pi = 3.14; // We are using float for decimal numbers
Simple Hello World Structure
#include <stdio.h>
int main() {
printf("Hello world\n");
return 0;
}
Output
Hello world
Here the code starts with the include <stdio.h> which includes the standard input/output header file that provides the printf function. We use int main as the return type and the printf function to print the words inside the double quotes. '\n' means move to new line and we give a return value 0 which tells the OS that the program ran successfully.