0% found this document useful (0 votes)
6 views33 pages

C Programming Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views33 pages

C Programming Notes

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C Programming

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.

Install IDE for C Programming:


An IDE (Integrated Development Environment) is used to edit & compile the code.
Direct download link for code blocks.
[Link]
[Link]/download

All C program files are saved using .c extensions.

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.

Header file in C Programming:

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.

ctype.h – Character Handling


Function Purpose

isalnum(c) Checks if alphanumeric (A–Z, a–z, 0–9)

isalpha(c) Checks if alphabetic

isdigit(c) Checks if digit (0–9)

islower(c) Checks if lowercase letter

isupper(c) Checks if uppercase letter

tolower(c) Converts to lowercase

toupper(c) Converts to uppercase

COMPILED BY SOUMICK ADHIKARY 1


stdio.h – Standard Input/Output
Function Purpose

printf() Print formatted output to stdout

scanf() Read formatted input

fprintf() Print formatted output to file

fscanf() Read formatted input from file

vprintf() etc. Variadic versions of printf/scanf

getchar() Get a character from stdin

putchar() Write a character to stdout

gets() Deprecated – use fgets()

puts() Write a string with newline

fopen() Open file

fclose() Close file

fread() Read block of data from file

fwrite() Write block of data to file

fgetc() Get character from file

fputc() Write character to file

fgets() Read string from file

fputs() Write string to file

remove() Delete file

rename() Rename file

stdlib.h – General Utilities


Function Purpose

malloc() Allocate memory

calloc() Allocate and zero-initialize memory

free() Free allocated memory

abs() Absolute value (int)

div() Division with quotient & remainder (int)

COMPILED BY SOUMICK ADHIKARY 2


math.h
Function Syntax

sqrt(x) double sqrt(double x)

cbrt(x) double cbrt(double x)

pow(x, y) double pow(double x, double y)

hypot(x, y) double hypot(double x, double y)

ceil(x) Rounds up

floor(x) Rounds down

round(x) Rounds to nearest integer

trunc(x) Removes decimal part

A computer program is a list of "instructions" to be "executed" by a computer. In a programming language,


these programming instructions are called statements. It is important that you end the statement with a
semicolon;

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

COMPILED BY SOUMICK ADHIKARY 3


Program Execution Steps:

Source Code(.c)

Compiler -----→ (.s file)

Assembly Code

Assembler

Object File (.o file)

Libraries
Linker

Executable file (.exe)

COMPILED BY SOUMICK ADHIKARY 4


Identifiers in C Programming:

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.

Rules for Naming Identifiers in C:

A programmer must follow a set of rules to create an identifier in C:

• Identifier can contain following characters:

o Uppercase (A-Z) and lowercase (a-z) alphabets.


o Numeric digits (0-9).

o Underscore (_).

• The first character of an identifier must be a letter or an underscore.

• Identifiers are case-sensitive.


• Identifiers cannot be keywords in C (such as int, return, if, while etc.).

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:

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

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;

Rules of naming a variable are same as that of an identifier.


Datatypes in C Programming:

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:

type variableName = value;

int x = 10;
or
float f = 10.52;
or
char ch = ‘A’;

Type conversion in C Programming:

To convert the value of one datatype to another type is known as type conversion. There are two types of
conversion in C:

• Implicit Conversion (automatically)

• Explicit Conversion (manually)

Implicit Type Conversion:

• Done automatically by the compiler without programmer intervention.


• Happens when a smaller data type is assigned to a larger data type (e.g., int to float).

• Occurs in arithmetic operations involving different data types to make them compatible.

COMPILED BY SOUMICK ADHIKARY 6


• Helps prevent data loss and ensure correct calculations.

Example:

#include <stdio.h>

int main() {
int n1 = 5;
float n2 = 4.5;

// Implicit type conversion from int to


float
float result = n1 + n2;

printf("%.2f\n", result);
return 0;
}

Explicit Type Conversion:

• Explicit type conversion is when the programmer manually converts a variable from one data type to
another.

• It is done using a type cast operator (type) before the value.


• Used to force conversion when automatic (implicit) conversion doesn’t happen or isn’t desired.

• 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;
}

COMPILED BY SOUMICK ADHIKARY 7


Practice Programs:

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:

Operators divide the operators into the following groups:

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators

Arithmetic Operators

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

++ Increment Increases the value of a variable by 1


X++ or ++x

-- Decrement Decreases the value of a variable by 1


x-- or --x

Comparison operators

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

COMPILED BY SOUMICK ADHIKARY 8


Logical Operators

&& And Returns True if both statements are true x < 5 && x < 10

|| Or Returns True if one of the statements is true x < 5 || x < 4

! Not Reverse the result, returns False if the result is true ! (x < 5 and x < 10)

Assignment Operators

Operator Example Same As

= 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

COMPILED BY SOUMICK ADHIKARY 9


Conditional Statements in C Programming:

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");
}
}

COMPILED BY SOUMICK ADHIKARY 10


2. if … else statement
the if block of statements is executed when the given condition/conditions are true and else block of
statements are executed when the given condition/conditions are false.
#include <stdio.h>

int main() {
int age = 10;

if (age >= 18) {


printf("Eligible for vote");
}
else {
printf("Not Eligible for vote");
}
return 0;
}

3. nested if … else statement


A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if
statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we
can place an if statement inside another if statement.

#include <stdio.h>

int main(){
int age = 11;

if (age >= 18) {


if (age >= 60)
printf("Eligible to vote (Senior Citizen)\n");
else
printf("Eligible for vote\n");
}
else {
printf("Not eligible to vote (Under 18)\n");
if (age >= 13)
printf("teenager\n");
else
printf("not a teenager\n");
}

return 0;
}

COMPILED BY SOUMICK ADHIKARY 11


4. switch … case statement
Instead of writing many if ... else statements, you can use the switch statement. The switch statement selects
one of many code blocks to be executed. The switch block consists of cases to be executed based on the
value of the switch variable.
#include <stdio.h>

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.

Ternary Operator (?):

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;

COMPILED BY SOUMICK ADHIKARY 12


#include <stdio.h>

int main() {
int a = 10, b = 20;
int max;

max = (a > b) ? a : b;

printf("Maximum = %d", max);


return 0;
}

Practice programs:

1. WAP to find larger of two number given by user.


2. WAP to input marks of 3 subject. Find the average. Display ‘pass’ if average is >= 40 else display ‘fail’.
3. WAP to input a number, check and display if it is even or odd.
4. WAP to calculate electric bill base of the below table
Units Rate / unit
>0 && <=100 Rs. 1.50
>100 && <=250 Rs. 1.75
>250 && <=500 Rs. 2.25
>500 Rs. 2.50
5. WAP to input a number and check if it is divisible by 5 & 7.
6. WAP to input 3 angles of a triangle and display the type of Triangle.
7. WAP to input a character and display if it is vowel or not.
8. WAP to calculate the roots of a quadratic equation.
9. WAP to input a character and display of it is alphabet, digit or a special character.
10. Write a menu-driven (switch case) program to perform 1. Addition 2. Subtraction 3. Multiplication 4.
Division depending on user choice.
11. WAP to check if a given year is a leap year or not.
12. WAP to input the X and Y coordinates and display in which quadrants they lie.

COMPILED BY SOUMICK ADHIKARY 13


Loop Statement in C Programming:

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.

COMPILED BY SOUMICK ADHIKARY 14


3. Do … while loop

Syntax:
initialization;
do {
statements;
increment/decrement;
} while(condition);

For loop vs While loop

COMPILED BY SOUMICK ADHIKARY 15


While loop vs Do-While Loop

Break and Continue Statements:

Break:

The break statement is used to immediately terminate a loop or switch statement and transfer control to the
statement after the loop.

It is mainly used to:

• Stop a loop early

• Exit from switch case

• Avoid unnecessary iterations

COMPILED BY SOUMICK ADHIKARY 16


Example:

#include <stdio.h> 1234


int main() {
int i;
for(i = 1; i <= 10; i++) {
if(i == 5) {
break; // Loop stops here
}
printf("%d ", i);
}
return 0;
}
As soon as i becomes 5, the loop terminates completely.

Continue:

The continue statement is used to skip the current iteration of a loop and move directly to the next iteration.

It does not stop the loop, only skips one step.


Example:

#include <stdio.h> 1245


int main() {
int i;
for(i = 1; i <= 5; i++) {
if(i == 3) {
continue; // Skip this iteration
}
printf("%d ", i);
}
return 0;
}
When i = 3, printing is skipped, but the loop continues.

Practice Programs

1. WAP to display first 10 natural number.


2. WAP to display all even numbers between 1 and N, where N is given by users.
3. WAP display Fibonacci series up to N-terms. 0 1 1 2 3 5 8 13 … N-terms
4. WAP to display the following series:
1. 1 -2 3 -4 5 -6 … N
2. 1 11 111 1111 … N
3. 0 1 4 9 16 … 100
4. 1 3 5 7 9 … 30
5. WAP to find sum of all natural numbers till N given by user.

COMPILED BY SOUMICK ADHIKARY 17


6. WAP to find factorial of a number given by user.
7. WAP to find sum of the below series:
Sum = x + x/2 + x/3 + … +x/n
8. WAP to display the following patterns:
1. 1
12
123
1234
12345

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.

COMPILED BY SOUMICK ADHIKARY 18


Array in C Programming:

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.

int arr[5] = {111,22,33,44,55};

or,

int arr[] = {11,22,33,44,55};

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.

COMPILED BY SOUMICK ADHIKARY 19


#include <stdio.h>

int main() {
int arr[5] = {2, 4, 8, 12, 16};

// Print each element of array using loop or Traversal


printf("Printing Array Elements\n");
for(int i = 0; i < 5; i++){
printf("%d ", arr[i]);
}
printf("\n");

// Printing array element in reverse


printf("Printing Array Elements in Reverse\n");
for(int i = 4; i>=0; i--){
printf("%d ", arr[i]);
}

return 0;
}

Practice Programs

1. WAP to find sum and average of all array elements.


2. WAP to find sum of all even and odd elements in an array.
3. WAP to find the largest element in the array.
4. WAP to display index of a search element given by user using linear search technique.
5. WAP to display index of a search element given by user using binary search technique.
6. WAP to sort an array using bubble sort techniques.
7. WAP to sort an array using selection sort techniques.
8. WAP to insert an element at an index given by user.
Ex.
Arr = [11, 22, 44, 55] //before insertion
Insert 33 at index 2
Arr = [11, 22, 33, 44, 55] //after insertion
9. WAP to reverse the elements of an array using swapping technique.
10. WAP to find the second largest element of an array.

Note

int arr[] = {11,22,33,44,55,66,77};


int n = sizeof(arr) / sizeof(arr[0]); //size of the array will be 7(size of arr is 28bytes / size of arr[0] is 4bytes)

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.

COMPILED BY SOUMICK ADHIKARY 20


String in C Programming:

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
“..”

char str[] = “Hello”;

str = ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’


indexes → 0 1 2 3 4 5

Format specifier for string is %s

String Functions

Function Purpose

strlen() Finds length

strcpy() Copies string

strcat() Appends string

strcmp() Compares strings

strrev() Reverses string

strupr() Converts to uppercase

strlwr() Converts to lowercase

strchr() Finds first character

strrchr() Finds last character

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.

Multidimensional or 2D Array in C Programming:


A multidimensional array is basically an array of arrays. We can visualize a two-dimensional array as one-
dimensional arrays stacked vertically forming a table with 'm' rows and 'n' columns. Arrays are 0-indexed, so
the row number ranges from 0 to (m-1) and the column number ranges from 0 to (n-1).

Syntax

The general form of declaring 2-dimensional arrays is shown below:

type arrName[row_size][column_size];
int arr[10][5];

The array int arr[10][5] can store total of (10*5) = 50 elements.

COMPILED BY SOUMICK ADHIKARY 22


Initializing 2-D array

int arr[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};

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.

#include <stdio.h> Element [0][0] : 0


Element [0][1] : 1
int main() { Element [0][2] : 2
int arr[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}; Element [0][3] : 3
Element [1][0] : 4
for(int i = 0; i < 3; i++){ Element [1][1] : 5
for(int j = 0; j < 4; j++){ Element [1][2] : 6
printf(“Element [%d][%d] : %d \n”, i, j, arr[i][j]); Element [1][3] : 7
} Element [2][0] : 8
} Element [2][1] : 9
return 0; Element [2][2] : 10
} Element [2][3] : 11

Passing 2-D array to a function

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:

#include <stdio.h> The matrix is:


11 22 33
void print_array(int arr[3][3], int n, int m) { 44 55 66
int i,j; 77 88 99
printf("The matrix is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int arr[3][3] = {{11, 22, 33},
{44, 55, 66},
{77, 88, 99}};
print_array(arr, 3, 3); //passing array_name and size of row & column

return 0;
}
COMPILED BY SOUMICK ADHIKARY 23
Practice Programs

1. WAP to create a 2D array from user input and display it.


2. WAP create a 2D array from user input. Transpose the matrix and display.
3. WAP to perform matrix multiplication of two 2D arrays.
4. WAP to find sum of all elements of left diagonal and right diagonal of a matrix.
5. WAP to find sum of each row in a 2D array.

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.

• On a 32-bit system, all pointers typically occupy 4 bytes.

• On a 64-bit system, all pointers typically occupy 8 bytes.

Advantages of Pointers

Following are the major advantages of pointers in C:

• Pointers are used for dynamic memory allocation and deallocation.


• An Array or a structure can be accessed efficiently with pointers

• Pointers are useful for accessing memory locations.

• 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;
}

COMPILED BY SOUMICK ADHIKARY 24


#include<stdio.h> 10 6487580 6487580 6487568 6487568 6487560
int main(){
int i = 10; 10 10 10 10
int *j;
int **k;

j = &i;
k = &j;

printf("%u %u %u %u %u %u",i, j, *k, &j, k, &k);

printf("\n\n%d %d %d %d",i, *(&i), *j, **k);

return 0;
}

Issues with Pointers

Pointers are vulnerable to errors and have following disadvantages:

• Memory corruption can occur if an incorrect value is provided to pointers.

• Pointers are a little bit complex to understand.

• Pointers are majorly responsible for memory leaks in C.

• Accessing using pointers are comparatively slower than variables in C.

• Uninitialized pointers might cause a segmentation fault.

Call by value vs Call by reference:

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

• Only values are passed.


• Original variable remains unchanged.
• More secure (data cannot be modified accidentally).
• Requires separate memory for parameters.

COMPILED BY SOUMICK ADHIKARY 25


#include<stdio.h>
int main(){ Before Swap-Outside Function:
int a = 10, b = 20; a = 10 b = 20
After Swap-Inside Function:
printf("\nBefore Swap-Outside Function:\n"); a = 20 b = 10
printf("a = % d \t b = %d",a,b); After Swap-Outside Function:
a = 10 b = 20
swap(a,b);

printf("\nAfter Swap-Outside Function:\n");


printf("a = % d \t b = %d",a,b);

return 0;
}
void swap(int a, int b){
int temp;

temp = a;
a = b;
b = temp;

printf("\nAfter Swap-Inside Function:\n");


printf("a = % d \t b = %d",a,b);
}

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.

• Original variable gets modified.

• Uses pointers.

• No extra memory for copies.

COMPILED BY SOUMICK ADHIKARY 26


// Call by Reference
#include<stdio.h> Before Swap-Outside Function:
int main(){ a = 10 b = 20
int a = 10, b = 20; After Swap-Inside Function:
a = 20 b = 10
printf("\nBefore Swap-Outside Function:\n"); After Swap-Outside Function:
printf("a = % d \t b = %d",a,b); a = 20 b = 10

swap(&a,&b);

printf("\nAfter Swap-Outside Function:\n");


printf("a = % d \t b = %d",a,b);

return 0;
}
void swap(int* a, int* b){
int temp;

temp = *a;
*a = *b;
*b = temp;

printf("\nAfter Swap-Inside Function:\n");


printf("a = % d \t b = %d",*a,*b);
}

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

ptr = (data_type*) malloc(size_in_bytes);


//Malloc() Enter no of Elements:
5
#include<stdio.h> Enter Element 1:1
#include<stdlib.h> Enter Element 2:2
int main(){ Enter Element 3:3
int* ptr; Enter Element 4:6
int n, max, i; Enter Element 5:5
The Elements are:
printf("\nEnter no of Elements:\n"); 12365
scanf("%d", &n);

COMPILED BY SOUMICK ADHIKARY 27


ptr = (int*)malloc(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");
for(i = 0; i < n; i++){
printf("%d ",ptr[i]);
}
free(ptr);
return 0;
}

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 = (data_type*) calloc(n, size);

//Calloc() Enter no of Elements:


5
#include<stdio.h> Enter Element 1:1
#include<stdlib.h> Enter Element 2:2
int main(){ Enter Element 3:3
int* ptr; Enter Element 4:4
int n, max, i; Enter Element 5:6
The Elements are:
printf("\nEnter no of Elements:\n"); 12346
scanf("%d", &n);

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;
}

COMPILED BY SOUMICK ADHIKARY 29


Structure in C Programming:

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.

#include <stdio.h> My number: TVS


My letter: 2020
// Create a structure called myBike
struct myBike {
char brand[50];
int year;
};

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;
}

COMPILED BY SOUMICK ADHIKARY 30


We can use pointers with structs to make our code more efficient, especially when passing structs to functions
or changing their values. To use a pointer to a struct, just add the (*) symbol.

To access its members, you must use the -> operator instead of the dot (.)

#include <stdio.h> My number: TVS


My letter: 2020
// Create a structure called myStructure
struct myBike {
char brand[50];
int year;
};

int main() {
// Create a structure variable of myStructure called
s1
struct myBike B1 = {"TVS",2020};

struct myBike *ptr = &B1;

// Print values
printf("My number: %s\n", ptr->brand);
printf("My letter: %d\n", ptr->year);

return 0;
}

Passing Struct Pointers to Functions

#include <stdio.h> My number: TVS


// Create a structure called myStructure My letter: 2020
struct myBike {
char brand[50];
int year;
};
void updateYear(struct myBike *B) {
B->year = 2025; // Change the year
}
int main() {
// Create a structure variable of myStructure called
s1
struct myBike B1 = {"TVS",2020};
struct myBike *ptr = &B1;

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.

#include <stdio.h> BMW 1999


Ford 1969
// Without typedef:
struct Car {
char brand[30];
int year;
};

// 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

printf("%s %d\n", [Link], [Link]);


printf("%s %d\n", [Link], [Link]);
return 0;
}

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.

• Structure packing forces the compiler to store members without gaps.

COMPILED BY SOUMICK ADHIKARY 32


File Handling in C Programming:

COMPILED BY SOUMICK ADHIKARY 33

You might also like