PSPC - Unit-3
PSPC - Unit-3
PSPC - Unit-3
Concepts:
Arrays and Strings: Arrays: One-Dimensional Arrays, Declaration, Array Initialization, Input and Output of Array
Values, Two- Dimensional Arrays.
Strings: String Fundamentals, String Input and Output, String manipulation functions.
What is an 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.
The Array is the simplest data structure where each data element can be randomly accessed by using
its index number.
Important terms to understand the concept of array:
Element
Index
data_type array_name[Size];
We can create an array with size and also initialize values to it.
In the above syntax, the data type specifies the type of values we store in that array and size specifies the maximum
number of values that can be stored in that array.
For example:
float mark[5];
Here, we declared an array called mark, of floating-point type and its size is 5. Meaning, it can hold 5
floating-point values.
int a[3];
In the above memory allocation, all the three memory locations have a common name 'a'. So accessing
individual memory location is not possible directly. Hence compiler not only allocates the memory but also
assigns a numerical reference value to every individual memory location of an array. This reference number is
called "Index" or "subscript" or "indices". Index values for the above example are as follows...
It is not necessary to define the size of array during initialization. We can also initialize the size of an
array like this:
int marks[]={80,60,70,85,75};
The above example tells that memory is allocated at run time based on the number of elements given
in an array. This is another approach to initialize an array.
The number of elements in the initialization list should be less than the size of array because index is
starts with 0.
If the array size is greater than the list of elements in the array, then it first allocate memory for the
int marks[5]={10,20,30};
marks[0] marks[1] marks[2] marks[3] marks[4]
10 20 30 0 0
If the array elements are greater than the array size, then it shows compilation error.
int age[4]={1,2,3,4,5} // ERROR
Example:
The elements can be accessed from an array with help of index values.
Suppose declare an array mark with int data type followed by some size i.e. int mark[5];
The first element is accessed with mark[0], the second element is mark[1] and so on.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int mark[5]={10,20,30,40,50};
th
mark[ [0]); element i.e. 10
mark[ [1]); 1st element i.e. 20
mark[ [2]); 2nd element i.e. 30
mark[ [3]); 3rd element i.e. 40
mark[ [4]); 4th element i.e. 50
getch( );
}
for(i=0;i<n;i++)
{
for(i=0;i<n;i++)
{
print \ a[i]);
}
}
2. Two dimensional Array (2D) or Multidimensional array:
An array of arrays is called as 2D or multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two
dimensional array or three dimensional array or four dimensional array or more. Most popular and
commonly used multi dimensional array is two dimensional array. The 2-D arrays are used to store data in the form
of table. We also use 2-D arrays to create mathematical matrices.
We use the following general syntax for declaring a two dimensional array...
int array1[2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes each in the
form of 2 rows and 3 columns.
Example:
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes each in the
form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and second row is
initialized with values 4, 5 & 6.
We can also initialize as follows...
Example:
int array1[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
(OR)
Another way to initialize value into an array:
int a[2][2];
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
Example :
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[2][2],i;
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
for(i=0;i<2;i++)
{
\
for(j=0;j<2;j++)
{
\
}
}
getch();
}
Example :
#include<stdio.h>
#include<conio.h>
Void main()
{
int a[2][3]={ {1,2,3},{4,5,6}};
int i,j;
for(i=0;i<2;i++) //for rows
{
for(j=0;j<3;j++) //for columns
{
\
}
}
getch();
}
STRINGS
Strings Introduction:
Strings are defined as an array of characters. The difference between a character array and a string
\
The termination character ('\0') is important in a string since it is the only way to identify where
the string ends.
When we define a string as char s[10], the character s[10] is implicitly initialized with the null in
the memory.
Declaration of a String:
Declaring a string is as simple as declaring a one-dimensional array.
Syntax for declaring a string:
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to define the
length of the string.
Example: char str[10];
Initialization of a string:
A string can be initialized in different ways:
1. char str[]
Here, size is not mentioned so that it will automatically allocate memory at run time and
\
2.
3. char str[] = {'w', 'e', 'l', 'c', 'o', 'm', 'e','\0'};
4. char str[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e','\0'};
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str1
char str2
char str3[] = {'w', 'e', 'l', 'c', 'o', 'm', 'e','\0'};
char str4[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e','\0'};
, str2);
, str3);
, str4);
getch();
}
Output:
welcome
welcome
welcome
welcome
Input Functions:
scanf function
gets function:
getchar function
Output functions:
printf function
puts function
putchar function
The getchar() function reads the next available character from the screen and returns it as an integer. This
function reads only single character at a time. You can use this method in the loop in case you want to read
more than one character from the screen.
The putchar() function puts the passed character on the screen and returns the same character. This function
puts only single character at a time. You can use this method in the loop in case you want to display more
than one character on the screen. Check the following example
Example
#include<stdio.>
void main( )
{
char c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a
text and press enter, then the program proceeds and reads only a single character and displays it as
Output:
Enter a value: welcome
You entered: w
Example:
#include <stdio.h>
void main( )
{
char str[100];
printf( "Enter a string :");
gets( str );
printf( "\n The string is: %s", str);
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and
press enter, then the program proceeds and reads the complete line till end, and displays it as follows:
Output:
Enter a string : welcome to c
The string is: welcome to c
The puts() function is very much similar to printf() function. The puts() function is used to print the
string on the console which is previously read by using gets() or scanf() function.
Example:
#include<stdio.h>
#include <string.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
getch();
}
Output:
Enter your name: welcome to c program
Your name is: welcome to c program
The scanf() function reads the input from the standard input stream stdin and scans that input
according to the format provided.
entered into an array according to base address.
The printf() function writes the output to the standard output stream stdout and produces the
output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print
or read strings, integer, character or float respectively. There are many other formatting options
available which can be used based on requirements.
Let us now proceed with a simple example to understand the concepts better
#include <stdio.h>
void main( )
{
char
str[100];
printf( "Enter a string :");
);
printf( "\nYou entered: %s", str);
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it as follows
Output 1:
Output 2:
Enter a string: Hello World
You entered: Hello
Here, while reading a string, scanf() stops reading as soon as it encounters a space, so "Hello World" are two strings for
scanf().
String manipulation functions/library functions/pre defined functions/built-
in functions:
1. String length::strlen()
2. String copy::strcpy()
3. String concatenation::strcat();
4. String reverse::strrev()
5. String comparison::strcmp()
6. String upper :: strupr()
7. String lower::strlwr()
Output:
Enter string hello world
String length= 11
String copy: strcpy( )
String copy function copies contents of one string into another string.
Syntax for strcpy( ) function is given below:
strcpy ( destination, source );
Example:
strcpy (str1,str2) It copies contents of str2 into str1.
strcpy ( str2, str1) It copies contents of str1 into str2.
destination string.
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20];
char str2[20];
printf("Enter a string1");
gets(str1);
strcpy(str2,str1);
printf("The copied string is=%s",str2);
}
Output:
Enter a string1 vignan
The copied string is=vignan
character is added at the end of new destination string which is created after strcat( ) operation
Example:
#include <stdio.h>
#include <string.h>
void main( )
{
char string1[ 20] ;
char string2[20];
printf ( "\n enter string1 :" ) ;
gets(string1);
printf ( "enter string2:") ;
gets(string2);
strcat( string1,string2);
printf ( "The string after concatenation= %s", string1);
}
Output:
Enter string1: vignan
Enter string2: institute
The string after concatenation=vignaninstitute
#include<stdio.h>
#include<string.h>
void main()
{
char name[30] = "Hello";
printf("String before reverse : %s\n", name);
strrev(name);
printf("String after reverse : %s", name);
}
Output:
Example:
#include <stdio.h>
#include <string.h>
void main( )
{
char str1[50] = "abcd" ;
char str2[50] = "abCd";
char str3[50] = "abcd";
int res;
res = strcmp ( str1, str2 ) ;
printf("%d \n", res);
res = strcmp ( str1, str3 ) ;
printf ("%d ", res ) ;
getch();
}
Output:
32
0
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char str[ ] = "vignan";
strupr(str);
printf("%s", str);
getch();
}
Output:
VIGNAN
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char str[ ] = "VIGNAN";
strlwr(str);
printf("%s", str);
}
Output:
vignan
String manipulation functions without using built-in functions:
1. string length:
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[50];
gets(str);
int i, length=0;
for(i=0; \ ;i++)
{
length++;
}
getch();
}
Output:
Enter a string= hello world
the length of the string is=11
2. string copy:
#include<stdio.h>
#include<conio.h>
void main( )
{
char str[50],str1[50];
printf("Enter a string=");
gets(str);
int i;
for(i=0; str[i]!= '\0'; i++)
{
str1[i]=str[i];
}
str1[i]='\0';
printf(" copied string is=%s",str1);
getch();
}
Output:
Enter a string=vignan
copied string is=vignan
3. string comparison:
#include<stdio.h>
Void main()
{
char str[50], str2[50];
int i;
gets(str1);
gets(str2);
for(i=0; str1[i]!='\0' \ ; i++)
{
if(str[i]!=str2[i])
break;
}
printf("Comparison result=%d",str1[i]-str2[i]);
getch();
}
Output:
Enter string1 and string2 : ABCD
ABCD
Comparison result=0
4. string concatenation:
#include <stdio.h>
void main()
{
char str1[20], str2[20];
int i, length=0;
p );
gets(str1);
gets(str2);
for(i=0;str1[i] != '\0';i++)
{
length++;
}
for(i=0;str2[i] != '\0';i++)
{
str1[length+i]=str2[i];
}
str1[length+i] = '\0';
printf("\nConcatenated string: %s", str1);
}
Output:
Enter string 1 and string 2: welcome
vignan
Concatenated string: welcomevignan
5. string upper:
#include <stdio.h>
void main()
{
char str1[20];
int i=0;
printf("Enter string
gets(str1);
while(str1[i] != '\0')
{
{
Str1[i]=str1[i]-32;
}
i++;
}
getch();
}
Output:
Enter string: hello world
Upper case letter is: HELLO WORLD
6. string lower:
#include <stdio.h>
void main()
{
char str1[20];
int i=0;
printf("Enter str
gets(str1);
while(str1[i] != '\0')
{
A )
{
Str1[i]=str1[i]+32;
}
i++;
}
Lower
getch();
}
Output:
Enter string: HELLO WORLD
Lowercase letter is: hello world
Programs on Arrays
1. Write a C program to read and print array elements
Program:
#include<stdio.h>
void main()
{
int a[10], n, i;
for(i=0;i<n;i++)
{
for(i=0;i<n;i++)
{
print \ a[i]);
}
}
Output:
Enter the number of elements= 5
Read the elements:1
2
3
4
5
The elements are:
12345
for(i=0;i<n;i++)
{
Output:
for(i=0;i<n;i++)
{
}
reverse of an array is
for(i=n-1;i>=0;i--)
{
\
}
}
Output:
Enter the number of elements= 5
Read the elements:1
2
3
4
5
The reverse of an array is= 5 4 3 2 1
for(i=0;i<n;i++)
{
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
The sum of an array is=%d\ );
}
Output:
Enter the number of element: 4
Read the elements=10
20
30
40
The sum of an array is=100
the elements =
for(i=0;i<n;i++)
{
}
min=a[0],max=a[0];
for(i=0;i<n;i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
Minimum of array is=%d\ min);
Maximum of array is=%d\ max);
getch();
}
Output:
Enter the number of elements: 5
Enter the elements: 80
25
45
77
9
The Minimum of array is=9
The Maximum of array is =80
6. Write a C program to perform Linear Search:
Program :
#include<stdio.h>
void main()
{
int a[10],i,n,count=0,key;
printf("enter number of elements=");
scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter key value");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
count++;
}
}
if(count==1)
{
printf("elements is found");
}
else
{
printf("elements not found");
}
getch();
}
Output:
enter number of elements=5
enter elements=55
44
8
52
74
enter key value 52
elements found
Output:
enter number of row and columns=2 2
enter elements=10
20
30
40
the matrix is:
10 20
30 40
the transpose of a matrix
10 30
20 40
8. Write a C program to read and print a matrix
Source code:
#include<stdio.h>
void main()
{
int a[20][20],m,n,i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
}
}
\
for(i=0;i<m;i++)
{
\
for(j=0;j<n;j++)
{
\
}
}
Output:
scanf( );
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
two matrix is:\
for(i=0;i<c;i++)
{
for(j=0;j<c;j++)
{
\
}
\
}
}
Output:
10 12
Source code:
#include<stdio.h>
void main()
{
int a[10],i,n,count=0,key,low,high,mid;
printf("enter number of elements=");
scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter key value");
scanf("%d",&key);
low=0,
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key<a[mid])
{
high=mid-1;
}
if(key>a[mid])
{
low=mid+1;
}
if(key==a[mid])
{
count++;
break;
}
}
if(count==1)
else
Output:
Enter the number of elements:5
Enter the elements: 10
20
30
40
50
Enter key value: 40
Element is found
12. Write a c program to print the list of elements in a sorted order (bubble sort)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,j,n,temp;
printf("enter number of elements=");
scanf("%d",&n);
printf("enter elements=");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
p
for(i=0;i<n;i++)
{
printf("%d\t",&a[i])
}
getch();
}
Output:
Enter no of elements: 5
Enter elements: 10
50
30
40
20
After sorting: 10 20 30 40 50
Programs on Strings
Output:
Enter the string: vignan
Reverse string is : nangiv
2. Write a C program to check whether a string is palindrome or not.
Source code:
#include<stdio.h>
#include<string.h>
void main() {
char str[100];
int i,j,len=0;
printf("\nEnter the string :");
gets(str);
for( \ ++)
{
len++;
}
i = 0;
j = len-1;
while (i<j)
{
if(str[i]! = str[j])
{
break;
}
i++;
j--;
}
if(i>=j)
{
pri );
}
else
{
}
getch();
}
Output:
Enter the string: madam
madam is a palindrom
Output 2:
Enter the string: hai
Given string is not a palindrom