Unit Iv&v
Unit Iv&v
Arrays
• An array is a variable that can store multiple values of same data type.
int marks[5]
marks
How to declare an array?
• For example, if you want to store marks obtained in C for 70 students(70
integer values), you can create an array for it.
How to declare an array?
dataType arrayName[arraySize];
int marks[70];
Here, we declared an array, marks, of integer data type. And its size is 70.
Meaning, it can hold 70 integer values.
• You can access elements of an array by indices.
• The first element is mark[0], the second element is mark[1] and so on.
Few keynotes:
• mark
Few keynotes:
•Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
•If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4].
•Also, the array name stores the memory address of the first element
mark=111
How to initialize an array?
• It is possible to initialize an array during declaration. For example,
• mark[0] is equal to 19
• mark[1] is equal to 10
• mark[2] is equal to 8
• mark[3] is equal to 17
• mark[4] is equal to 9
Change Value of Array elements
• Hence, you should never access elements of an array outside of its bound.
Two-dimensional arrays
• C programming language allows multidimensional arrays. Here is the
general form of a multidimensional array declaration −
• type name[size1][size2]...[sizeN]; For example, the following
declaration creates a three dimensional integer array −
int threedim [5][10][4];
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.
Initializing Two-Dimensional Arrays
• int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
• The nested braces, which indicate the intended row, are optional. The
following initialization is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
• Initialization of a 3d array
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Two dimensional array for( i = 0; i < 3; ++i)
Input / Output for(j=0; j<3; ++j)
scanf("%d", &values[i][j]);
/ Program to store values in a two printf("Displaying integers: ");
dimensional array and to print the // printing elements of the array
elements stored in the array/
#include <stdio.h> for( i = 0; i < 3; ++i)
#include <conio.h> {
void main() for( j = 0; j < 3; ++j)
{ printf("%d", values[i][j]);
int values[3] [3], i,j; printf(“\n”);
printf("Enter the values\n "); }
// taking input and storing it in the
array getch();
}
Two-dimensional Array Input/Output
// C program to store temperature of two cities of a printf("\nDisplaying values: \n\n");
week and display it.
// Using nested loop to display values of a 2D
#include <stdio.h> array
const int CITY = 2; const int WEEK = 7; for (int i = 0; i < CITY; ++i)
void main() {
{ printf(“City %d \n”,i+1)
int temperature[CITY][WEEK] ,i, j; for (int j = 0; j < WEEK; ++j)
// Using nested loop to store values in a 2D array {
for ( i = 0; i < CITY; ++i) printf(" Day = %d temperature= %d\n", i
+ 1, temperature[i][j]);
{
}
for (int j = 0; j < WEEK; ++j)
printf(“\n\n”);
{
}
printf("City %d, Day %d:\n ", i + 1, j + 1);
return 0;
scanf("%d", &temperature[i][j]); }
}
Sum of Two Arrays // adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
#include <stdio.h>
#include <conio.h> for (int j = 0; j < 2; ++j)
void main() {
{ result[i][j] = a[i][j] + b[i][j];
float a[2][2], b[2][2], result[2][2];
}
// Taking input using nested for loop
printf("Enter elements of 1st matrix\n"); / Displaying the sum
for (int i = 0; i < 2; ++i) printf("\nSum Of Matrix:");
for (int j = 0; j < 2; ++j)
for (int i = 0; i < 2; ++i)
{
printf("Enter a%d%d: ", i + 1, j + 1); for (int j = 0; j < 2; ++j)
scanf("%f", &a[i][j]); printf("%.1f\t", result[i][j]);
}
printf("\n");
// Taking input using nested for loop
printf(“\nEnter elements of 2nd matrix\n"); }
for (int i = 0; i < 2; ++i) getch();
for (int j = 0; j < 2; ++j) }
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
Programs using arrays
• Linear sorting
• Bubble sort
• Median of n numbers
• Standard Deviation of numbers
• Program to find the largest and second largest number in a set of
numbers
• Program to delete an element from an array in a given position
• Program to add an element at a given position in the array.
• Linear search
Programs using arrays
• Binary search
• Merging of two arrays
• Sum of main diagonal and off diagonal elements
• Matrix is symmetric or not.
• Product of 2 matrices
• Print the elements of upper triangle and lower triangle in a squre
matrix
• Program to find the determinant of a matrix.
Strings in C
• In C programming, a string is a sequence of characters terminated
with a null character \0. For example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in
the double quotation marks, it appends a null character \0 at the end
by default.
How to initialize strings?
You can initialize strings in a number of ways.
char c[100];
• c = "C programming"; // Error! array type is not assignable.
• Note: Use the strcpy() function to copy the string instead.
Commonly Used String Functions
• If the first character of two strings is equal, the next character of two
strings are compared. This continues until the corresponding
characters of two strings are different or a null character '\0' is
reached.
The first unmatched character between string str1 and str2 is third
character. The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67.
Hence, when strings str1 and str2 are compared, the return value is 32
(99-67).
When strings str1 and str3 are compared, the result is 0 because both
strings are identical.
When strings str1 and str2 are compared and if the result is negative,
str2 is alphabetically below str1.
C strcat()
s2[i] = '\0';
printf("String s2: %s", s2);
getch();
}
Program to find the length of a string without using strlen()
#include <stdio.h>
void main()
{
char s[] = "Programming is fun";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
getch();
}
C Program to Concatenate Two Strings without using strcat()
#include <stdio.h>
#include<conio.h> // concatenate s2 to s1
void main() for (j = 0; s2[j] != '\0'; ++j, ++length) {
{ s1[length] = s2[j];
char s1[100] = "programming ", s2[] =
}
"is awesome"; // terminating the s1 string
int length, j; s1[length] = '\0';
// store length of s1 in the length
variable printf("After concatenation: ");
length = 0; puts(s1);
while (s1[length] != '\0') {
++length; return 0;
} }
C program to compare two for(i=0;(str1[i]!=‘\0’)||(str2[i]!=‘\0’));++i)
strings without strcmp() {
If(str1[i]==str2[i])
function flag=1;
#include <stdio.h> else If(str1[i]>str2[i])
#include <string.h> {
#include<conio.h> flag=0;
void main() printf(“str1 is alphabetically below str2”);
{ }
char str1[100], str2[100]; else
int i, flag; {
printf("\n Please Enter the First String : printf(“str1 is alphabetically above str2”);
");
gets(Str1); }
printf("\n Please enter the Second String }
: "); If (flag==1)
gets(Str2); printf(“strings are equal”);
getch();
}
Questions
• Write a program to read lines of text and print it.
• Write a program to convert lines of text in uppercase if the characters are
in lowercase.
• Program to find the number of lines, digits , alphabets and number of
characters in a text.
• Program to find the number of words in a text.
• Program to check if a string is palindrome or not.
• Program to sort strings in alphabetical order.
• Program to sort list of names without considering case sensitivity
• Program to count occurances of all words.
Questions
• Interchange a word with another word in a text.
• Find the largest word in a given text.
• Without using library function change a line of text to uppercase.
• Program to delete a particular word from a string.
• Enter two strings. Check whether the second string is the substring of
the first.
FUNCTIONS
• A function is a group of statements that together perform a task.
• Every C program has at least one function, which is main().
• We can divide up our code into separate functions (user defined
functions).
• How you divide up your code among different functions is up to you,
but logically the division is such that each function performs a specific
task.
• A function can also be referred as a method or a sub-routine or a
procedure, etc.
• The C standard library provides numerous built-in functions that your
program can call. For example, strcat()
• A function consists of three parts:
• Function definition: provides the actual body of the function.
• Function declaration: Tells the compiler about a function's name, return type,
and parameters
• Function call: to use a function, a function has to be called.
Function definition
• The general form of a function definition in C programming language is as follows
return_type function_name( parameter list )
{
body of the function
}
• A function definition in C programming consists of a function header and a
function body.
• All the parts of a function header are:
• Return type
• Function name
• Parameter list
Function Header and Function body
• 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.
• 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.
return result;
}
Function Declarations
• A function declaration tells the compiler about a function name and how
to call the function.
• A function declaration has the following parts
return_type function_name( parameter list );
• For the above defined function max(), the function declaration is as follows
int max(int num1, int num2);
• Parameter names are not important in function declaration only their type
is required, so the following is also a valid declaration
int max(int, int);
Calling a Function
• To use a function, you will have to call that function to perform the defined
task.
• To call a function, you simply need to pass the required parameters along
with the function name, and if the function returns a value, then you can
store the returned value.
printf( "Max value is : %d\n", ret );
Example: getch();
}
#include <stdio.h>
#include<conio.h>
int max(int num1, int num2)
/* function declaration */ {
int max(int num1, int num2);
void main () /* local variable declaration */
{ int result;
/* local variable definition */
int a = 100;
if (num1 > num2)
result = num1;
int b = 200;
else
int ret; result = num2;
/* calling a function to get max value */
ret = max(a, b); return result;
}
Local declarations and global declarations
• Local declarations:
• these declarations are made inside the functions.
• They are known only to functions inside which it is made.
• Global declarations:
• These declarations are made before main() function
• They are known to main() function and all the other user defined functions
used in the program.
C function argument and return values
• A function in C can be called either with arguments or without arguments.
• These function may or may not return values to the calling functions.
• There are following categories:
#include <stdio.h>
Case 1: Function #include<conio.h>
with no argument void mult (void)
and no return value int c,d;
void main()
{
When a function has no printf(enter the no.\n”);
arguments, it does not receive scanf(”%d%d”,&c,&d);
any data from the calling
mult();
function. Similarly when it
getch();
does not return a value, the
}
calling function does not
void mult(void)
receive any data from the
{
called function.
int e;
e= c*d;
printf (“product is %d”, e);
}
#include <stdio.h>
Case 2: Function with #include<conio.h>
arguments but no void mult (int a, int b)
return value void main()
{
When a function has
int c,d;
arguments, it receives the data
printf(enter the nos.\n”);
from the calling function but it
scanf(”%d%d”,&c,&d);
returns no values.
mult(c,d);
getch();
}
void mult(int a, int b)
{
int e;
e= c*d;
printf (“product is %d”, e);
}
#include <stdio.h>
Case 3: Function with #include<conio.h>
no arguments but int mult (void)
int c,d;
return a value
void main()
There could be occasions {
where we may need to int z;
design functions that may printf(enter the nos.\n”);
not take any arguments but scanf(”%d%d”,&c,&d);
returns a value to the calling z=mult(c,d);
function printf (“product is %d”, z);
getch();
}
int mult(void)
{
int e;
e= c*d;
return(e);
}
#include <stdio.h>
Case 4: Function with #include<conio.h>
arguments and return int mult (int a, int b);
void main()
values
{
These are functions that int c,d, z;
are designed to take data printf(enter the nos.\n”);
from the calling functions scanf(”%d%d”,&c,&d);
z=mult(c,d);
and also returns a value printf (“product is %d”, z);
to the calling function getch();
}
int mult(int a, int b)
{
int e;
e= a*b;
return(e);
}
Questions
• Program to find N𝐶𝑟
𝑥 𝑥2
• Program to calculate 1 + + +⋯
1! 2!
Recursion in C
• A function that calls itself in C is called recursion.
• Recursive functions are very useful to solve many mathematical
problems, such as calculating the factorial of a number, generating
Fibonacci series, etc.
• Through Recursion one can solve problems in easy way while its
iterative solution is very big .
• Recursive functions make use of stacks.
#include <stdio.h> Number Factorial using Recursion
#include<conio.h>
long int factorial(int i); STACK
void main() {
int i; Prod=2*factorial(1)=1
Return(prod=2!)
printf(“enter a value for i\n”); i=5
scanf(“%d”,&i);
printf("Factorial of %d is %d\n", i, factorial(i));120 Prod=3*fact(2)2
getch(); Return (prod=3!)
}
long int factorial(int i) 1
Prod=4*fact(3)6=24
{
Return(prod=4!)
int prod;
if(i <= 1) prod=5xfactorial(4)
return 1; prod=4xfactorial(3) =3!x4 Prod=5*fact(4)24
else prod=3xfactorial(2) =2!x3 Return(prod) 5! To main
()
prod= ( i * factorial(i – 1)); =1!x2
return(prod);
#include<stdio.h>
#include<conio.h> Program to reverse a line of text
putchar(k)
void reverse(void); Return to
void main() enter line
Putchar(r)
{ new york Return to
printf(“ënter line\n”); kroy wen
Putchar(o)
reverse(); Return to
getch();
Putchar(y)
} Return to
void reverse(void) Putchar( )
{ Return to
char c; Putchar(w)
If((c=getchar())!=‘\n’) Return to
reverse(); Putchar(e)
putchar(c); Return to
return; Putchar(n)
} Return to the calling function
Questions
• Write a program for binary search using recursion
• Print the first n natural nos. in reverse order
• Print Fibonacci numbers using recursion
• Find the sum of any n numbers using recursion
• Write a program in C to find the sum of digits of a number using
recursion.
• Write a program in C to count the digits of a given number using
recursion
• Write a program in C to convert a decimal number to binary using
recursion.
Passing Arrays to Functions
Single Dimensional Arrays
• The array should be followed by square bracket.
• No need to declare the size of the array in function declaration and function
definition
int search(int a[]);
• Mention only the name of the array in function call.
val=search(a);
Two dimensional Arrays
• We must mention the second dimension in function declaration and function
definition.
void read(int d[][5],int r, int s);
• Mention only the name of the array in function call.
QUESTIONS
• Program to find S.D. of a set of numbers with 2 functions, one to find mean
and other to find S.D.
• Program to sort array using function
• Program to find product of 2 matrices
𝑥 𝑥2
• Program to find 1 + + + ⋯ using two functions –one to find power
1! 2!
and another for factorial.
• Sum of upper triangle elements
• Sum of off diagonal and main diagonal elements
• Matrix symmetric or not using functions
• To arrange rows of array in ascending order
• Determinant of 3x3 matrix
POINTERS IN C
• A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location. Like any variable or
constant, you must declare a pointer before using it to store any
variable address. The general form of a pointer variable declaration is
type *var-name;
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
How to use pointers?
• There are a few important operations, which we will do with the help
of pointers very frequently.
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand.
The following example makes use of these
operations
#include <stdio.h>
void main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
#include <stdio.h>
void main ()
{
getch();
}
When the above code is compiled and executed, it produces the following result −The value of ptr is 0
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
POINTERS AND ARRAYS
• The array name stores the address of the first element of the array.
void main()
{
Int a[10];
here, the array name a contains the address of a[0] that is,a=&a[0]
a+1=&a[1]
a+2=&a[2]
a+3=&a[3] and so on
POINTERS AND ARRAYS
mark
Also, two variables of the same structure type can be copied in the same way as ordinary
variables.
bk1=bk2;
ARRAY OF STRUCTURES
• In array of structures, every element of the array is a structure.
• Array of structures can be declared as follows:
Struct stud
{ int roll;
int mark;
char name[10];
};
struct stud s[70];
S[70] is an array containing 70 elements where each element is a structure of type
stud.
Pointer to structures
• We can also define a pointer to a structure.
• Such pointers are called structure pointers.
Struct book
{
char name[25];
char author[25];
int pages;
int price;
};
struct book bk1,*ptr;
Here, ptr is a pointer to a structure of type book.
This means, ptr contains the address of a variable which is a structure of type book.
Pointer to structures
ptr= &bk1;
In such cases,
bk1.name=ptr->name
bk1.author=ptr->author
bk1.pages=ptr->pages
bk1.price=ptr->price
Passing structures to functions
Create a structure of customers in a bank with name, account number and
balance.
Call by value method
• Call by value method - copies the value of an argument(actual
parameter) into the formal parameter of that function.
• Therefore, changes made to the formal parameters in the function do
not affect the actual parameter of the main function.
• In this call by value method, values of actual parameters are copied to
function's formal parameters, and the formal parameters are stored
in different memory locations. So any changes made inside functions
are not reflected in actual parameters of the caller.
Call by reference method
• Call by reference method copies the address of an argument into the
formal parameter. In this method, the address is used to access the
actual argument used in the function call. It means that changes made
in the parameter alter the passing argument.
Does not allow you to make any changes in Allows you to make changes in the values of
Alteration of value
the actual variables. variables by using function calls.
Values of variables are passed using a Pointer variables are required to store the
Passing of variable
straightforward method. address of variables.
Value modification Original value not modified. The original value is modified.
Actual and formal arguments will be created Actual and formal arguments will be created
Memory Location
in different memory location in the same memory location
• The register storage class is used to define local variables that should be
stored in a register instead of RAM.
• This means that the variable has a maximum size equal to the register size
(usually one word)
• The static storage class instructs the compiler to keep a local variable
in existence during the life-time of the program instead of creating
and destroying it each time it comes into and goes out of scope.
• Therefore, making local variables static allows them to maintain their
values between function calls.
Fibonacci series using static function
void fib(int a,int b,int c)
{
#include<stdio.h> int sum;
#include<conio.h> static int i=2;
void fib(int a, int b,int n) sum=a+b;
{ a=b;
int f1=0,f2=2,n,’; b=sum;
clrscr(); i=i+1;
printf(ënter the limit\n”); printf(“%d”,sum);
printf(“%3d%3d”,f1,f2); If(i<c)
fib(f1,f2,n); fib(a,b,c);
} return;
}