PSP Module-3-Notes
PSP Module-3-Notes
MODULE-3
Prepared by:
CHANDANA D.C
Assistant professor
Dept. Of ISE
21PSP13 Module 3
ARRAYS
1. WHY DO WE NEED ARRAYS?
Arrays are used to represent multiple data items of the same type using single name.
2. DEFINITION OF ARRAYS
Properties of Array
Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
o 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
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 Linked List which we will learn later
3. TYPES OF ARRAYS
I. One-Dimensional Array:
A list of items can be given one variable name using only one subscript and such a variable is called as one
dimensional array.
Initialization of One-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. There are 4 different methods:
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[array_size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[3]={29.5, 30.7, 35.6};
In the declaration the array size will be set to the total number of initial values specified.
The compiler will set the size based on the number of initial values.
If we not specify the all the elements in the array, the unspecified elements will be
initialized to zero.
In such a case elements are initialized in the order from 0th element.
The remaining elements will be initialized to zero automatically by the compiler.
Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.
a) Initializing all the elements zero: If we want to store zero to all the elements in the array we can do.
Examples: int marks[4]={0};
e) String Initialization
Sequence of characters enclosed within double quotes is called as string.
The string always ends with NULL character (\0)
2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Example:
printf(“Enter 4 marks”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
Reading and writing single dimensional arrays.
To read array elements from keyboard we can use scanf() function as follows:
To read 0th element: scanf(“%d”,&a[0]);
To read 1st element: scanf(“%d”,&a[1]);
To read 2nd element: scanf(“%d”,&a[2]);
……
…….
To read nth element : scanf(“%d”,&a[n-1]);
In general
To read ith element:
Write a C program to read N elements from keyboard and to print N elements on screen.
#include <stdio.h>
void main()
{
int a[10],i,n;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\nElements in array are: ");
for(i=0;i<n;i++)
{
printf("%d ", a[i]);
}
}
Output
Enter size of array: 5
Enter 5 elements in the array : 3 7 5 6 7
Elements in array are: 3 7 5 6 7
#include <stdio.h>
void main()
{
int a[10],i,n, big;
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\nElements in array are: ");
big=a[0];
for(i=0;i<n;i++)
{
if(a[i]>big)
big=a[i];
}
printf(" big %d ",big);
}
OUTPUT
Enter size of array: 5
Enter 5 elements in the array : 12 45 7 1 7
Elements in array are: big 45
#include <stdio.h>
void main()
{ int fib[24];
int i,n;
printf("Enter size of array: ");
scanf("%d",&n);
fib[0] = 0;
fib[1] = 1;
for(i = 2; i < n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for (i = 0; i < n; i++)
{
printf("%d \t", fib[i]);
}
}
OUPUT
OUT PUT
Enter degree of the polynomial X :: 3
Enter coefficient's of the polynomial X ::
Enter Coefficient of [ X^3 ] :: 1
Enter Coefficient of [ X^2 ] :: 3
Enter Coefficient of [ X^1 ] :: 2
Enter Coefficient of [ X^0 ] :: 5
Enter the value of X :: 4
Value of the polynomial is = [ 125.000000 ]
Declaration of Two-Dimensional Array: Here is general syntax for array declaration along with examples.
Initialization of Two-Dimensional Array: After array is declared, next is storing values in to an array is
called initialization. There are two types of array initialization:
1. Compile-time initialization
2. Run-time initialization
1. Compile time initialization: If we assign values to the array during declaration it is called compile
time initialization. Following are the different methods of compile time initialization.
1 2 3 4 29.5 30.5
marks city_temp
35.6 45.7
5 6 7 8
2. Run time initialization: Run time initialization is storing values in an array when program is
running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);
for(i=0; i<3; i++)
for(j=0;j<3;j++)
{
scanf(“ %d”, &marks[i][j]);
}
More Examples: Other way of initialization:
int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};
int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};
012 1234
a b
345 5678
67 8 9 10 11 12
III. Multi-Dimensional Array: It can have 3, 4 or more dimensions. A three dimensional array is an
array of 2D arrays. It has row, columns, depth associated with it.
NOTE:
USING ARRAYS WITH FUNCTIONS:
In large programs that use functions we can pass Arrays as parameters. Two ways of passing arrays to
functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter
#include<stdio.h> #include<stdio.h>
int square(int); int sum(int [ ]);
#include<stdio.h>
void main()
{
int m, n , i, j , a[3][3];
printf(“Enter number of Rows and Columns\n”);
scanf(“%d %d”, &m, &n);
printf(“Enter array Elements\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”, &a[i][j]);
}
}
printf(“Array Elements are\n”);
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
}
big = a[0][0];
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
{
if(big > a[i][j])
big = a[i][j];
}
}
printf(“Big is %”, big);
}
if(n!=p)
{
printf("Matrix multiplication is not possible\n");
exit(0);
}
printf("Enter the elements of matrix A\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < n; j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of matrix B\n");
}
for(i=0 ; i < m ; i++)
{
for(j=0 ; j < q ; j++)
{
c[i][j] = 0;
for(k=0;k<n;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
printf("Matrix A is\n");
for(i = 0 ; i < m; i++)
{
for(j = 0 ; j < n; j++)
{
printf("%d\t",a[i][j]);
}
#include <stdio.h>
void main()
{
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
// asssigning elements to the matrix
printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
1. Linear Search:
• Linear search also called sequential search is a simple searching technique.
• In this technique we search for a given key item in linear order i.e,one after the other from first
Element to last element.
• The search may be successful or unsuccessful.
• If key item is present, the search is successful, otherwise unsuccessful search.
2. Binary Search:
• Binary search is a simple and very efficient searching technique which can be applied if the items are
Arranged in either ascending or descending order.
• In binary search first element is considered as low and last element is considered as high.
• Position of middle element is found by taking first and last element is as follows.
mid=(low+high)/2
• Mid element is compared with key element, if they are same, the search is successful.
• Otherwise if key element is less than middle element then searching continues in left part of the array.
• If key element is greater than middle element then searching continues in right part of the array.
• The procedure is repeated till key item is found or key item is not found.
• Note: Elements in the array Need to in Sorted Order otherwise Binary Search is not
Going to work properly
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a[20],low,mid,high,i,n,k;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("%d\n",n);
printf("Enter the elements\n");
for(i = 0 ; i < n ; i++)
scanf("%d",&a[i]);
printf("Enter the element to be searched\n");
scanf("%d",&k);
low = 0;
high = n - 1;
while(low <= high)
{
mid = (low + high)/2;
if(a[mid] == k)
{
printf("Successful search, element %d found at %d\n",k,mid+1);
exit(0);
}
else if(a[mid] > k)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
printf("Unsuucessful search\n");
SORTING
SORTING: It is the process of arranging elements in the list according to their values in ascending or
descending order. A sorted list is called an ordered list.
Ex: Bubble Sort, Selection Sort, Insertion Sort, Shell Sort, Merge Sort, Quick Sort.
1. Bubble Sort
This is the simplest and easiest sorting technique.
In this technique two successive elements of an array such as a[j] and a[j+1] are compared.
If a[j]>=a[j+1] the they are exchanged, this process repeats till all elements of an array are arranged in
ascending order.
After each pass the largest element in the array is sinks at the bottom and the smallest element in the array
is bubble towards top. So this sorting technique is also called as sinking sort and bubble sort.
2. Selection Sort
It is an another technique for Sorting the elements in the array
Here it considers the first element as minimum
It Compares the Next Element with the Minimum Position Element
If it is less than the Minimum Position Element it changes the default position of minimum to current
Minimum value position.
Whereas in bubble sort it was comparing the neighbor elements and swap was taking place but in
Selection sort swap happens from maximum value to the minimum value.
o It reduces the Number of swap time
Selection sort will start by comparing the first element with other elements and finds minimum element and
swaps, then it starts comparing by taking second element with other elements and so on.
#include<stdio.h>
void main( )
{
int n, a[100], i, j, temp, pos;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter elements of array\n");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if( a[pos]>a[j])
pos=j;
}
if(pos !=i )
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
}
printf("The sorted array is\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
STRINGS
1. INTRODUCTION
A group of characters together is called String.
String is always enclosed within double quotes (“ “)
String always ends with delimiter (NULL – ‘\0’ )
Ex: a = “CBIT”
Operations on string:
3. INITIALIZATION OF A STRING
Syntax: data_type string_name[size] = value;
Example: The String can be initialized in two ways:
i. char name[30] = “SUVIKA”;
ii. char name[30] = {‘S’, ‘U’, ‘V’, ‘I’, ‘K’, ‘A’, ‘\0’};
NOTE:
i. char a[2] = “CPPS”;
The above initialization is invalid because, the size is less.
ii. char a[5];
a = “CPPS”;
The above initialization is invalid because, in string the declaration and initialization should
be done together.
4. LIMITATION OF STRINGS
One string variable cannot be directly assigned to another variable as shown below:
char name1[10] = “Hello”;
While reading strings we need not specify address operator because, character array itself is an
address.
NOTE:
It is used to specify the type of character that can be accepted by scanf function.
Ex 1: char name[20];
scanf(“%[0123456789]”, name);
Ex 2: char name[20];
scanf(“%[^0123456789]”, name);
Example 2 specifies that it accepts only alphabets, special symbols, space but it does not accept any
number.
Ex 3: char name[20];
scanf(“%[A-Z]”, name);
ii. Writing/Printing a String: We can use print function with %s format specifier to print a string. It
prints the character until NULL character.
Output:
S U V I K A
S U V
S U V
A program illustrating strings or char arrays, accept your name and print it
#include<stdio.h>
#include<conio.h>
main()
{
char name[10];
printf("\n Enter Your name");
scanf("%s", name);
printf("\n Your name is %s", name);
}
C library supports a large number of string handling functions that can be used to carry out many of
string manipulation and are stored in header file <string.h>
There are mainly 6 string handling functions:
It is possible to assign the value to a string variable using strcpy( ). It allows us to copy one string
from one location to another.
The string length function can be used to find the length of the string in bytes.
String length function has one parameter str which is a string. It returns an integer value.
It is used to compare two strings. It takes the two strings as a parameter and returns an integer
value.
Syntax: result = strcmp(first, second);
It is used to concatenate or join two strings together. It has two parameters where the combined
string will be stored in the (destination) first parameter.
Note: strcat( ) stops copying when it finds a NULL character in the second string.
int len=0;
clrscr();
printf(“Enter the First String \n”);
scanf(“%s”, str1);
printf(“Enter the Second String \n”);
scanf(“%s”, str2);
printf(“Concatenated String=%s \n”, strcat(str1,str2);
getch();
}
It compares upto specify number of characters from the two strings and returns integer value.
This function allows us to extract a substring from one string and copy it to another location.
The strncpy( ) takes three parameters. It copies the number of characters (numchars) from source
string to destination string.
Since, numchars doesn’t include NULL character we have to specify explicitly.
A program to illustrate the use of string upper strupr() and string lower strlwr() functions
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char str1[10], rev[10];
int len=0;
clrscr();
printf(“Enter the String \n”);
scanf(“%s”, str1);
printf(“Upper String =%s \n”, strupr(str1));
printf(“Lower String=%s \n”, strlwr(str1);
getch();
}
Write functions to implement string operations such as compare, concatenate, string length. Convince
the parameter passing techniques
#include<stdio.h>
#include<string.h>
void stringlength(char a[100],char b[100]);
void concatenate(char a[100],char b[100]);
void stringcompare(char a[100],char b[100]);
void main()
{
char p[100],q[100],ch[100];
int len1,len2;
printf("Enter the first string:\n");
gets(p);
printf("Enter the second string:\n");
gets(q);
stringlength(p,q);
stringcompare(p,q);
concatenate(p,q);
}
void stringlength(char a[100], char b[100])
{
int len1,len2;
len1=strlen(a);
len2=strlen(b);
7. ARRAY OF STRINGS
It is an array of 1D character array which consists of strings as its individual elements.
Write a program to check whether a given string is palindrome or not. (without using any built-in string
function
#include <stdio.h>
#include <string.h>
int main(){
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
if (flag) {
printf("%s is not a palindrome", string1);
}
else {
printf("%s is a palindrome", string1);
}
return 0;
}
Write a ‘C’ function to count the number of vowels and consonants in a string.
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000];
int i,vowels=0,consonants=0;
printf("Enter the string : ");
gets(s);
for(i=0;s[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
{
QUESTION BANK
1 What is an array? How a s ingle dimension and two dimension arrays are declared and initialized?
8M
2 Write a C program that reads N integer numbers and arrange them in ascending order using
selection Sort. Trace the steps for the input: 9, 1, 6, 3, 2, 0, 5 10M
3 Write a C program to search an integer from N numbers in ascending order using binary searching
technique 6M
4 Write a ‘C’ program to implement matrix multiplication and ensure if the rules for multiplication
are checked. 8M
5 Write a ‘C’ Program to read N numbers into an array & perform Linear search 5M
6 Write a ‘C’ program to find the sum of rows and sum of columns of a matrix 5M
7 Write a C program to input N integers in a single dimensional array & sort them in ascending order
using bubble sort. 6M
8 Explain searching, and techniques to implement searching. List their advantages and disadvantages
8M
11 For a array declared as int a[50], compute the address of a[35] if a’s base address is 1000 and
word size=2. 2M CO3
12 How 1D and 2D integer arrays are represented in memory? Explain with the help of suitable
example the declaration and initializing the array elements. 10M
Strings (module 3)
14 Write a program to check whether a given string is palindrome or not. (without using any built-in
string function). 5M
15 Write a ‘C’ function to count the number of vowels and consonants in a string. 5M
#include<stdio.h>
void main( )
{
int m, n, I, j, a[100][100], t[100][100];
printf(“Enter the order of matrix\n”);
scanf(“%d%d”, &m, &n);
printf(“Enter the elements of matrix\n”);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
scanf(“%d”, &a[i][j]);
for(i=0; i<m; i++)
for(j=0; j<n; j++)
t[j][i] = a[i][j];
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf(“%d”, t[i][j]);
}
printf(“\n”);
}
}
2 WACP to copy a string (combination of digits and alphabets) to another string (only alphabets).
#include<stdio.h>
#include<ctype.h>
void main()
{
char s1[100], s2[100];
int i=0, j=0;
printf("Enter String1\n");
scanf("%s",s1);
while(s1[i] != '\0')
{
if(isalpha(s1[i]))
{
s2[j] = s1[i];
j++;
}
i++;
}
s2[j] = '\0';
printf("The copied string is %s\n", s2);
}
#include<stdio.h>
void main()
{
#include<stdio.h>
void main()
{
char s1[100], s2[100];
int i=0, j=0;
printf("Enter String1\n");
scanf("%s", s1);
printf("Enter String2\n");
scanf("%s", s2);
while(s1[i] != '\0')
i++;
while(s2[j] != '\0')
{
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0';
printf("The concatenated string is %s", s1);
}
******************"If you want to shine like a sun, first burn like the sun."*****************