0% found this document useful (0 votes)
27 views50 pages

Final DS Workbook

Uploaded by

Sayali Kawale
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)
27 views50 pages

Final DS Workbook

Uploaded by

Sayali Kawale
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
You are on page 1/ 50

M.S.P.M.

’s

Deogiri Institute of Engineering and


Management Studies, Aurangabad

Department of Computer Science


and Engineering

Work-Book
for
Data Structures
Using C
Dear Students,

Learning data structures and algorithms helps in solving real time


complex problems and in improving problem-solving skills. So, let’s
see what the prerequisites for Data Structures and Algorithms are.
The first prerequisite for Data Structures and Algorithms is one must
be aware of at least one programming language. Most of the student
will be in a dilemma, is learning one programming language is
enough? The answer is yes, instead of learning two or three
programming languages and make yourself more confused better to
learn one programming language in good way is enough. So here the
question what are programming languages need to be learnt for Data
Structures?
• C
• C++
• Java
• Python

If you are new to programming then start learning C-language, as it


is base for every programming language. After learning C-language
you can automatically learn by yourself C++, Java. We are using C
programming language for implementing concept of Data
Structures. So, if you want to be good in Data Structures, you should
be good enough in C then! 2
CONTENTS
S.No. Name of Topic Page

1. Data Types 6-9

2. Variables 10-12

3. Operators 13-21

4. Input/Output 22-24

5. Conditional Statements 25-30

6. Loops 31-34

7. Functions 35-39

8. Structures 40-43

9. Unions 44

10. Pointers 45-50

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

Online Courses Available


Also, u can go with few good online courses available online.
1. Course on “C Programming for Beginners – Master the C
Language” by Udemy
2. Course on “Introductory C Programming Specialization”
by Coursera
3. Course on “C in 4 Hours” (Free YouTube Course by
FreeCodeCamp)
4. Course on “Learn C from Scratch” (Free Course Educative)

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.

• int: It is responsible for storing integers.


The memory it occupies depends on the Data types in C refer to
compiler (32 or 64 bit). In general, int data the characteristics of data stored into a
type occupies 4 bytes of memory when variable.
working with a 32-bit compiler.
• float: It is responsible for storing fractions
or digits up to 7 decimal places.. It
occupies 4 bytes of memory Signed: It is used to store

• char: It can be used to store a set of all zero, positive or negative

characters which may include alphabets, values.

numbers and special characters. It Unsigned: It can store only

occupies 1 byte of memory being the zero or positive values.

smallest addressable unit of a machine Long: It is used to store

containing a fundamental character set. large integer numbers. The

• double: It is responsible for storing size of the long type is 8

fractions or digits up to 15-16 decimal bytes.

places. It is usually referred to as a Short: It is used to store

double-precision floating-point type. small integer numbers. Its s

• void (Null) data type: It indicates zero or size is of 2 Bytes.

no return value. It is generally used to


assign the null value while declaring a
function. 6
Data Type Memory (In Bytes) Format Specifiers Range
int 4 %d -2,147,483,648 to
2,147,483,647
short int 2 %hd -32,768 to 32,767
unsigned int 4 %u 0 to 4,294,967,295
unsigned short int 2 %hu 0 to 65,535
long int 4 %ld -2,147,483,648 to
2,147,483,647
unsigned long int 4 %lu 0 to 4,294,967,295
long long int 8 %lld -(263) to (263)-1
unsigned long long 8 %llu 0 to
int 18,446,744,073,709,5
51,615

char 1 %c -128 to 127


Signed char 1 %c -128 to 127
Unsigned char 1 %c 0 to 255
float 4 %f –
double 8 %lf –
long double 12 %Lf –

In order to compute the size of a variable, we can use the function


sizeof ( ) operator. Its output is of the form of an unsigned integer.

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.

Types of Variables in C Valid variable names


There are many types of variables int a;
in c: int _ab;
1. Local variable int a30;
2. Global variable Invalid variable names
3. Static variable int 2;
4. Automatic variable int a b;
5. External variable int long;

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

Static Variable Automatic Variable


All variables in C that are declared
A variable that is declared with the static
inside the block, are automatic variables
keyword is called static variable.
by default. We can explicitly declare an
void function1( ){
automatic variable using auto
int x=10;//local variable
keyword.
static int y=10;//static variable
void main( )
x=x+1;
{
y=y+1;
int x=10;//local variable (also auto
printf("%d,%d",x,y);
matic)
}
auto int y=20;//automatic variable
If you call this function many times,
}
the local variable will print the same External Variable
value for each function call, e.g, 11,11,11 We can share a variable in multiple C
and so on. But the static variable will source files by using an external
print the incremented value in each variable. To declare an external
function call, e.g. 11, 12, 13 and so on. variable, you need to use extern
keyword.
extern int x=10;//external variable
11
Check Your Understanding
1. How many keywords are there in c ?
A. 31
B. 32
C. 64
D. 63
2. Which of the following is true for variable names in C?
A. Variable names cannot start with a digit
B. Variable can be of any length
C. They can contain alphanumeric characters as well as special characters
D. Reserved Word can be used as variable name

3. Which of the following cannot be a variable name in C?


A. TRUE
B. friend
C. export
Practice Quiz
D. volatile Link
4. What is the output of this program? https://tinyurl.co
m/5x7982ar
void main()
{
int x = 10;
float x = 10;
printf("%d", x) }
A. Compilations Error
B. 10
C. 10
D. 10.1
12
Lesson 3 : Operators

• An operator is a symbol that


operates on a value or a
variable. For example: + is an
operator to perform addition.
• C has a wide range of
operators to perform various
operations.

#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

Operator Example Same As

= addition or unary plus a=b

+= subtraction or unary minus a += b

-= multiplication a -= b

*= division a *= b

/= a /= b a = a/b

%= a %= b a = a%b

An assignment operator is used for


assigning a value to a variable. The most
common assignment operator is =
14
C Program for illustrating short hand assignment operators

#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

Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

// C Program for relational operators Output


#include <stdio.h> 5 == 5 is 1
int main() 5 == 10 is 0
{ 5 > 5 is 0
int a = 5, b = 5, c = 10; 5 > 10 is 0
Don’t just read
printf("%d == %d is %d \n", a, b, a == b); 5 < 5 is 0
the program!
printf("%d == %d is %d \n", a, c, a == c); 5 < 10 is 1 Execute them
printf("%d > %d is %d \n", a, b, a > b); 5 != 5 is 0 with the help
printf("%d > %d is %d \n", a, c, a > c); 5 != 10 is 1 of tools
printf("%d < %d is %d \n", a, b, a < b); 5 >= 5 is 1 mentioned at
printf("%d < %d is %d \n", a, c, a < c); 5 >= 10 is 0 the beginning
printf("%d != %d is %d \n", a, b, a != b); 5 <= 5 is 1 of workbook!
printf("%d != %d is %d \n", a, c, a != c); 5 <= 10 is 1
printf("%d >= %d is %d \n", a, b, a >= b);
printf("%d >= %d is %d \n", a, c, a >= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
16
Logical Operators

Operator Meaning of Operator Example

&& Logical AND. True only if all If c = 5 and d = 2 then, expression


operands are true ((c==5) && (d>5)) equals to 0.

|| Logical OR. True only if either If c = 5 and d = 2 then, expression


one operand is true ((c==5) || (d>5)) equals to 1.

! Logical NOT. True only if the If c = 5 then, expression !(c==5)


operand is 0 equals to 0.
// C Program for relational operators
// Working of logical operators Output
#include <stdio.h> (a == b) && (c > b) is 1
int main() (a == b) && (c < b) is 0
{ (a == b) || (c < b) is 1
int a = 5, b = 5, c = 10, result; (a != b) || (c < b) is 0
result = (a == b) && (c > b); !(a != b) is 1
printf("(a == b) && (c > b) is %d \n", result); !(a == b) is 0
result = (a == b) && (c < b);
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) is %d \n", result); Explanation
result = !(a != b); of Program
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
(a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
17
Bitwise Operators

• During computation, Comma operators are used to link


related expressions together. For
mathematical operations like example:
addition, subtraction, int a, c = 5, d;
multiplication, division, etc are
sizeof operator
converted to bit-level which
The sizeof is a unary operator that
makes processing faster and saves returns the size of data (constants,
variables, array, structure, etc).
power.
• Bitwise operators are used in C
programming to perform bit-level Operator Meaning of Operator
operations.
& Bitwise AND

C Program for sizeof( ) Operator | Bitwise OR

#include <stdio.h> ^ Bitwise exclusive OR


int main()
{ ~ Bitwise complement
int a;
float b; << Shift left
double c;
>> Shift right
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 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

4. What will be the output of the following C code?


#include <stdio.h>
int main()
{
int a = 1, b = 1, c;
c = a++ + b;
printf("%d, %d", a, b);
}
A. a = 1, b = 1
B. a = 2, b = 1
C. a = 1, b = 2
D. a = 2, b = 2

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

Practice Quiz Link


https://tinyurl.com/3
d5p339j

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.

fflush(stdin) fflush(stdin); Removes characters from the


input stream (keyboard).

fpurge(stdin) fpurge(stdin); Removes characters from the


input stream (keyboard). This
function must be used in Unix
rather than fflush(stdin).

getchar() [ch = ]getchar(); Reads a single character from


the keyboard. The character is
displayed and, optionally,
stored in the char variable ch.

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

2. For a typical program, the input is taken using _________


A. scanf
B. Files
C. Command-line
D. All of the mentioned Practice Quiz Link
https://tinyurl.co
3. What is the value of EOF? m/2b7wwwa8

A. -1
B. 0
C. 1
D.10

4. What is the return value of putchar()?


A. The character written
B. EOF if an error occurs
C. Nothing
D. Both characters written & EOF if an error occurs

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

C Program for illustrating nested-if statements


#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}

Output
First class 28
Check Your Understanding
1. Choose C conditional operator from the list
A. ?.
B. :?
C. :<
D. <:

2. Find the output of following code,

#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

2. What is the output of following code?


#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");}
else if(m<n) {
printf("m is less than n"); }
else {
printf("m is equal to n");}
}
A. Compilation error
B. m greater than n
C m is equal to n
D. m is less than n

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.

Sr. No. Loop Type Description


1. While Loop In while loop, a condition is evaluated before
processing a body of the loop. If a condition is true,
then and only then the body of a loop is executed.
2. Do-While Loop In a do...while loop, the condition is always executed
after the body of a loop. It is also called an exit-
controlled loop.
3. For Loop In a for loop, the initial value is performed only once,
then the condition tests and compares the counter to a
fixed value after each iteration, stopping the for loop
when false is returned.
31
Syntax of While Loop in C C Program to illustrate while loop
while (condition) #include<stdio.h>
{ #include<conio.h>
statements; int main()
} {
int num=1; //initializing the
variable
while(num<=10) //while loop
with condition
{
Syntax of Do- printf("%d\n",num);
While Loop in C: num++;
do { //incrementing operation Output
statements } 1
} return 0; 2
while(expression); } 3
4
#include<stdio.h> 5
#include<conio.h> 6
int main() 7
{ 8
int num=1; //initializing the Output 9
variable 2 10
do //do-while loop 4
{ 6
printf("%d\n",2*num); 8
num++; 10
//incrementing operation 12
}while(num<=10); 14
return 0; 16
} 18
20

32
Syntax of for Loop in C
for (initial value; condition; incrementation or decrementation )
{
statements;
}

C Program for for loop Output


#include<stdio.h> 1
int main( ) 2
{ for, do,
3
int number; 4
while are
for(number=1;number<=10;number++) 5 keywords
//for loop to print 1-10 numbers 6 in C
{ 7
printf("%d\n",number); 8
//to print the number 9
} 10
return 0;
}
//C Program to print multiplication table
#include <stdio.h>
Selection of a loop is always a int main() {
tough task for a programmer, int i, j;
to select a loop do the int table = 2;
following steps: int max = 5;
•Analyze the problem and for (i = 1; i <= table; i++) {
check whether it requires a // outer loop
pre-test or a post-test loop. for (j = 0; j <= max; j++) {
•If pre-test is required, use a // inner loop
while or for a loop. printf("%d x %d = %d\n", i, j, i*j);
•If post-test is required, use a }
do-while loop. printf("\n");
/* blank line between tables */
}}
33
Break Statement in C Continue Statement in C
The break statement is used mainly When you want to skip to the next
in in the switch statement. iteration but remain in the loop,
you should use the continue
statement.
#include <stdio.h>
#include <stdio.h>
int main() {
Output int main() { Output
int num = 5;
5 int nb = 7; 6
while (num > 0) {
4 while (nb > 0) { 4
if (num == 3)
nb--; 3
break;
if (nb == 5) 2
printf("%d\n", num);
continue; 1
num--;
printf("%d\n", nb);
}}
}}

Check Your Understanding


What is the output of C Program.?
int main()
{
while(true)
Practice Quiz
{
Link
printf("RABBIT");
https://tinyurl.co
break;
m/w53njc2z
}

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 () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

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

#include <stdio.h> The call by value


/* function declaration */ method of passing
void swap(int x, int y); arguments to a function
int main () { copies the actual value
/* local variable definition */ of an argument into the
int a = 100; formal parameter of the
int b = 200; function. In this case,
printf("Before swap, value of a : %d\n", a ); changes made to the
printf("Before swap, value of b : %d\n", b ); parameter inside the
/* calling a function to swap the values */ function have no effect
swap(a, b); on the argument.
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b ); By default, C
return 0; programming uses call
} by value to pass
void swap(int x, int y) { arguments.
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
return;
}
Output
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

37
Program for Understanding Call By Reference Concept

To pass a value by reference, argument pointers are passed to the


functions just like any other value. So accordingly, you need to declare
the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables
pointed to, by their arguments.

#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.

Student is the name of the structure


and is called as the structure tag.

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;

We can also use scanf() to give values to structure members through


terminal.

scanf(" %s ", s1.name);


scanf(" %d ", &s1.age);

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.

#include<stdio.h> scanf("%d", &std.roll);


show(std);
struct Student }
{
char name[10]; void show(struct Student st)
int roll; {
}; printf("\nstudent name is %s",
st.name);
void show(struct Student st); printf("\nroll is %d", st.roll);
}
void main()
{
Practice Quiz
struct Student std;
Link
printf("\nEnter Student record:\n");
https://tinyurl.co
printf("\nStudent name:\t");
m/u2vxpdjm
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
43
Lesson 9 : Unions
• Union can be defined as a user-defined data type which is a
collection of different variables of different data types in the same
memory location.
• The union can also be defined as many members, but only one
member can contain a value at a particular point in time.
• Union is a user-defined data type, but unlike structures, they share
the same memory location.
Practice
In union, members will share the memory Quiz Link
location. If we try to make changes in any of https://tiny
the member then it will be reflected to the url.com/bd
other member as well. Let's understand this 3vt6at
concept through an example.
union abc Here, union has two members, i.e.,
{ 'a' and 'b'. The 'var' is a variable of
int a; union abc type. In the main()
char b; method, we assign the 66 to 'a'
}var; variable, so var.a will print 66 on
int main() the screen. Since both 'a' and 'b'
{ share the memory location, var.b
var.a = 66; will print 'B' (ascii code of 66).
printf("\n a = %d", var.a);
printf("\n b = %d", var.b); As we know, the size of int is
} 4 bytes, size of char is 1 byte,
size of float is 4 bytes, and
Deciding the size of the union the size of double is 8 bytes.
Since the double variable
union abc{ int main() occupies the largest memory
int a; { among all the four variables,
char b; printf("Size of union so total 8 bytes will be
float c; abc is %d", sizeof(union allocated in the memory.
double d; abc)); Therefore, the output of the
}; return 0; given program would be 8
} bytes.
44
Lesson 10 : Pointers
• The pointer in C language is a variable which stores the address of
another variable.
• This variable can be of type int, char, array, function, or any other
pointer.
• The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.

Consider the following example to Declaring a pointer


define a pointer which stores the The pointer in c language can
address of an integer. be declared using * (asterisk
symbol). It is also known as
int n = 10; indirection pointer used to
int* p = &n; // Variable p of type dereference a pointer.
pointer is pointing to the address of
the variable n of type integer. int *a;//pointer to int
char *c;//pointer to char

As you can see in the above figure,


pointer variable stores the address
of number variable, i.e., fff4. The
value of number variable is 50. But
the address of pointer variable p is
aaa3.
By the help of * (indirection
operator), we can print the value of
pointer variable p.
• Pointer reduces the code and improves the
performance, it is used to retrieving strings, trees, etc.
Advantages
and used with arrays, structures, and functions.
of Pointers
• We can return multiple values from a function using
the pointer.
• It makes you able to access any memory location in
the computer's memory.
45
#include<stdio.h> Output
int main(){ Address of number variable is fff4
int number=50; Address of p variable is fff4
int *p; Value of p variable is 50
p=&number;
//stores the address of number variable
printf("Address of p variable is %x \n",p);
// p contains the address of the number therefore printing p gives the /
/address of number.
printf("Value of p variable is %d \n",*p);
// As we know that * is used to dereference a pointer therefore if we
//print *p, we will get the value stored at the address contained by p.
return 0;
}

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>

const int MAX = 3;


Output
int main () { Value of var[0] = 10
Value of var[1] = 100
int var[] = {10, 100, 200}; Value of var[2] = 200
int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */
}

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

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

int main() Value of a is 10


{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;

/* The above line is equivalent of following two


void (*fun_ptr)(int);
fun_ptr = &fun;
*/

// Invoking fun() using fun_ptr


(*fun_ptr)(10);

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("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

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

You might also like