Final DS Workbook
Final DS Workbook
’s
Work-Book
for
Data Structures
Using C
Dear Students,
2. Variables 10-12
3. Operators 13-21
4. Input/Output 22-24
6. Loops 31-34
7. Functions 35-39
8. Structures 40-43
9. Unions 44
3
Books to be referred
Here are some books I personally recommend for exploring
prerequisites C Programming contents,
1. Programming in ANSI C by E. Balguruswamy - Best
book for learning basic of C
2. Let Us C, Yashwant Kanetkar - Leading book for
exploring C programs
3. The Art of Computer Programming, Donald E. Knuth -
Best for deeper understanding of programming
language
4
Platforms for executing C Program
If you have laptop/desktop available, there
are many softwares available. For instance,
you can choose any of the following platform
for executing C program,
1. Code blocks
2. Dev C++
3. Turbo C++
4. GCC
If you do not have laptop/desktop, you can
use following websites/apps that run fine on
smartphones too,
1. Codeboard.io(Website/App)
2. Mobile C/C++ Compiler (App)
3. Online Compiler(App)
4. Jdoodle(Website)
5. Onlinegdb.com(Website)
Happy C Learning!
5
Lesson 1 : Data Types
A programming language cannot work
without a wide range of data types as
each type has its own significance and
utility to perform various
tasks. programming.
7
C Program for
#include <stdio.h>
int main()
{
int number1 = 400;
short int number2 = 500;
illustrating
unsigned short int number3 = 600;
long int number4 = 700; concept of
Data Types
unsigned long int number5 = 800;
unsigned long long int number6 = 900;
char character1 ='A';
signed char character2 ='B';
unsigned char character3 ='C';
float digit1 =20.00;
double digit2 = 3.14159;
long double digit3 = 1.414213;
printf("Welcome to CSE Department!\n\n");
//Print statements to show the size of various data types
printf("The size of int data type %d is: %lu bytes.\n", number1, sizeof(number1));
printf("The size of short int data type %d is: %lu bytes.\n", number2, sizeof(number2));
printf("The size of unsigned short int data type %d is: %lu bytes.\n", number3, sizeof(number3));
printf("The size of long int data type %ld is: %lu bytes.\n", number4, sizeof(number4));
printf("The size of unsigned long int data type %ld is: %lu bytes.\n", number5, sizeof(number5));
printf("The size of unsigned long long int data type %lld is: %lu bytes.\n", number6,
sizeof(number6));
printf("The size of char %c is: %lu byte.\n", character1, sizeof(character1));
printf("The size of signed char %c is: %lu byte.\n", character2, sizeof(character2));
printf("The size of unsigned char %c is: %lu byte.\n", character3, sizeof(character3));
printf("The size of float data type %f is: %ld bytes.\n", digit1, sizeof(digit1));
printf("The size of double data type %lf is: %ld bytes.\n", digit2, sizeof(digit2));
printf("The size of long double data type %Lf is: %ld bytes.\n", digit3, sizeof(digit3));
return 0;
}
Output
8
Check Your Understanding
1. The format identifier ‘%i’ is also used for _____ data type?
A. char
B. int
C. float
D. double
2. What is the size of an int data type?
A. 4 Bytes
B. 8 Bytes
C. Depends on the system/compiler
D. Cannot be determined
3. Which of the following is not a valid declaration in C?
a. short int x;
b. signed short x;
c. short x; Practice Quiz
d. unsigned short x; Link
A. c and d https://tinyurl.
B. b com/48bbmyzp
C. a
D. All are valid
4. When double is converted to float, the value is?
A. Rounded
B. Truncated
C. Depends on the standard
D. Depends on the compiler
5. Which of the following is not a data type?
A. Symbolic data
B. Alphanumeric data
C. Numeric data
D. Alphabetic data 9
Lesson 2 : Variables
A variable is a
name of the Rules for defining variables
memory location. • A variable can have alphabets,
It is used to store
digits, and underscore.
data. Its value can
be changed, and it • A variable name can start with the
can be reused many
alphabet, and underscore only. It
times.
can't start with a digit.
type variable_list;
• No whitespace is allowed within the
int a;
float b; variable name.
char c;
• A variable name must not be any
int a=10,b=20;
float f=20.8;
reserved word or keyword, e.g. int,
char c='A'; float, etc.
10
Local Variable Global Variable
A variable that is declared inside the A variable that is declared outside the
function or block is called a local variable. function or block is called a global
It must be declared at the start of the variable. Any function can change the
block. value of the global variable. It must be
void function1(){ declared at the start of the block.
int x=10;//local variable int value=20;//global variable
} void function1(){
You must have to initialize the local int x=10;//local variable
variable before it is used. }
#include <stdio.h>
Program
int main() for
Arithmetic { Arithmetic
Operators int a = 9,b = 4, c; Operators
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
Operator Meaning of Operator printf("a*b = %d \n",c);
c = a/b;
+ addition or unary plus printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b
- subtraction or unary = %d \n",c);
minus return 0;
* multiplication }
/ division a+b=13
Output of
a-b=5
above
a*b=36 program
% remainder after division
a/b=2
(modulo division) 13
Increment & Decrement Operators
Program
for
• C programming has two #include <stdio.h> Increment/
int main() Decrement
operators increment ++ Operators
{
and decrement -- to change int a = 10, b = 100;
the value of an operand float c = 10.5, d = 100.5; //
(constant or variable) by 1.
printf("++a = %d \n", ++a);
• • Increment ++ increases printf("--b = %d \n", --b);
the value by 1 whereas printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
decrement -- decreases the
value by 1. return 0;
}
++a = 11
--b = 99 Output of
C Assignment above
++c = 11.500000 program
Operators --d = 99.500000
-= multiplication a -= b
*= division a *= b
/= a /= b a = a/b
%= a %= b a = a%b
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
15
Relational Operators
== Equal to 5 == 3 is evaluated to 0
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
18
Check Your Understanding
1. Which of the following operator takes only integer operands?
A. +
B. -
C. *
D. /
E. %
2. What is the output of following code?
#include <stdio.h>
int main()
{
int a = 1;
int b = 1;
int c = a || --b;
int d = a-- && --b;
printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d);
return 0;
}
A. a = 0, b = 1, c = 1, d = 0
B. a = 0, b = 0, c = 1, d = 0
C. a = 1, b = 1, c = 1, d = 1
D. a = 0, b = 0, c = 0, d = 0
19
Check Your Understanding
3.What is the output of following code?
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
}
A. TRUE
B. FALSE
C. Compiler Error
D. Output is compiler dependent
20
Check Your Understanding
5. What will be the output of the following C code?
#include <stdio.h>
int main()
{
int i = 0;
int j = i++ + i;
printf("%d\n", j);
}
A. 0
B. 1
C. 2
D. Compile time error
21
Lesson 4 : Input Output
•When you start dealing with variables in C, you’ll invariably stumble into the
garden of I/O, or input/output. The computer’s primary input device is the
keyboard, and its primary output device is the monitor, and you need to know
how to get C to recognize input and create output.
•Here is a quick summary of the C language text input and output functions that
you can use to help read information from the keyboard and push information to
the screen.
atof() [numvar = ]atof(string); Converts a floating-point
value found in string into a
floating-point number, which
can be stored in a
variable, numvar, or used
immediately. Requires the
STDLIB.H header file to be
included.
atoi() [numvar = atoi](string); Converts an integer value
found in string into an integer,
which can be stored in a
variable, numvar, or used
immediately. Requires the
STDLIB.H header file to be
included.
22
gets() gets(string); Reads a string of text from the
keyboard (terminated by the
Enter key). The text is stored in
the variable string.
printf() printf(“format”[,var[,var…]]) Displays formatted text according to
; the format string. Optional values or
variables,
var, can be specified to match
placeholders or conversion
characters in the format string.
putchar() putchar(ch); Displays the character ch on the
screen, where ch is a single character
(or escape code) in single quotes or
the name of a char
variable.
puts() puts(string); Displays the text string on the
screen, where string is a literal string
of text (enclosed in double quotes)
or the name of a string
variable.
scanf() scanf(“format”,&var); Reads information from the
keyboard according to the
conversion
character in the format string. The
information is then stored in the
variable var, which must match the
type of conversion
character that’s used (int, float,
or char, for
example).
int main() Enter integer and then a float: -3
{
3.4
int a;
You entered -3 and 3.400000
float b;
printf("Enter integer and then a float: ");
// Taking multiple inputs Output
scanf("%d%f", &a, &b);
printf("You entered %d and %f", a, b);
return 0;
}
23
Check Your Understanding
1. Which among the following is the odd one out?
A. Printf
B. Fprintf
C. Putchar
D. scanf
A. -1
B. 0
C. 1
D.10
24
Lesson 5 : Conditional Statements
Conditional Statements in C programming are used to make decisions
based on the conditions. Conditional statements execute sequentially
when there is no condition around the statements. If you put some
condition for a block of statements, the execution flow may change
based on the result evaluated by the condition. This process is called
decision making in 'C.'
C Program for illustrating ‘if’
Output
#include<stdio.h>
int main()
num1 is
{
smaller than
int num1=1;
num2
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}
25
C Program for illustrating concept of if-else
#include<stdio.h>
int main() Output
{ The value is greater than 10
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}
Conditional Expressions
• There is another way to express
an if-else statement is by
introducing the ?: operator.
• In a conditional expression the ?:
operator has only one statement
associated with the if and the else.
#include <stdio.h>
int main()
{
int y; Output
int x = 2; y=2
y = (x >= 6) ? 6 : x;
/* This is equivalent to: if (x >= 5) y = 5; else y = x; */
printf("y =%d ",y);
return 0;
}
26
C Program for illustrating concept of nested if-else
#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
} Output
else The value is:1
{
printf("The value is greater than 10");
}
return 0; }
27
Nested else-if is used when multipath decisions are required.
The general syntax of how else-if ladders are constructed in 'C' programming is
as follows:
if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Output
First class 28
Check Your Understanding
1. Choose C conditional operator from the list
A. ?.
B. :?
C. :<
D. <:
#include<stdio.h>
int main()
{ Practice Quiz
Link
if(-5) https://tinyurl.co
printf("a"); m/4vb8sj8u
printf("b");
else
printf("c");
printf("d");
return 0;
}
A. abd
B. cd
C. Compile time error
D. ab
29
Check Your Understanding
1. Find the output of following code,
#include<stdio.h>
int main()
{
if("true") printf("a");
else printf("b");
return 0;
}
A. error
B. a
C. b
D. ab
30
Lesson 6 : Loops in C
Looping Statements in C execute the
sequence of statements many times
until the stated condition becomes
false.
A loop in C consists of two parts, a
body of a loop and a control
statement. The control statement is a
combination of some conditions that
direct the body of the loop to execute
until the specified condition becomes
false. The purpose of the C loop is to In an entry control loop in C, a condition
repeat the same code a number of is checked before executing the body of a
loop. In an exit-controlled loop, a
times. condition is checked after executing the
body of a loop.
32
Syntax of for Loop in C
for (initial value; condition; incrementation or decrementation )
{
statements;
}
return 0;
}
A. RABBIT
B. RABBIT is printed unlimited number
of times.
C. No output
D. Compiler error.
34
Lesson 7 : Functions in C
A function is a group of
Defining a Function
statements that together
The general form of a function definition in C
perform a task. Every C
programming language is as follows
program has at least one
return_type function_name( parameter list ) {
function, which is main(), and
body of the function
all the most trivial programs
}
can define additional
functions.
Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
Function Body − The function body contains a collection of statements that
define what the function does.
Function Declaration Calling a function
A function declaration tells the compiler A called function performs a
about a function name and how to call the defined task and when its return
function. The actual body of the function can statement is executed or when its
be defined separately. function-ending closing brace is
reached, it returns the program
A function declaration has the following control back to the main program.
parts −
To call a function, you simply
return_type function_name( parameter list ); need to pass the required
parameters along with the
Parameter names are not important in function name, and if the function
function declaration only their type is returns a value, then you can store
required the returned value.
35
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
Output
Max value is : 200 36
Function Arguments
1. Call By Value
2. Call By Reference
Program for Understanding Call By Value Concept
37
Program for Understanding Call By Reference Concept
#include <stdio.h>
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
Output
return;
Before swap, value of a : 100
}
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
38
Check Your Understanding
1. Choose a correct statement about C Function?
void main() {
printf("Hello");
}
A. "main" is the name of default must and should Function
B. main() is same as int main()
C. By default, return 0 is added as the last statement of a function
without specific return type
D. All the above
2. How many times the program will print “DIEMS"?
int main() {
printf(“DIEMS");
main();
return 0;
}
A. Infinite times Practice Quiz
B. 32767 times Link
C. 65535 times https://tinyurl.co
D. Till stack overflows m/3kfn2pkr
3. Determine Output :
void show() {
printf("PISTA “);
show( );
}
void main() {
printf("CACHEW ");
return 10;
}
PISTA CACHEW
CASHEW PISTA
PISTA CASHEW with compiler warning
Compiler error 39
Lesson 8 : C Structures
• Structure is a user-defined datatype in C language which allows us to
combine data of different types together.
• Structure helps to construct a complex data type which is more
meaningful.
• It is somewhat similar to an Array, but an array holds data of similar
type only. But structure on the other hand, can store data of any type,
which is practical more useful.
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
... Here struct Student declares a
}[structure_variables]; structure to hold the details of a
student which consists of 4 data
fields, namely name, age, branch
and gender. These fields are called
struct Student structure elements or members.
{
char name[25];
int age;
char branch[10]; Each member can have different
// F for female and M for male datatype, like in this case, name is
char gender; an array of char type and age is of
}; int type etc.
40
Accessing Structure Members
Structure members can be accessed and assigned values in a number of
ways. Structure members have no meaning individually without the
structure. In order to assign a value to any structure member, the
member name must be linked with the structure variable using a dot .
operator also called period or member access operator.
#include<stdio.h> /*
#include<string.h> using string function to add
name
struct Student */
{ strcpy(s1.name, "Viraaj");
char name[25]; /*
int age; displaying the stored values
char branch[10]; */
//F for female and M for male printf("Name of Student 1:
char gender; %s\n", s1.name);
}; printf("Age of Student 1: %d\n",
int main() s1.age);
{
struct Student s1; return 0;
}
/*
s1 is a variable of Student type
and Output
age is a member of Student Name of Student 1: Viraaj
*/ Age of Student 1: 18
s1.age = 18;
41
Structure Initialization
Like a variable of any other datatype, structure variable can also be
initialized at compile time.
struct Patient struct Patient p1;
{ p1.height = 180.75; //initialization
float height; of each member separately
OR
int weight; p1.weight = 73;
int age; p1.age = 23;
};
struct Patient p1 = { 180.75 , 73,
23 }; //initialization
Array of Structure
We can also declare an array of structure variables. in which each
element of the array will represent a structure variable. Example : struct
employee emp[5];
#include<stdio.h> printf("\nEnter Salary:\t");
struct Employee scanf("%d", &emp[i].sal);
{ }
char ename[10]; printf("\nDisplaying Employee
int sal; record:\n");
};
struct Employee emp[5]; for(i = 0; i < 3; i++)
int i, j; {
void ask() printf("\nEmployee name is
{ emp[i].ename);
for(i = 0; i < 3; i++) printf("\nSalary is %d",
{ emp[i].sal);
printf("\nEnter %dst Employee }
record:\n", i+1); }
printf("\nEmployee name:\t"); void main()
scanf("%s", emp[i].ename); {
ask(); }
Above program defines an array emp of size 5. Each element of the array
emp is of type Employee. 42
Nested Structures struct Student
Nesting of structures, is also {
char[30] name;
permitted in C language. Nested int age;
structures means, that one /* here Address is a structure */
struct Address
structure has another stucture as {
member variable. char[50] locality;
char[50] city;
int pincode;
}addr;
};
Structure as Function Arguments
We can pass a structure as a function argument just like we pass any
other variable or an array as a function argument.
Pointer to array
int arr[10];
int *p[10]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.
Pointer to a function
void show (int);
void(*p)(int) = &display; // Pointer p is pointing to the address of a
function
Pointer to structure
struct st {
int i;
float f;
}ref;
struct st *p = &ref;
c pointers
46
In C, you can declare an array and can use pointer to alter the data of
an array.
This program declares the array of six element and the elements of that
array are accessed using pointer and returns the sum.
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main(){
int i, class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
47
C Program for Pointers and Strings
#include <stdio.h>
int main()
{ Output
char *cities[] = {"Iran", "Iraq"}; Iran
int i; Iraq
for(i = 0; i < 2; i++)
printf("%s\n", cities[i]);
return 0;
}
C Program for Array of Pointers
#include <stdio.h>
return 0;
}
48
C Program for Pointers and Functions
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
Output
return 0;
49
C Program for Pointers and Structures
#include <stdio.h>
struct person
{
int age;
float weight;
};
Practice Quiz
int main() Link
{ https://tinyurl.co
struct person *personPtr, person1; m/ydt78e5y
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
1. personPtr->age is equivalent to (*personPtr).age
2. personPtr->weight is equivalent to (*personPtr).weight
50