0% found this document useful (0 votes)
31 views29 pages

Unit-1, Bca-301 Data Structures Using C

Uploaded by

vanshthakur993
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)
31 views29 pages

Unit-1, Bca-301 Data Structures Using C

Uploaded by

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

BY : ANKIT KUMAR BALIYAN

[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

DATA STRUCTURES USING C


(According to Swami Vivekanand Subharti University Syllabus)

BCA 301

By :
Mr. Ankit Kumar
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

UNIT -1

I C-Language Programming
Data types, I/O functions, Logical Operators, Control structures of C, Conditional Statements, Switch
Statement, Arrays.

INTRODUCTION OF C LANGUAGE

C Language
 C Language is developed by Dennis Ritchie for creating system applications
 C programming is considered as the base for other programming languages
 C is a procedural language. In C, variables and function prototypes must be
declared before being used.
 Structured programming language.

 Mid-level programming language

 System programming language

History of C

 History of C language is interesting to know. Here we are going to discuss

a brief history of the c language.

 C programming language was developed in 1972 by Dennis Ritchie at bell

laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.

Features of C Language

It provides many features that are given below.


BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

1. Simple

2. Machine Independent or Portable

3. Mid-level programming language

4. structured programming language

5. Rich LibraryMemory Management

6. Fast Speed

7. Pointers

8. Recursion

9. Extensible

First C Program
Firstly you need to learn how to write, compile and run the first c program.
To write the first c program, open the C console and write the following code:

**** Write a program to Print “Hello C Language”.#include <stdio.h>


#include <conio.h>
Void main()

{
printf("Hello C Language");
getch();
}

#include <stdio.h> includes the standard input output library functions. Theprintf() function is defined in
stdio.h.
#include <conio.h> includes the Console input output library functions. Thegetch() function is defined in
conio.h .

Void main() func on is the entry point of every program in c language.

printf() The printf() function is used to print data on the console.

getch() The getch() function is used to Hold the console screen wheneveruser press any key.

How to compile and run the c program

 press Alt+f9 keys compile


 press ctrl+f9 keys run
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

prin () and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).

prin () func on

The printf() function is used for output. It prints the given statement to theconsole.

syntax:
printf("format string",argument_list);

Note: The format string can be %d (integer), %c (character), %s (string), %f(float) etc.

scanf() func on

The scanf() function is used for input. It reads the input data from the console.

syntax:

scanf("format string",argument_list);

eg. scanf(“%d”,&a);
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

Variables
A variable is a name of the memory location. It is used to store data. Its value can
be changed, and it can be reused many times.

syntax:
type variable_Name;

example : int a;
float b;
char c;

Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';

Rules for defining variables


o A variable can have alphabets, digits, and underscore.

o A variable name can start with the alphabet, and underscore only. It can't

start with a digit.

o No whitespace is allowed within the variable name.

o A variable name must not be any reserved word or keyword, e.g. int, float,

etc.
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

C Tokens
Tokens in C is the most important element to be used in creating a program in C.
We can define the token as the smallest individual element in C. For `example, we
cannot create a sentence without using words; similarly, we cannot create a
program in C without using tokens in C.

Classifica on of tokens in C

Tokens in C language can be divided into the following categories:

o Keywords in C

o Identifiers in C

o Strings in C

o Operators in C

o Constant in C

o Special Characters
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

Keywords :

Keywords in C can be defined as the pre-defined or the reserved words having


its own importance, and each keyword has its own functionality. Since keywords
are the pre-defined words used by the compiler, so they cannot be used as the
variable names. If the keywords are used as the variable names, it means that we
are assigning a different meaning to the keyword, which is not allowed. C language
supports 32 keywords given below:

Auto double int struct

Break else long switch

Case enum register typedef

Char extern return union

Const float short unsigned

Continue for signed void

Default goto sizeof volatile

Do if static while

Iden fiers :

 Identifiers in C are used for naming variables, functions, arrays, structures,


etc.
 Identifiers in C are the user-defined words.
 It can be composed of uppercase letters, lowercase letters, underscore, or
digits, but the starting letter should be either an underscore or an alphabet.
 Identifiers cannot be used as keywords.
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an

underscore, and then it can be followed by any of the character, digit, or

underscore.

o It should not begin with any numerical digit.

o In identifiers, both uppercase and lowercase letters are distinct. Therefore,

we can say that identifiers are case sensitive.

o Commas or blank spaces cannot be specified within an identifier.

o Keywords cannot be represented as an identifier.

o The length of the identifiers should not be more than 31 characters.

o Identifiers should be written in such a way that it is meaningful, short, and

easy to read.

Strings :

 Strings are always represented as an array of characters having null


character '\0' at the end of the string.
 This null character denotes the end of the string.
 Strings are enclosed within double quotes, while characters are enclosed
within single characters.
 The size of a string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "vedansh"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "vedansh"; // The compiler allocates the memory at the run time.

char a[10] = {'v','e','d','a','n','s','h','\0'}; // String is represented in the form of


characters.

Operators :
 Operators is a special symbol used to perform the functions.
 The data items on which the operators are applied are known as operands.
 Operators are applied between the operands. Depending on the number of
operands, operators are classified as follows:
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

Unary Operator
A unary operator is an operator applied to the single operand. For example:
increment operator (++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is
the list of the binary operators:

o Arithmetic Operators

o Relational Operators

o Shift Operators

o Logical Operators

o Bitwise Operators

o Conditional Operators

o Assignment Operator

o Misc Operator

Constants :
 A constant is a value assigned to the variable which will remain the same
throughout the program.
 constant value cannot be changed.

Types of constants

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Character constant 'a', 'b', 'c', etc.


BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

String constant "java", "c++", ".net", etc.

Special characters :

Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.

o Square brackets [ ]: The opening and closing brackets represent the single

and multidimensional subscripts.

o Simple brackets ( ): It is used in function declaration and function calling.

For example, printf() is a pre-defined function.

o Curly braces { }: It is used in the opening and closing of the code. It is

used in the opening and closing of the loops.

o Comma (,): It is used for separating for more than one statement and for

example, separating function parameters in a function call, separating the

variable when printing the value of more than one variable using a single

printf statement.

o Hash/pre-processor (#): It is used for pre-processor directive. It basically

denotes that we are using the header file.

o Asterisk (*): This symbol is used to represent pointers and also used as an

operator for multiplication.

o Tilde (~): It is used as a destructor to free memory.

Period (.): It is used to access a member of a structure


BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

DATA TYPES

A data type specifies the type of data that a variable can store such as integer,
floating, character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void


BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

Control Statements

The if statement in C language is used to perform operation on the basis of condition. By


using if-else statement, you can perform operation either condition is true or false.

There are many ways to use if statement in C language:

o If statement
o If-else statement
o If else-if ladder
o Nested if

If Statement

The single if statement in C language is used to execute the code if condition is true. The
syntax of if statement is given below:

if(expression)
{
//code to be executed
}

Let's see a simple example of c language if statement.

1. #include<stdio.h>
2. int main()
3. {
4. int number=0;
5. printf("enter a number:");
6. scanf("%d",&number);
7. if(number%2==0)
8. {
9. printf("%d is even number",number);

10. }
11. return 0;
12. }
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false. The syntax
of if-else statement is given below:

1. if(expression)
2. {
3. //code to be executed if condition is true
4. }
5. else
6. {
7. //code to be executed if condition is false
8. }

Let's see the simple example of even and odd number using if-else statement in C language.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{

10. printf("%d is odd number",number);


11. }
12. return 0;
13. }
BY : ANKIT KUMAR BALIYAN
[email protected]
DEPARTMENT OF COMPPUTER APPLICATION

If else-if ladder Statement


The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if
statement is given below:

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if
condition2 is true 5. }
6. else if(condition3){

7. //code to be executed if
condition3 is true 8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

The example of if-else-if statement in C language is given below.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals
to 10"); 8. }
9. else if(number==50){
10.printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }

Output

enter a number:4
number is not equal to 10, 50 or 100
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Switch Statement
The switch statement in C language is used to execute the code from multiple
conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

1. switch(expression)
2. {
3. case value1:
4. //code to be executed;
5. break; //optional
6. case value2:
7. //code to be executed;
8. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12.}

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

3) The case value can be used only inside the switch statement.

4)The break statement in switch case is not must. It is optional. If there is no


break statement found in switch case, all the cases will be executed after
matching the case value. It is known as fall through state of C switch statement.
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Let's see a simple example of c language switch statement.

1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }

Output

enter a number:4
number is not equal to 10, 50 or 100
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Loops

The looping can be defined as repeating the same process multiple times until a specific condition
satisfies. There are three types of loops used in the C language

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10
iterations.

Advantage of loops in C

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops
There are three types of loops in C language that is given below:

1. do while
2. while
3. for

do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is
used when it is necessary to execute the loop at least once (mostly menu driven programs).

The syntax of do-while loop in c language is given below:

1. do{
2. //code to be executed
3. }while(condition);
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

while loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

1. while(condition)
2. {
3. //code to be executed
4. }

for loop in C
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if
the number of iteration is known in advance.

The syntax of for loop in c language is given below:

1. for(initialization; condition; incr/decr)


2. {
3. //code to be executed
4. }

Example to Display Numbers from 1 to 5


1. #include <stdio.h>
2. int main() //main function
3. {
4. for (int count = 1; count <= 5; count++)
5. {
6. printf("The number is: %d\n", count);
7. }
8. return 0;
9. }
Output:

The number is: 1


The number is: 2
The number is: 3
The number is: 4
The number is: 5
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Example to Print Even Numbers Between 2 and 10

1. #include <stdio.h>
2. int main() //main function
3. {
4. for (int num = 2; num<= 10; num += 2)
5. {
6. printf("The even number is: %d\n", num);
7. }
8. return 0;
9. }

Output:

The even number is: 2


The even number is: 4
The even number is: 6
The even number is: 8
The even number is: 10

Examples: Displaying Multiplication Table of a given number


1. #include <stdio.h>
2. int main() //main function
3. {
4. int num;
5. printf("Enter the multiplication table number you want to print: ");
6. scanf("%d",&num);
7. for (int q = 1; q <= 10; q++)
8. {
9. printf("%d x %d = %d\n", num, q, num * q);
10. }
11. return 0;
12. }

Output:

Enter the multiplication table number you want to print: 5


5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Nested for Loop


In C programming language, a nested for loop is defined as one for loop inside another for loop. Every
time the outer loop is executed, the inner loop is fully executed.

Syntax

It has the following syntax:

1. for (initialization; condition; increment) {


2. for (initialization; condition; increment) {
3. // statement of inner loop
4. }
5. //statement of outer loop
6. }

How do we use a nested for loop in C?

o The outer loop should be used to regulate the primary sequence (for example, rows in a matrix).
o In order to accommodate sub-iterations, place the inner loop inside the outer loop (for example,
columns).
o Set the correct initialization, condition, and update expressions for both loops.
o Add the logic that we want to run inside the inner loop's body.
o Structure the output by using line breaks or formatting methods as required.

Example

1. #include <stdio.h>
2. int main() //main function
3. {
4. int rows = 7;
5. for (int row_num = 1; row_num <= rows; row_num++)
6. {
7. for (int col_num = 1; col_num <= row_num; col_num++)
8. {
9. printf("%d ", col_num);
10. }
11. printf("\n");
12. }
13. return 0;
14. }
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc. It also has the
capability to store the collection of derived data types, such as pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly
accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.

Properties of Array
The array contains the following properties.

Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.

Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.

Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.

Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Declaration of C Array
We can declare an array in the c language in the following way.

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[5];

Here, int is the data_type, marks are the array_name, and 5 is the array_size.

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.

marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

C array example
#include<stdio.h>
int main()
{
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}

Output

80
60
70
85
75

C Array: Declaration with Initialization


We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the following
code.

int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.

#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}

Output

20
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

30
40
50
60

C Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array in ascending order.

#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Program to print the largest and second largest element of the array.
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);

}
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D arrays are
created to implement a relational database lookalike data structure. It provides ease of holding the
bulk of data at once which can be passed to any number of functions wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

data_type array_name[rows][columns];

Consider the following example.

int arr[3][3];

Here, 3 is the number of rows, and 3 is the number of columns.

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at
least the second dimension of the array. The two-dimensional array can be declared and defined
in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

Two-dimensional array example in C


#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
BY :- MR. ANKIT KUMAR BALIYAN
[email protected]
BCA DEPARTMENT

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

You might also like