0% found this document useful (0 votes)
0 views25 pages

CS3353 C Programming and Data Structures 25 Pages

The document provides an overview of arrays in C programming, including their declaration, initialization, and features. It explains both compile-time and runtime initialization, as well as the concept of two-dimensional arrays. Additionally, it introduces functions, pointers, and recursion, highlighting their importance in code modularity and reusability.

Uploaded by

Arun Raj AK
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)
0 views25 pages

CS3353 C Programming and Data Structures 25 Pages

The document provides an overview of arrays in C programming, including their declaration, initialization, and features. It explains both compile-time and runtime initialization, as well as the concept of two-dimensional arrays. Additionally, it introduces functions, pointers, and recursion, highlighting their importance in code modularity and reusability.

Uploaded by

Arun Raj AK
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/ 25

1.11.

ARRAYS
An array is defined as finite ordered collection of homnogenous data, stored in
contiguous memory locations.
Features
to store list of Employee or Student names,
to store marks of students,
or to store list of numbers or character
Declaring an Array
Like any other variable, arrays must be declared
before they are used. General
form of array declaration is.,
data-type variable-name<size];
/* Example of array declaration */
int arr[10];

arr [0] [1] (2] [31 (4) (5] [6] [7] [8) [9)
int isthe data type, arr is the
name of the array and 10 is the size of
array arr can only array. It mea
contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first
at arr•0]address and the last element of arr array will be store
element willoccupy arrf91.
Initialization of an Array
After an array is
declared it must be initialized. Otherwise. it will contain garbag
value(any random value). An array can be initialized at either compile time or a
runtime.
CProgramming Basics 1.33

Compile time Array initializaion


Compile time initialization of array elements is
initialization. The general form of initialization of array is,same as ordinary variable
data-type array-name[size] = { list of values };
* Here are a few examples */
int marks[4]={ 37,47, 46, 76 }: Ilinteger array initialization
float area[5]={ 23.4, 6.8, 5.5 }: / Aloat
array initialization
#include<stdio.h>

void main)

int i:
int arr[] = (2,3, 4):
4}; I//Compile
Compile time array initialization
for(i =0;i<3;itt)

printf("%dlt", arr[i]);:

234

Runtime Array initialization


An array can also be initialized at runtime using scanf() function. This approach is
usually used for initializing large arrays, or to initialize arrays with user specified
values. Example,
#include<stdio.h>

void main)

int arr[4]:;
Fundamentals of Data
1.34| Structures in C
int i, j;
printf("Enter array element");
for(i =0;i<4; it+)

scanf("%d",&ar[i): //Run time array initialization

for(j =0; j<4; jt+)

printf("%dn", arri]);

Two dimensional Arrays


Clanguage supports multidimensional arrays also. The
simplest form of a
multidimensional array is the two-dimensional array. Both the row's and
column's
index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-sizel[column-size]
* Example */
int a[3||4];

a (0] [0] a[0][1] a(0][2] a(0](3]

a(1] [0] a[1][1] a[1][2] a (1] (3]

a (2] [0] a[2] [1] a [2] (2]


a [2] [3]
|1.34 Fundamentals of Data Structures in C
int i, j:
printf("Enter array element");
for(i =0; i<4; itt)

scanf("%d", &arr[i); /Run time array initialization

forj = 0;j<4; jt+)

printf"%dn", arr[i):

Two dimensional Arrays


C language supports multidimensional arrays also. The simplest form of a
multidimensional array is the two-dimensional array. Both the row's and column's
index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
* Example */
int a<3|[4);

a (0] [0) a[0][1] a[0][2] a(0][3)

a [1] [0] a[1][1] a [1][2 ] a [1] |3]

a [2] [0] a [2] [1] a [2] (2] a [2] [3]


CProgramming Basics 1.35|

An array can also be declared and initialized together.


For example,
int arr(][3]={
{0,0,0},
{1,1,1}

We have not assigned any row value to our array in the above example. It means
we can initialize any number of rows. But, we must always specify number of
columns, else it willgive a comnpile time error. Here, a 2*3 multi-dimensional matrix
is created.

Runtime initialization of a two dimensional Array


#include<stdio.h>

void main()

int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i<3;it+)

for(j = 0;j<4;j++)

scanf("%d", &arr[i]GD;

for(i =0; i<3; it+)


{
for(j = 0;j<4; jt+)
CProgramming Basics
|1.37
char c[] ="abcd":
OR,
char c[5]= {'a, 'b', 'c, 'd', n0'}:
String can also be initialized using
pointers as:
char *c = "abcd":
char name[10] =
str = "hell";
{L;e,'s,'s,o,n';s,\0'}:
// Illegal
/valid initialization

1.13. STRINNG HANDLING FUNCTION


Clanguage supports a large number of string handling
functions that can be used
to carry out many of the string manipulations. These
functions are packaged in
string.h library. Hence, we must include string.h header file in your
these functions.
programs to use
The following are the most commonly used string handling functions.

Method
Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show length of a string

strcpy) Copies one string into another


strcmp() It is used to compare the string

strcat() function
strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e it will ouput helloworld.
strlen() function
strlen() function will return the length of the string passed to it.
int j;
j= strlen("computer");
printf("%d" j);
UNIT II
FUNCTIONS, POINTERS,
STRUCTURES AND UNIONS
2.1. FUNCTIONS

Afunction is a block of code that performs a particular task.


There are many situations where we might need to write same line of code for
more than once in a program. This may lead to unnecessary repetition of code, bugs
and even becomes boring for the programmer. So, C language provides an approach
in which you can declare and define a group of statements once in the form of a
function and it can be called and used whenever required.
These functions defined by the user are also known as User-defined Functions
Cfunctions can be classified into two categories,
Library functions
User-defined functions
Library functions are those functions which are already defined in C library,
example printf(), scanf) ete. We need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.
A User-defined functions on the other hand, are those functions which are
defined by the user at the time of writing program. These functions are made for
code reusability and for saving time and space.
Merits of Using Functions
It provides modularity to program's structure.
It makes code reusable.
Debugging and editing becomes easier.
It makes the program more readable and easy to understand.
undd
2.2
res in C

Function Declaration

General syntax for function declaration is,


Return type function name (data typel, paramneterl, data type2, parameter2,
....)

IIfunction body

declared beforeit i.
Like any variable or an aray, a function must also be
used.

Function declaration informs the compiler about the function name


parameters is accept, and its return type.
The actual body of the function can be defined separately.
It's also called as Function Prototyping.
Function declaration consists of 4 parts. Such as return type, function name,
parameter list, function body

1. Return Type

When a function is declared to perform some sort of calculation or any operation


and is expected to provide with some result at the end, in such cases,
a return statement is added at the end of function body. Return type specifies the type
of value (int, char, float, double, etc) that function is expected to return to tne
program which called the function.
In case your function doesn't return any value, the return type would be void.
2. Function Name
Function name is an identifier and it specifies the name of the
function.
function name is any valid Cidentifier and therefore must follow the samne namit
rules like other variables in C language.
3. Parameter List

The parameter list declares the type and number of arguments that the function
expects when it is called. They are often referred as formal
parameters.
Eunctions, Pointers, Structures and Unions 2.3
4. Function Body
The function body contains the declarations and the
statements(algorithm)
necessary for performing the required task. The body is enclosed within curly
braces...} and consists of three parts.
local variable declaration(if required).
function statements to perform the task inside the function.
a return statemnent to return the result evaluated by the function

Example:

Asimple program with a main() function, and a user defined function to multiply
two numbers, which will be called from the main function.
# include <stdio.h>

int multiply(int a, int b); // function declaration


int main)

int i, j, result;
printf("Enter two numbers :);
scanf("%d%d", &i, &j);
result = multiply(ij); I/function call
printf("RESULT: %d", result);
return (0);

Int multiply(int a, int b)

Teturn(a * b): // function definition

Callinga Function
function is called, control of the program gets transferred to the function.
When a
Function name (argumentl, argument2, ...)
Fundamentals of Data.
|2.4 Structures in C

Passing Arguments to a function function call, for which


during the
Arguments are the values specified
parameters are declared while defining the function.
the formal
Functions

Without Arguments
With Arguments

declared and defined with No parameters included


parameter list

values for parameter No value passed during


passed during call function call

Eg: Eg:
IIdeclaration Il declaration
int sum (int x, int y);: int display ):
l call Il call
sum (10, 20) display ():

It is possible to have a function with parameters but no return type. It is not


necessary, that if a function accepts parameter(s), it must return a result to0.
# include<stdio.h>

int multiptly(int a, int b):


int main(0

result = multiply (i, j):


Providing orguments while
calling function
int multiply (int a, int b)

While declaring the function, we have declared two


parameters a and b of type int.
Therefore, while calling that function, we need to pass two arguments, else we will
get compilation error. And the two arguments passed should be
received in the
Functions, Pointers, Structures and Unions 2.5

function definition, which means that the function header in the function definition
should have the two parameters to hold the argument values. These received
arguments are also knoWn as formal parameters. The name of the variables while
declaring, calling and defining a function can be different.
Returning a Value from Function
A function may or may not return a result. But if it does, we must use
the return statement to output the result. return statement also ends the function
execution, hence it must be the last statement of any function.
The datatype of the value returned using the return statement should be same as
the return type mentioned at function declaration and definition. If any of it
mismatches, you will get compilation error.
In the next tutorial, we will learn about the different types of user defined
functions in Clanguage and the concept of Nesting of functions which is used in
recursion.

Type of User-defined Functions in C


There can be four different types of user-defined functions, they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3 Function with arguments and no return value
4 Function with arguments and a return value
1. Function with no arguments and no return value
Functions can either be used to display information or they are completely
dependent on user inputs.
from user, and
Below is an example of a function, which takes 2 numbers as input
display which is the greater number.
# include <stdio.h>

void big):
int main(0

big() // function call


|2.12 Fundamentals of Data Structures in C

2.4. POINTERS

Address in C
Whenever a variable is defined in C language, a memory location is assigned for
it, in which it's value will be stored. We can casily check this memory address, using
the & symbol.
If var is the name of the variable, then & var will give it's address.
Scanf(*9%d", &var):
This is used to store the user inputted value to the address of the variable var.
Concept of Pointers
Whenever a variable is declared in a program, system allocates a location i.e an
address to that variable in the memory, to hold the assigned value. This location has
its own address number, Let us assume that system has allocated memory
location 80F for a variable a.
int a = 10:
Value

10

a name of location
80 F
Location
address

We can access the value 10either by using the variable name a or by using its
address 80F.

Since the memory addresses are also just numbers, they can also be assigned to
some other variable. The variables which are used to hold memory
addresses are
called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an
address o!
some other variable. And the value of a pointer variable gets
stored in another
memory location.
Functions, Pointers, Structures and Unions 2.13
address of "a"
80 F|
ptr pointer name
82 C

10
address of pointer
80 F

Advantage of Pointer
1. Pointer reduces the code and improves the performance, it is used to
retrieving strings, trees etc. and used with arrays, structures and functions.
2. We can return multiple values from function using pointer.
3. It makes you able to access any memory location in the computer's
memory.
4. It allows C language to support Dynamic Memory management.
Address Of Operator
The address of operator '&retuns the address of avariable. But, we need to use
%u to display the address of avariable.
Example
#include<stdio.h>
int main){
int number=50;
%u",number,&number):
m("value of number is od, address of number is

return 0;
address of number is fff4
number is 50,
OUTPUT:value of
POINTER VARIABLE
2.4.1. DECLARATION OF
declaration is,
General syntax of pointer
Data tyype *pointer name;
2.3. RECURSION

Recursion isa special way of nesting functions, where a function calls itself inside
it. We must have certain conditions in the function to break out of the recursion,
otherwise recursion will occur infinite imes.
Functions, Pointers, Structures and Unions

Function l1)

Ilfunctionl body;
Function2(0 l/ calling of function2) inside the function1(0
}
Example: Factorialofa number using Recursion
#include <stdio.h>

int factorial (int x); // declaring the function


int main()

int n,m;
printf(Enter the value for n'");
scanf(%d", &n);
m= factorial(n);
printf(Factorial value for %d is %d", n,m);
return(0);
}
int factorial(int x)

int r=1;
if (x-=1)
return 1;
else
{
r=x *factorial(x-1);
return r;
2.6. STRUCTURE

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. Each element of a structure is called a member.
2.6.1. DEFINITION OF STRUCTURE
struct keyword is used to define a structure. struct defines a new data type which
is a collection of primary and derived datatypes
struct structure name

data type memberl;


data_type member2;
Functions, Pointers, Structures and Unions

data_type memeberN:
}:

Example :
struct employee
intid:
char name[50];
float salary;
}el,e2;
tag or structure tag
struct keyword

Struct employee{
int id; members or
char name [50]: fields of
float salary; structure

Accessing members of structure


There are two ways to access structure members:
1, ." (member or dot operator)
2. ->structure pointer operator)
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}el; //declaring el variable for structure
int main()

lstore first employee information


Fundamentals ofD
|2.22
el.id=100;
stringintochar array
strepy(el.name,"Rama");/copying
l/printing first employee information
printf( "employee 1id:%dn", el.id);
el.name);
printf( "employee 1 name:%s\n",
return 0;

OUTPUT:
employee 1id : 100
employee 1 name : Rama
2.6.2. ARRAY OF STRUCTURE
The array of structures is known as collection of structures.
Example :
#include<stdio.h>
#include <string.h>
struct student
int rollno;
char name[10];

int main) {
int i;
struct student st[2];
printf("Enter Records of 2 students'"):
for(i=0;i<5;it+){
printf("nEnter Rollno:");
scanf("%d" &st[i].rollno);
printf("nEnter Name:");
scanf("%s",&st[i].name);
Functions, Pointers, Structures and Unions 2.23|

printf("nStudent Information List:"):


for(i-0;i<2;i++){
"nRollno:%d, Name:%s".st[i].rollno,st[i].name);
printf("\

return 0:

OUTPUT

Enter Records of 2 students


Enter Rollno:11
Enter Name:rama
Enter Rollno:22
Enter Name:sita
Student Information List:
Rollno:11,Name:rama
Rollno:22, Name:sita
Searchingand, Sorting Algorithms
5.3

printf"%dis present at location


%d.\n", search, c+1);
break;

if(c==n)
printf("%disn't present in the array.\n", search);
return 0:

51.2. BINARY SEARCH


The binary search algorithm finds the position of a specified input value (the
search "key") within an array sorted by key value. For binary search, the array should
be arranged in ascending or descending order. In each step, the algorithm compares
the search key value with the key value of the middle element of the array. If the
keys match, then a matching element has been found and its index, or position, is
returned. Otherwise, if the search key is less than the middle element's key, then the
algorithm repeats its action on the sub-array to the left of the middle element or, if
the search key is greater, on the sub-array to the right. If the remaining array to be
Searched is empty, then the key cannot be found in the array and a special "not
found" indication is returned.

Algorithm
Probe middle of list
If target equals list[mid], FOUND.
* lf target < list [mid], discard 1/2 of list between list [mid] and list [last].
Iftarget >> list [mid], discard 1/2 of list between list [first]and list [mid].
*Continue searching the shortened list until either the target is found, or there
are no elements to probe.

ExamplAe: B C D E F G H I K L

2 3 4 5 6 7 8 9 10 11
Fundamentc
5.4

Search for F
low is 0, high is 11.
(high + low)/2 or (11+ 0)/2 or 5.
mid is
list[5]is E. /FOUND!
Complexity
Bestcase complexity requires 0 (1)time.
* Average case requires O (log n) time.
Routine to Binary Search
#include <stdio.h>

int main()

int c, first, last, middle, n, search, array[100];

printf("Enter number of elementsn");


scanf("%d",&n);

printf("Enter %d integersn", n);

for (c =0; c <n; ctt)


scanf("%d",&array[c]);
printf("Enter value to findn"):
scanf("%d", &search);

first =0:;
last =n - 1:;
middle = (first+last)2;
Scarcchingand Sorting Algorithms 5.5
!
while (irst <= last)
if(array[middle] <search)
1:
first middle +
clsei if (array[middle] =-search)
printi("odfound at location %d.In",
search, middle +l);:
break:

clse

last = middle - 1:

middle = (first + last)/2:

if (first > last)


nrintf("Not found! od isn't present in the list.\n",
search):
return 0;

5.2. SORTING

It is an algorithm that puts elements of a list in a certain order. The


orders are numerical order and most-used
for optimizing the use of other lexicographical order. Efficient sorting is important
algorithms which require input data to be in sorted
lists. The output of sorting must satisfy the
following conditions.
1. The output is in
non-decreasing order.
2. The output is reordering the input.
The factors to be considered while
choosing sorting techniques are:
* Programming time
Execution time
* Number of
comparisons
Fundamentals of Data
|5.6| Structures in (:
Memory utilization
Computational complexity
Types of Sorting Techniques
Sorting techniques are categorized into 2 types:
1. Internal Sorting
2. External Sorting
Internal Sorting
It takes place in the main memory of a computer.
Example: 1. Bubble sort 2. Insertion sort
3. Selection sort 4. Shell sort
5. Quick sort 6. Radix sort
7. Heap sort
External Sorting
External sorting takes place in the secondary memory of a computer. Since the
number of objects to be sorted is too large to fit in main memory.
Example: 1. Merge sort
2. Multi way merge
3. Polyphase merge

5.3. BUBBLE SORT

Concept
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison
based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order.
Procedure

* Itmakes multiple passes through a list.


$ Itcompares adjacent items and exchanges those that are out of order.
Each pass through the list places the next largest value in its proper place.
Searching andISorting Algorithms
|5.7|
In essence, cach
item "bubbles" up to the
Example location where it belongs.
-245 0 11
11| g45|
-2o-1
4
|45|
-2-o145
-2)45o11 -2o 11-las -2 0-911|45 o2 o11|45
44
-2 o 45|11 -2 o11-l45| -2-g o11|45
1145
4 4
9
-2o-1145
-2 011-45

Step 1 Step 2 Step 3 Step 4

Algorithm Analysis
Ihis algorithm is not suitable for large data, sets as its average and worst case
complexity are of O(n2) where n is the number of items.
Routine for Bubble Sort
#include <stdio.h
int main(

int array[100]
00], n, i,j, swap;

printf("Enter number of elementsn");


Scanf("%d", &n);
printf("Enter-%d integers\n", n);
5.8
Fundan

for (i = 0: i< n; it+)

scanf("%d", &array[i);

for (i =0 i<(n-1); it+)


{
for (j =0;j<n -i-1;jtt)

if (array[j]>array[j+1]) /* For decreasing order use < */

swap = array[i]:
array[j] = array[j+1];
array[j+1] = swap;

printf("Sorted list in ascending order:ln"):

for (i = 0;i<n; it+)


printf("%dn", array[i]);

return 0;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy