Dsa M1
Dsa M1
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify, document, and
understand in a particular format. C program must follow the below-mentioned outline in order to
successfully compile and execute. Debugging is easier in a well-structured C program.
There are 6 basic sections responsible for the proper execution of a program. Sections are mentioned below:
Documentation
Preprocessor Section
Definition
Global Declaration
Main() Function
Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and the creation date and
time of the program. It is specified at the start of the program in the form of comments. Documentation can
be represented as:
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program. Header files
help us to access other’s improved code into our code. A copy of these multiple files is inserted into our
program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation. There are
multiple steps which are involved in the writing and execution of the program. Preprocessor directives start
with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables. Variables
and functions which are declared in this scope can be used anywhere in the program.
Example:
Example:
void main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted to the
called function whenever they are called from the main or outside the main() function. These are specified as
per the requirements of the programmer.
Example:
return x+y;
CONTROL STATEMENTS
C language allows you to manipulate the flow of program control by using various control
statements.These control statements are categorized into the following types:
1. Decision making statements Decide which actions are to be performed.
2. Looping statements Decide how many times an action is to be performed.
One of the significant differences between decision making and looping statements is that the
decisionmaking statements direct the flow of program control from top to bottom without any
iteration; while,looping statements direct the flow of program control from top to bottom, and
then again to the top, inan iterative manner.
A program may contain both decisions making as well as looping statements.
Syntax:
if(expression)
statement 1;
statement 2;
statement n;
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 16
Data Structures using C
Example: Using if statement, write a program to find out if the given number is positive or
negative.
Program : Determine whether given number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()
int num;
clrscr();
printf(“Enter an integer value: “);
scanf(“%d”, &num);
if(num>=0)
If there is only a single statement inside the
printf(“%d is a positive number”,num); if block then the braces are not required
if(num<0) to be added.
2. If else statement: If else statement comprises two sets of instruction, one each with if and
else block. If the given expression statement is true then the if-block instructions are executed.
However, ifthe expression evaluates to a false value, then the if-block instructions are skipped
and the else-block instructions are executed. A program can contain multiple if else statements.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 17
Data Structures using C
Syntax:
if(expression)
statement 1;
statement 2;
statement n;
else
statement 1;
statement 2;
statement n;
Example: Using if else statement, write a program to find out if the given number is positiveor
negative.
Program: Determine whether given number is positive or negative
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 18
Data Structures using C
#include<stdio.h>
#include<conio.h>
void main()
int num;
clrscr();
printf(“Enter an integer value: “);
scanf(“%d”, &num);
if(num>= 0) If-else block
printf(“%d is a positive number”,num);
else
printf(“%d is a negative number”,num);
getch();
Output:
Enter an integer value: 22
22 is a positive number
3. Switch statement: Switch statement is a multi-way selection structure that matches the
given expression or variable value with one of a number of integer values, and upon successful
match branches to the corresponding statement block. A default value is also specified with the
switch statement to take appropriate action in case there is a complete mismatch. Switch
statement can be considered as an alternative to multiple if statements.
Syntax:
switch (expression)
{
case value1:
<statement block>
break;
case value2:
<statement block>
break;
case value3:
<statement block>
break;
.
.
.
default:
<statement block>
}
In the above syntax:
expression is the expression to be matched.
value1, value2, etc., are constants, also known as case labels.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 19
Data Structures using C
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 20
Data Structures using C
Example: Using switch statement, write a program to count the frequency of individual digits
in a number.
Program : To count the frequency of individual digits in a number
#include<stdio.h>
#include <conio.h>
void main()
{
long int num1, num2;
int temp, d1=0, d2=0, d3=0, d4=0, d5=0, d6=0, d7=0, d8=0, d9=0, d0=0;
clrscr();
num2=num1;
while(num1! = 0)
{
temp=num1%10;
switch(temp) /*Switch statement*/
{
case 1:
d1++; /*Counting number of Ones*/break;
case 2:
d2++; /*Counting number of Twos*/break;
case 3:
d3++; /*Counting number of Threes*/break;
case 4:
d4++; /*Counting number of Fours*/break;
case 5:
d5++; /*Counting number of Fives*/break;
case 0:
d0++; /*Counting number of Zeros*/break;
case 6:
d6++; /*Counting number of Sixes*/break;
case 7:
d7++; /*Counting number of Sevens*/break;
case 8:
d8++; /*Counting number of Eights*/break;
Case 9:
d9++; /*Counting number of Nines*/break;
default:
/*Do-nothing*/
}
num1=num1/10;
}
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 21
Data Structures using C
getch( );
}
Output:
Enter the number: 889653442
Note The break statement is inserted with each case block so that the control exits from the
case
blocks will be sequentially validated.
2. Looping Statements
C language supports the following looping statements:
1. While
2. Do-While
3. For
1. While loop is used for repetitively executing a set of instructions until the specified condition
is true. As soon as the condition becomes false, the control is automatically transferred out of the
loop. Awhile loop can be considered as an equivalent of a repetitive set of if statements.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 22
Data Structures using C
Syntax:
while (expression)
statement 1;
statement 2;
statement n;
void main()
temp=num;
/*Calculating sum of digits*/
while(temp!=0)
If there are multiple statements inside the
sum = sum+temp%10; while block then the same must be
included inside braces; otherwise only
temp=temp/10; the immediate statement after the while
statement will be considered.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 23
Data Structures using C
2. Do-While Loop:
Similar to the while loop, the do-while loop is also used for repetitively executing a set of
instructions until the specified condition is true. The difference between while loop and do-while
loop is that in while loop the conditional expression is evaluated first and if it is true, the
associated statement block is executed. However, in do-while loop the statement block is
executed first and thenthe conditional expression is evaluated. If the expression evaluates to a
true value, then the statement block is executed again; else the control is transferred out of the
do-while loop. Hence, in case of do- while loop, the statement block is executed at least once even
if the conditional expression evaluates to a false value at its very first attempt. This is in contrast
to the while statement which executes the statement block if and only if the conditional
expression is true.
Syntax
do
statement 1;
statement 2;
statement n;
}while(expression);
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 24
Data Structures using C
Example: Using do-while loop, write a program to compute the sum of digits of a number.
Program: Sum of digits of a number
#include <stdio.h>
#include <conio.h>
void main()
temp=num;
/*Calculating sum of digits*/
do
Output:
Enter an integer value: 123456
The sum of digits of 123456 is 21
3. For Loop:
The functionality of for loop is exactly the same as while loop, however its specificationis a little
different. It includes the initialization statement, conditional expression and the modifier
statement of the loop inside a single one-line for statement. At the end of each iteration, the
value of the variable is updated as per the modifier expression and the condition is again
evaluated. This processcontinues until the conditional expression holds true. The for loop is more
compact and easier to implementin comparison to while loop.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 25
Data Structures using C
Syntax:
statement 1;
statement 2;
statement n;
Example : Using for loop, write a program to print integers from 1 to 10.
Program: To print integers from 1 to 10
#include <stdio.h>
#include <conio.h>
void main()
int i;
clrscr();
printf(“Integers from 1 to 10:\n”);
printf(“%d\n”,i)
The initialization statement, conditional
getch(); expression, and modifier expression are
separated by semi-colons.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 26
Data Structures using C
ARRAYS
Array is a linear data structure that groups elements of similar types and stores them at
contiguous memory locations. The concept of arrays can be easily related with real-life scenarios.
For example, percentage marks of 50 students, salary amounts of 100 employees and names of
books present in a library are all examples of arrays.
Each element in an array is assigned an index number called array subscript. It is used to
identify the location of element in the array. In C language, the index number of the base element
(first element)of an array starts with 0. Therefore, the location of the last element of an array
containing n elements is always n-1. An array is referred using the array name defined at the time
of array declaration. Each individual array element is referred using array name and index
number.
Let us consider an array A containing four elements. Figure below shows the logical
representation ofarray A:
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 27
Data Structures using C
initialize an array either at the time of its declaration or initialize it later in the program with the
help of assignment operator.
The subsequent sections explain the declaration and initialization of single and multi-
dimensional arrays along with related syntax and examples.
1 .Single/Dimensional Array
Array Declaration:
Syntax:
<data-type> <array_name>[size];
Example:
int A[10];
Array Initialization:
Syntax:
<data-type> <array_name>[size] = {element1, element2, ….., elementn};
<array_name>[index_number] = <element>;
Example:
int A[3]={2,4,8};
A[0]=2;
Array Representation
Figure below shows the logical representation of single-dimensional array.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 28
Data Structures using C
#include <stdio.h>
#include <conio.h>
void main()
clrscr();
sum=0;
for(i=0;i<=9;i++)
sum=sum+a[i];
ave=1.0*sum/10;
2.Multi/Dimensional Array
Array Declaration:
Syntax:
Array Initialization:
Syntax:
<array_name> [row-index_number][column-index_number] = <element>;
<data-type> <array_name>[row-subscript][column-subscript] =
{element1, element2, ….., elementn};
Example:
A[1][0]=3;
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 29
Data Structures using C
Array Representation
Figure below shows the logical representation of multi-dimensional array.
#include <stdio.h>
#include <conio.h>
void main()
int i,j,M[2][2];
printf(“M[%d][%d] = “, i, j);
the inner loop signifies matrix columns.
scanf(“%d”,& M[i][j]);
printf(“\n\t\t “);
for(j=0; j<2; j++)
printf(“%d “, M[i][j]);
getch();
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 30
Data Structures using C
3. STRINGS
C supports the concept of strings to store a string of characters. Strings are nothing but character
arrays that store the string characters at contiguous memory locations with a null character
stored at the last location to indicate the end of the string.
The syntax and example of string declaration and initialization is shown below:
Syntax:
<data_type> <string_name>[size]=”string_characters”;
Example:
char str[10]=”hello”;
C supports a number of built-in functions that make it easier to work with strings. Table
below lists these string-based functions:
String functions:
Type Function
Input/output string functions gets( ) Receives a character string from the console.
Example:
char str[50]; gets(str);
puts( ) Prints the string data on the console.
Example:
char str[50]; gets(str); puts(str);
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 31
Data Structures using C
%s”,str,revstr);getch();
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 32
Data Structures using C
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 37
Data Structures using C
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 38
Data Structures using C
7. STRUCTURES
Structures are used to group together data of different types inside a single unit. It removes one
of the key limitations of arrays which can only store data elements with similar types. Thus,
structures can be easily used in situations where data elements with distinct types are required
to be stored as a singleentity; for example, a student record containing data elements such as
name, roll no, marks, etc.
Before a structure can be used in a program, it needs to be first declared and initialized. The
subsequent sections explain the declaration and initialization of a structure along with the
method of accessing itsdata members.
Structure Declaration
Syntax:
struct <structure_name>
<data_type> member1;
<data_type> member2;
<data_type> membern;
}var1;
struct <structure_name> var2;
Example:
struct book
Char title[20];
Char author[15];
}book1;
struct book book2;
Structure Initialization:
Syntax
structure_variable1.member1=value;
structure_variable2.member2= value;
Example:
book.title = “Data Structures”;
book.pages = 450;
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 39
Data Structures using C
Example :Write a program that uses a simple structure to store students’ details.
Program:To store students’ details
#include <stdio.h>
#include <conio.h>
void main ()
/*Structure Declaration*/
struct student
char name[30];
int rollno;
int t_marks;
};
scanf(“%d”,&num);
for(i=0;i<num;i++)
printf(“\n student %d \n Name %s \n Roll No. %d \n Total Marks %d\n”,i+1,std[i].name,
std[i].rollno, std[i].t_marks);
getch();
}
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 40
Data Structures using C
void main()
getch();
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 41
Data Structures using C
8. UNIONS
Like structures, unions also allow us to group together dissimilar type elements inside a single
unit. But there is a significant difference between structures and unions in the way they are
implemented in the system. The size of a structure is equal to the sum of the sizes of its
constituent members. In contrast, the size of a union is equal to the size of its largest sized
element. This is because unions allow only one member to be utilized at any given point of time.
That is, union members can only be manipulated exclusive of each other.
Syntax:
union <union_name>
type1 var1;
type2 var2;
typen varn;
};
Example:
union result
{
int marks;
char grade;
float percent;
};
Unions are particularly useful in situations where it is not required to simultaneously access
the data members. In such situations, unions prove to be memory efficient in comparison to
structures.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 42
Data Structures using C
Int roll_no;
char result;
}st1,st2;
printf(“\n\n”);
/*Accessing and printing the values incorrectly*/
printf(“\nRoll NO: %d”,st2.roll_no);
printf(“\nResult: %c”,st1.result);
getch();
Structures Unions
It is defined with ‘struct’ keyword. It is defined with ‘union’ keyword.
All members of a structure can be utilized Only one member of a union can be utilized at
simultaneously. anygiven point of time.
The size of a structure is equal to the sum of the The size of a union is equal to the size of its
sizesof its members. largestmember.
Structure members are stored at discrete locations All the union members share common memory
inmemory. space.
Structures are not considered as memory efficient Unions are considered as memory efficient in
incomparison to unions. situationswhere the members are not required to
be accessed simultaneously.
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 43
Data Structures using C
POINTERS
Pointer is a derived data type that stores memory addresses as its value. It points or indicates the
location where another variable is stored. Pointers are particularly used for dynamic memory
management. Figure below shows the logical representation of a pointer:
int num=10;
int *ptr; /*Pointer declaration*/
ptr=# /*Pointer initialization*/
In the above code, the address of num variable is allocated to pointer variable ptr. Whenever
* is preceded with a variable name, it refers to the value stored at the location being pointed by the
variable.On the other hand, whenever & is preceded with a variable name, it refers to the memory
address of the variable.
Like any other variable, pointer variables can also be used in expressions to form pointer expressions.
This is depicted below:
a = *b +*c;
z = z + *y;
*c = *ptr+5;
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 44
Data Structures using C
Example: Using the concept of pointers, write a program to print the address and value of a
variable.
Program: To print address and value of a variable
#include<stdio.h>
#include<conio.h>
void main()
int a;
int *ptr; /*Declaring pointer variable*/
clrscr();
a=50;
ptr=&a; /*Pointer allocation*/
Prof. Shyam Sundar V, Dept. of ECE Cambridge Institute of Technology, Bangalore-36 Page 45
8/8/23, 7:43 PM Swapping numbers using Call by Value in C - Forget Code
Choose Category
Output:
Before Swapping
x = 10
y=5
https://forgetcode.com/c/1957-swapping-numbers-using-call-by-value 2/3
8/8/23, 7:43 PM Swapping numbers using Call by Value in C - Forget Code
Output:
Values of a and b is 5 10
After Swapping
x = 10
y=5
https://forgetcode.com/c/1957-swapping-numbers-using-call-by-value 3/3