C Programming Notes
C Programming Notes
C is a general-purpose programming language that has been widely used for years. C is very powerful; it has
been used to develop operating systems (like Unix), databases, applications, etc.
Eg. myfirstprogram.c
#include <stdio.h>
int main() {
printf("Hello World!");
return 0;
}
Syntax : Syntax refers to the fundamental rules that govern how code is written in a programming language,
dictating the correct structure, grammar, and formatting of instructions.
A header file is a file with extension .h which contains C function declarations and macro definitions to be
shared between several source files. All lines that start with # are processed by a preprocessor which is a
program invoked by the compiler.
ceil(x) Rounds up
Comments in C Programming:
• Single-line comments start with two forward slashes (//). Any text between // and the end of the line is
ignored by the compiler (will not be executed).
• Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by the
compiler
Source Code(.c)
Assembly Code
Assembler
Libraries
Linker
Identifiers are the names used to identify variables, functions, arrays, structures, or any other user-defined items.
It is a name that uniquely identifies a program element and can be used to refer to it later in the program.
o Underscore (_).
Keywords in C Programming:
Keywords are predefined or reserved words that have special meanings to the compiler. These are part of the
syntax and cannot be used as identifiers in the program. A list of keywords in C or reserved words in the C
programming language is mentioned below:
We cannot use these keywords as identifiers (such as variable names, function names, or struct names). The
compiler will throw an error if we try to do so.
Variables in C Programming:
Variables are named memory locations used for storing data values, like numbers and characters. It is also
called an identifier.
Syntax:
type variableName = value;
Each variable in C has an associated data type. It specifies the type of data that the variable can store like
integer, character, floating, double, etc.
COMPILED BY SOUMICK ADHIKARY 5
Declaring a variable:
type variableName;
int x;
or float f;
or
char ch;
Initializing a variable:
int x = 10;
or
float f = 10.52;
or
char ch = ‘A’;
To convert the value of one datatype to another type is known as type conversion. There are two types of
conversion in C:
• Occurs in arithmetic operations involving different data types to make them compatible.
Example:
#include <stdio.h>
int main() {
int n1 = 5;
float n2 = 4.5;
printf("%.2f\n", result);
return 0;
}
• Explicit type conversion is when the programmer manually converts a variable from one data type to
another.
• Can convert larger types to smaller types or smaller types to larger types, but converting to smaller types
may cause data loss or truncation.
Example:
#include <stdio.h>
int main()
{
float n1 = 7.9;
int n2;
// Explicit type conversion (casting)
from float to int
n2 = (int)n1;
printf("%d", n2);
return 0;
}
1. WAP to add, subtract, multiply and divide two numbers given by user.
2. WAP to find area and perimeter of a circle.
3. WAP to find average of 3 numbers.
4. WAP to input base and height and display the area of the triangle.
5. WAP area and perimeter of a rectangle taking length and width from user.
6. WAP to display square and cube of a number given by user.
Operators in C Programming:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
Arithmetic Operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
Comparison operators
== Equal x == y
!= Not equal x != y
&& And Returns True if both statements are true x < 5 && x < 10
! Not Reverse the result, returns False if the result is true ! (x < 5 and x < 10)
Assignment Operators
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
Operator Precedence
When a calculation contains more than one operator, C follows order of operations rules to decide which part to
calculate first.
Order of Operations
Here are some common operators in C, from highest to lowest priority:
1. () → Parentheses
2. *, /, % → Multiplication, Division, Modulus
3. +, - → Addition, Subtraction
4. >, <, >=, <= → Comparison
5. ==, != → Equality
6. && → Logical AND
7. || → Logical OR
8. = → Assignment
1. if statement
It is the simplest decision-making statement. It is used to decide whether a certain statement or block of
statements will be executed or not i.e if a certain condition is true then a block of statements is executed
otherwise not.
#include <stdio.h>
int main() {
int age = 20;
// If statement
if (age >= 18) {
printf("Eligible for vote");
}
}
int main() {
int age = 10;
#include <stdio.h>
int main(){
int age = 11;
return 0;
}
int main() {
// variable to be used in switch statement
int ch = 18;
// declaring switch cases
switch (var) {
case 15:
printf("You are a kid");
break;
case 18:
printf("Eligible for vote");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}
• The break statement breaks out of the switch block and stops the execution. This will stop the execution
of more code and case testing inside the switch block.
• The default statement is optional and specifies some code to run if there is no case match.
The ternary operator is a conditional operator that works as a short form of if–else. It is called ternary because it
uses three operands.
Syntax:
condition ? expression_if_true : expression_if_false;
int main() {
int a = 10, b = 20;
int max;
max = (a > b) ? a : b;
Practice programs:
Loops in C programming are used to repeat a block of code until the specified condition is met. It allows
programmers to execute a statement or group of statements multiple times without writing the code again and
again.
1. For loop
Syntax:
for(initialization; condition; increment/decrement) {
statements;
}
• Initialization → executes once
• Condition → checked every time
• Body → runs if condition is true
• Increment/Decrement
2. While loop
Syntax:
initialization;
while(condition) {
statements;
increment/decrement;
}
Condition is checked before entering the loop.
Syntax:
initialization;
do {
statements;
increment/decrement;
} while(condition);
Break:
The break statement is used to immediately terminate a loop or switch statement and transfer control to the
statement after the loop.
Continue:
The continue statement is used to skip the current iteration of a loop and move directly to the next iteration.
Practice Programs
2. 5 4 3 2 1
5432
543
54
5
3. 1
121
12321
9. WAP to reverse a number using while loop.
10. WAP to check if a number is palindrome number or not.
11. WAP to check if the number is perfect number or not.
12. WAP to check if the number is Armstrong number or not.
An array is a linear data structure that stores a fixed-size sequence of elements of the same data type in
contiguous memory locations. Each element can be accessed directly using its index, which allows for efficient
retrieval and modification. An array is denoted by [] brackets.
In the above image there are 6 elements. Hence the size of the array is 6. But the max index is 5, as indexes are
calculated from 0.
Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In C, we must declare the
array like any other variable before using it.
Syntax:
datatype array_name [size];
int arr[10];
Array Initialization
Array initialization is the process of assigning values to the array during declaration itself.
or,
Array Traversal
Array Traversal is the process in which we visit every element of the array in a specific order. For C array
traversal, we use loops to iterate through each element of the array.
int main() {
int arr[5] = {2, 4, 8, 12, 16};
return 0;
}
Practice Programs
Note
The sizeof() operator returns the size in bytes. sizeof(arr) returns the total number of bytes of the array. In an
array, each element is of type int, which is 4 bytes. Therefore, we can calculate the size of the array by dividing
the total number of bytes by the byte size of one element.
A string is an array of characters terminated by a special character '\0' (null character). This null character marks
the end of the string and is essential for proper string manipulation. Strings are enclosed within double quotes
“..”
String Functions
Function Purpose
String Inputs
• scanf()
It is used for basic string input. It is mostly used for single word input. If multiple words are used, it stops at
the first space encountered.
Syntax
char str[20];
scanf(“%s”,str);
Here if user give “Tony Stark”, only “Tony” will be stored.
• fgets()
It is better to use fgets() method to input string from user. It can take multiple words as input including
spaces. It takes 3 parameters i.e. char array, size of the char array and stdin keyword which means standard
keyboard input.
fgets(str,size,stdin);
COMPILED BY SOUMICK ADHIKARY 21
Syntax
char str[20];
fgets(str,20,stdin);
Here if user give “Tony Stark”, entire “Tony Stark” will be stored.
Practice programs
1. WAP to input a character and display if it is vowel or not.
2. WAP to input a character and display if it is an alphabet, digit or a special character.
3. WAP to input a word and check if it is palindrome or not.
4. WAP to find length of a string without using library function.
5. WAP to count number of words in a sentence given by user.
6. WAP to count frequency of a given character in a word.
7. WAP to input a word and convert all its uppercase character to lowercase and vice versa.
Syntax
type arrName[row_size][column_size];
int arr[10][5];
2D Array Traversal
Traversal means accessing all the elements of the array one by one. We will use two loops, outer loop to go over
each row from top to bottom and the inner loop is used to access each element in the current row from left to
right.
The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D
array with row size and column size. One thing to note is that we always must pass the size of the array's
dimensions separately.
Example:
return 0;
}
COMPILED BY SOUMICK ADHIKARY 23
Practice Programs
Pointer in C Programming:
A pointer is a variable whose value is an address of another variable. Instead of holding a direct value, it holds
the address where the value is stored in memory.
A pointer variable points to a data type (like int) of the same type and is created with the * operator.
Syntax:
data_type *pointer_name;
int *ptr;
Size of Pointers
The size of a pointer in C depends on the architecture (bit system) of the machine, not the data type it points to.
Advantages of Pointers
• Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
• Pointers reduce the length of the program and its execution time as well.
#include<stdio.h> Value of a = 10
int main(){ Value stored at pointer address = 10
int a = 10; Address of a = 6487580
int* p = &a; Address stored by p =6487580
printf("Value of a = %d\n",a); Address of p = 6487568
printf("Value stored at pointer address = %d\n", *p); Size f pointer = 8
printf("Address of a = %u\n",&a);
printf("Address stored by p =%u\n",p);
printf("Address of p = %u\n",&p);
printf("Size f pointer = %d", sizeof(p));
return 0;
}
j = &i;
k = &j;
return 0;
}
Call by value - In call by value, a copy of the actual variable is passed to the function. Any change made
inside the function does NOT affect the original variable.
Key Points
return 0;
}
void swap(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
Call by Reference - In call by reference, the address of the variable is passed to the function using
pointers. So, any change inside the function directly affects the original variable.
Key Points
• Address is passed.
• Uses pointers.
swap(&a,&b);
return 0;
}
void swap(int* a, int* b){
int temp;
temp = *a;
*a = *b;
*b = temp;
malloc() vs calloc()
The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the
memory is allocated during runtime (execution of the program).
malloc() - allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block.
malloc() doesn't initialize the allocated memory which means it will store all garbage values.
After successful allocation in malloc(), a pointer to the block of memory is returned otherwise NULL is
returned which indicates failure.
Syntax
calloc() - allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read
the value of the allocated memory without initializing it, you'll get 0.
After successful allocation in calloc(), a pointer to the block of memory is returned otherwise NULL is returned
which indicates failure.
Syntax
ptr = (int*)calloc(n,sizeof(int));
/*if n is 5 and size of int is 4 then 5*4=20bytes are allocated*/
if(ptr == NULL){
printf("\nMemory allocation Failed");
return 0;
}
for(i = 0; i < n; i++){
printf("Enter Element %d:",(i+1));
scanf("%d", &ptr[i]);
}
printf("The Elements are:\n");
COMPILED BY SOUMICK ADHIKARY 28
for(i = 0; i < n; i++){
printf("%d ",ptr[i]);
}
free(ptr);
return 0;
}
Structures (also called structs) are a way to group several related variables into one place. Each variable in the
structure is known as a member of the structure.
The struct keyword is used to define a structure. The items in the structure are called its members and they can
be of any valid data type.
Syntax
Struct structure_name{
member 1;
member 2
.
.
.
member n;
}
Example:
Simple Example
To access members of struct, use dot(.) operator.
int main() {
// Create a structure variable of myBike called B1
struct myBike B1 = {"TVS",2020};
// Print values
printf("My number: %s\n", [Link]);
printf("My letter: %d\n", [Link]);
return 0;
}
To access its members, you must use the -> operator instead of the dot (.)
int main() {
// Create a structure variable of myStructure called
s1
struct myBike B1 = {"TVS",2020};
// Print values
printf("My number: %s\n", ptr->brand);
printf("My letter: %d\n", ptr->year);
return 0;
}
updateYear(ptr);
// Print values
printf("My number: %s\n", ptr->brand);
printf("My letter: %d\n", ptr->year);
return 0;
}
COMPILED BY SOUMICK ADHIKARY 31
typedef with struct
typedef can be useful with struct, because it lets you avoid writing struct every time.
// With typedef:
typedef struct {
char brand[30];
int year;
} Car;
int main() {
struct Car car1 = {"BMW", 1999}; // needs "struct"
Car car2 = {"Ford", 1969}; // shorter with typedef
It is up to you whether you want to use typedef or not. Your code will work the same without it. However, in
modern C it is often used to make code shorter, clearer, and easier to maintain.
Size of Structures
• At first glance, the size of a structure should be equal to the sum of all its members size but is not always
equal to the sum of its members’ sizes because of structure padding.
• Structure padding means adding extra empty bytes in memory to align data properly.
• Padding helps the CPU access data faster by reducing read cycles.
• Sometimes, we need to remove these extra bytes to save memory — this is called structure packing.