CS3353 C Programming and Data Structures 25 Pages
CS3353 C Programming and Data Structures 25 Pages
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
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
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+)
printf("%dn", arri]);
printf"%dn", arr[i):
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.
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;
Method
Description
strcat() It is used to concatenate(combine) two strings
strlen() It is used to show length of a 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
Function Declaration
IIfunction body
declared beforeit i.
Like any variable or an aray, a function must also be
used.
1. Return Type
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 i, j, result;
printf("Enter two numbers :);
scanf("%d%d", &i, &j);
result = multiply(ij); I/function call
printf("RESULT: %d", result);
return (0);
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
Without Arguments
With Arguments
Eg: Eg:
IIdeclaration Il declaration
int sum (int x, int y);: int display ):
l call Il call
sum (10, 20) display ():
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.
void big):
int main(0
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 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
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
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|
return 0:
OUTPUT
if(c==n)
printf("%disn't present in the array.\n", search);
return 0:
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()
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:
5.2. SORTING
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
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;
scanf("%d", &array[i);
swap = array[i]:
array[j] = array[j+1];
array[j+1] = swap;
return 0;