0% found this document useful (0 votes)
7 views45 pages

C Unit Iii

Uploaded by

shuklaaakash089
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)
7 views45 pages

C Unit Iii

Uploaded by

shuklaaakash089
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/ 45

01/11/2022

UNIT - III
Arrays: Array notation and representation, Declaring one-
dimensional array, Initializing arrays, Accessing array elements,
Manipulating array elements, Arrays of unknown or varying size,
Two-dimensional arrays, Multidimensional arrays.
PROBLEM SOLVING USING C Pointers: Introduction, Characteristics, * and & operators, Pointer
type declaration and assignment, Pointer arithmetic, Call by
KCA102 reference, Passing pointers to functions, array of pointers, Pointers
UNIT-III to functions, Pointer to pointer, Array of pointers.
MCA I YEAR, I SEM. Strings: Introduction, Initializing strings, Accessing string elements,
Array of strings, Passing strings to functions, String functions.

UNITED INSTITUTE OF MANAGEMENT, NAINI MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

1
01/11/2022

What is an Array?
Example of an Array:
So far we have used only single variable name for storing one
data item. If we need to store multiple copies of the same data
then it is very difficult for the user. To overcome the difficulty a Suppose we have to store the roll numbers of the 100
new data structure is used called arrays. students the we have to declare 100 variables named
as roll1, roll2, roll3, ……. roll100 which is very difficult
 An array is a linear and homogeneous data structure. job. Concept of C programming arrays is introduced in
 An array permits homogeneous data. It means that similar C which gives the capability to store the 100 roll
types of elements are stored contiguously in the memory numbers in the contiguous memory which has 100
under one variable name. blocks and which can be accessed by single variable
 An array can be declared of any standard or custom data name.
type.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

2
01/11/2022

Conti… Pictorial representation of C Programming Arrays

1. C Programming Arrays is the Collection of


Elements
2. C Programming Arrays is collection of the
Elements of the same data type.
3. All Elements are stored in the Contiguous
The above array is declared as int a [5];
memory a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
4. All elements in the array are accessed using In the above figure 4, 5, 33, 13, 1 are actual data
the subscript variable (index). items and 0, 1, 2, 3, 4 are index variables.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

3
01/11/2022

Index or Subscript Variable What is Contiguous Memory?


1. Individual data items can be accessed by the name 1. When Big Block of memory is reserved or allocated
of the array and an integer enclosed in square bracket then that memory block is called as Contiguous
called subscript variable / index . Memory Block.
2. Subscript Variables helps us to identify the item 2. Alternate meaning of Contiguous Memory is
number to be accessed in the contiguous memory. continuous memory.
3. Suppose inside memory we have reserved 1000-
1200 memory addresses for special purposes then we
can say that these 200 blocks are going to reserve
a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1; contiguous memory.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

4
01/11/2022

Contiguous Memory Allocation


1. Two registers are used while implementing the
contiguous memory scheme. These registers are base
register and limit register.
2. When OS is executing a process inside the main
memory then content of each register are as

Here diagram 1 represents the contiguous allocation of


memory and diagram 2 represents non-contiguous
allocation of memory.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

5
01/11/2022

How to allocate contiguous memory? Array Declaration

1. Using static array declaration. Syntax:


2. Using alloc ( ) / malloc ( ) function to allocate big <data type> array name [size1][size2].....[sizen];
chunk of memory dynamically.
Syntax Parameter Significance
Data type Data Type of Each Element of the array

Array name Valid variable name


Size Dimensions of the Array

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

6
01/11/2022

Continue… Initialization of C Array

int marks[5]; marks[0]=80;//initialization of array


marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

7
01/11/2022

C array example C Array: Declaration with Initialization


#include<stdio.h>
void main(){
int i=0;
Example1-
int marks[5];//declaration of array int marks[5]={20,30,40,50,60};
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70; Example2-
marks[3]=85; int marks[]={20,30,40,50,60};
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

8
01/11/2022

Example1- Example2- User Input


#include<stdio.h>
#include<stdio.h> void main()
void main(){ {
int i=0; int arr [3];
for(int i=0;i<3;i++)
int marks[5]={20,30,40,50,60};//declaration and initiali {
zation of array printf("Enter array value\t");
scanf("%d",&arr[i]);//input array value
//traversal of array }
for(i=0;i<5;i++){ for(int i=0;i<3;i++)
printf("%d \n",marks[i]); {//output array value
printf("Value of array is %d \n",arr[i]);
} }
}
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

9
01/11/2022

Example3- Advantages of Array:


1- Arrays represent multiple data items of the same type using a
#include <stdio.h> single name.
void main ()
{
2. In arrays, the elements can be accessed randomly by using
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
the index number.
for ( i = 0; i < 10; i++ )
{ 3. Arrays allocate memory in contiguous memory locations for
n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output all its elements. Hence there is no chance of extra memory
each array element's value */ being allocated in case of arrays. This avoids memory overflow
for (j = 0; j < 10; j++ ) or shortage of memory in arrays.
{
printf("Element[%d] = %d\n", j, n[j] );
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

10
01/11/2022

Continue… Disadvantages of Arrays:


1- The number of elements to be stored in an array should be
4- Using arrays, other data structures like linked lists, stacks, known in advance.
queues, trees, graphs etc can be implemented.

5. Two-dimensional arrays are used to represent matrices. 2- An array is a static structure (which means the array is of
fixed size). Once declared the size of the array cannot be
modified. The memory which is allocated to it cannot be
increased or decreased.

3- Insertion and deletion are quite difficult in an array as the


elements are stored in consecutive memory locations and the
shifting operation is costly.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

11
01/11/2022

Continue… Applications of Arrays:

4- Allocating more memory than the requirement leads to 1- Arrays can be used for CPU scheduling.
wastage of memory space and less allocation of memory also
leads to a problem. 2-Arrays can be used for performing matrix
operations. Many databases, small and large, consist of one-
dimensional and two-dimensional arrays whose elements
are records.

3- Lastly, arrays are also used to implement other data structures


like Stacks, Queues, Heaps, Hash tables etc.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

12
01/11/2022

Assignment: Example1- Array in Reverse Order.


#include <stdio.h>
1- Write a program in C to read n number of values in an array void main()
and display it in reverse order. {
int i,n,a[100];
2. Write a program in C to find the sum of all elements of the printf("\n\nRead n number of values in an array and display it in reverse
array. order:\n");
printf("------------------------------------------------------------------------\n");
3. Write a program in C to find the maximum and minimum printf("Input the number of elements to store in the array :");
element in an array. scanf("%d",&n);

printf("Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

13
01/11/2022

Continue… Example2- Find Min & Max Element in an Array.


#include <stdio.h>
void main()
printf("\nThe values store into the array are : \n"); {
for(i=0;i<n;i++) int arr1[100];
int i, mx, mn, n;
{
printf("% d",a[i]); printf("\n\nFind maximum and minimum element in an array :\n");
} printf("--------------------------------------------------\n");

printf("Input the number of elements to be stored in the array :");


printf("\n\nThe values store into the array in reverse are :\n"); scanf("%d",&n);
for(i=n-1;i>=0;i--)
printf("Input %d elements in the array :\n",n);
{ for(i=0;i<n;i++)
printf("% d",a[i]); {
} printf("element - %d : ",i);
scanf("%d",&arr1[i]);
printf("\n\n"); }
} mx = arr1[0];
mn = arr1[0];

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

14
01/11/2022

Continue… Example3- Sum of Array Elements:


#include <stdio.h>
for(i=1; i<n; i++)
{
if(arr1[i]>mx) void main()
{ {
mx = arr1[i];
} int a[100];
int i, n, sum=0;
if(arr1[i]<mn)
{
mn = arr1[i]; printf("\n\nFind sum of all elements of array:\n");
} printf("--------------------------------------\n");
}
printf("Maximum element is : %d\n", mx);
printf("Minimum element is : %d\n\n", mn); printf("Input the number of elements to be stored in the
} array :");
scanf("%d",&n);

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

15
01/11/2022

Conti…
Declaration of 2D Array in C:
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i); data_type array_name[rows][columns];
scanf("%d",&a[i]);
} int a[4][3];
for(i=0; i<n; i++)
{
sum += a[i];
}

printf("Sum of all elements stored in the array is : %d\n\n",


sum);
}
UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

16
01/11/2022

Initialization of 2D Array in C: 2D array example in C:


#include<stdio.h>
void main(){
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

17
01/11/2022

Output- Example- Addition of two Matrix 2x2


arr[0][0] = 1
arr[0][1] = 2 #include<stdio.h>
arr[0][2] = 3 void main()
{
arr[1][0] = 2
float a[2][2], b[2][2],c[2][2];
arr[1][1] = 3 int i,j;
arr[1][2] = 4 printf(" enter the elements of first matrix\n");
arr[2][0] = 3 for(i=0;i<2;i++)
arr[2][1] = 4 {
arr[2][2] = 5 for(j=0;j<2;j++)
{
arr[3][0] = 4
printf("Enter a%d%d",i+1;j+1");
arr[3][1] = 5 scanf("%f",&a[i][j]);
arr[3][2] = 6 }
}
UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

18
01/11/2022

Continue… Continue…

printf("Enter the elements of 2nd matrix"); for(i=0;i<2;i++)


for(i=0;i<2;i++) {
{ for(j=0;j<2;j++)
for(j=0;j<2;j++) {
{ c[i][j]=a[i][j]+b[i][j];
printf("Enter b%d%d",i+1;j+1); }
scanf("%f",&b[i][j]); }
}
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

19
01/11/2022

Continue… Example- Multiplication of two Matrix 2x2


void main( )
printf(" sum of matrix:"); {
for(i=0;i<2;i++) int a[2][2], b[2][2],s[2][2];
{ int i,j,k;
for(j=0;j<2;j++) clrscr();
{ printf("Enter first matrix:\n" );
printf("%f/t",c[i][j]); for( i=1;i<=2;i++)
if(j==1) {
printf("/n"); for( j=1;j<=2;j++)
} {
} scanf("%d",&a[i][j]);
} }
}
UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

20
01/11/2022

Conti… Conti…
printf("Enter second matrix:\n"); for(i=1;i<=2;i++)
for(i=1;i<=2;i++) {
{ for(j=1;j<=2;j++)
for(j=1;j<=2;j++) {
{ s[i][j]=0;
scanf("%d",&b[i][j]); for(k=1;k<=2;k++)
} {
} s[i][j] +=a[i][k]*b[k][j];
}
}
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

21
01/11/2022

Conti…
printf("Matrix Multiplication Is: \n");
for(i=1;i<=2;i++)
{
for (j=1;j<=2;j++)
{
printf("%d ",s[i][j]); Pointer in C
}
printf("\n");
}
getch();
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

22
01/11/2022

Basic of Pointers Continue…


Name of Memory Block
Name of Memory int x = 5; x Variable
int x = 5; x Block Variable
Content in Memory Block
Content in Memory 5
5 Block
Memory Block Address of Memory Block
Address of Memory 2048
2048 Block void main()
Memory Block {
int x=5; Output -
printf(“%d”, x); 5
printf(“%d”, &x); 2048
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

23
01/11/2022

Address of Operator Indirection Operator

 & is known as Address of Operator.  * is an indirection operator.


 It is an unary Operator.  It is an unary Operator.
 Operand must be the name of variable.  It takes address as an argument.
 & Operator gives address number of variable.  & is also known as dereferencing operator.
 & is also known as referencing operator.  * returns the content/container whose address is its
argument.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

24
01/11/2022

Example- Note - %d or %u

%d – 32768 to 32767
void main() %u – 0 to 65535
{
int x=5; Output -
printf(“%d\n”, x); 5
printf(“%d\n”, &x); 2048
printf(“%d\n”, *&x); 5
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

25
01/11/2022

Question-? But…

int x = 5; int x = 5; x j
x
&x = 7; int *j;
j = &x;
5 2048
5
2048 3000
2048

We can’t store anything in &x as &x is not a variable, it is  We can store address in another variable.
the way to represent address of block x.  But j has to be declared before use.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

26
01/11/2022

But… Pointer-

 Pointer is a variable that contains address of another


int x = 5; x j
variable.
int *j;  Pointer always consumes 2 bytes in memory.
j = &x;
5 2048
2048 3000

 j is not an ordinary variable like any other integer


variable.
 It is a variable which contains the address of another
variable.
UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

27
01/11/2022

Question-? Extended Concept of Pointers-


x j q
x p r

5 2048 5 1000 2000 3000


1000 2000 3000 4000
2048 3000
void main() void main()
{ {
int x=5, *j ; int x=5, *p , **q , ***r ;
j = &x ; Output - Output -
printf(“%d %u\n”, x , j); 5 2048 7
printf(“%d %u\n”, *j , &x); 5 2048 p=&x;
printf(“%u\n”, *&x); 5 q=&p; **q=7;
} r=&q; printf(“%d\n”, x);
}

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

28
01/11/2022

Call by value and Call by reference in C Call by value in C-


 In call by value method, the value of the actual
There are two methods to pass the data into the function in C parameters is copied into the formal parameters. In
language, i.e., call by value and call by reference. other words, we can say that the value of the variable
is used in the function call in the call by value
method.
 In call by value method, we can not modify the value
of the actual parameter by the formal parameter.
 In call by value, different memory is allocated for
actual and formal parameters since the value of the
actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used
in the function call whereas formal parameter is the
argument which is used in the function definition.

29
01/11/2022

Example-Call by value in C: Call by Value Example: Swapping the values of the two variables

#include<stdio.h> #include <stdio.h>


int main() { void swap(int , int); //prototype of the function
int x=100; int main()
printf("Before function call x=%d \n", x); {
change(x);//passing value in function int a = 10;
Output -
printf("After function call x=%d \n", x); Before function call x=100 int b = 20;
return 0; Before adding value inside function printf("Before swapping the values in main a = %d, b = %d\n",a,b);
num=100
} After adding value inside function
void change(int num) num=200 // printing the value of a and b in main
After function call x=100
{ swap(a,b);
printf("Before adding value inside function num=%d \n",num); printf("After swapping values in main a = %d, b = %d\n",a,b);
// The value of actual parameters do not change by changing the f
num=num+100; ormal parameters in call by value, a = 10, b = 20
printf("After adding value inside function num=%d \n", num); }
}

30
01/11/2022

Continue… Call by reference in C-

void swap (int a, int b)  In call by reference, the address of the variable is
{ passed into the function call as the actual parameter.
int temp;
 The value of the actual parameters can be modified
temp = a;
a=b; by changing the formal parameters since the address
b=temp; of the actual parameters is passed.
printf("After swapping values in function a = %d, b = %d\n",a,b);  In call by reference, the memory allocation is similar
// Formal parameters, a = 20, b = 10 for both formal parameters and actual parameters. All
} the operations in the function are performed on the
Output -
value stored at the address of the actual parameters,
Before swapping the values in main a = 10, b = 20 and the modified value gets stored at the same
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20 address.

31
01/11/2022

Example-Call by reference in C- Call by reference Example: Swapping the values of the


two variables
#include<stdio.h>
int main() { #include <stdio.h>
int x=100; void swap(int *, int *); //prototype of the function
printf("Before function call x=%d \n", x); int main()
change(&x);//passing reference in function {
printf("After function call x=%d \n", x);
return 0;
int a = 10;
} int b = 20;
void change(int *num) { printf("Before swapping the values in main a = %d, b = %d\n",
printf("Before adding value inside function num=%d \n",*num); a,b); // printing the value of a and b in main
(*num) += 100; swap(&a,&b);
printf("After adding value inside function num=%d \n", *num);
}
printf("After swapping values in main a = %d, b = %d\n",a,b);
// The values of actual parameters do change in call by reference, a = 10, b = 20
Output -
Before function call x=100
}
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

32
01/11/2022

Continue… Array Of Pointers-

void swap (int *a, int *b) datatype *pointername [size];


{ For example,
int temp;
temp = *a; int *p[5];
*a=*b; //It represents an array of pointers that can hold 5 integer
*b=temp; element addresses.
printf("After swapping values in function a = %d, b =
%d\n",*a,*b); // Formal parameters, a = 20, b = 10
}
Output -
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

33
01/11/2022

Example- Array Of Pointers: Pointer to Pointer-


#include<stdio.h> Pointer to pointer is a variable that holds the address of another
main () pointer.
{
int a[3] = {10,20,30};
int *p[3],i; datatype ** pointer_name;
for (i=0; i<3; i++)
p[i] = &a[i]; //initializing base address of array
printf (elements of the array are”)
for (i=0; i<3; i++)
printf ("%d \t", *p[i]); //printing array of pointers
getch();
}

Output
elements at the array are : 10 20 30

34
01/11/2022

Example- Pointer to Pointer:


#include<stdio.h>
main ()
{
int a = 10;
int *p;
int **q;
p = &a; String
q = &p;
printf("a =%d",a);
printf("a value through pointer = %d", *p);
printf("a value through pointer to pointer = %d", **q);
}

Output
a=10
a value through pointer = 10
a value through pointer to pointer = 10

35
01/11/2022

String Types of String:

 The string can be defined as the one-dimensional There are two ways to declare a string in c language.
array of characters terminated by a null ('\0').
 The character array or the string is used to manipulate
text such as word or sentences. 1. By char array
 Each character in the array occupies one byte of
2. By string literal
memory, and the last character must always be 0.
 The termination character ('\0') is important in a
string since it is the only way to identify where the
string ends.

36
01/11/2022

Continue… String Example in C:

1. Example of declaring string by char array in C language. #include<stdio.h>


char ch[10]={‘U', ‘I', ‘M', '\0'}; #include <string.h>
int main(){ Output
0 1 2 3 Char Array Value is: UIM
char ch1[4]={‘U', ‘I', ‘M', '\0'}; String Literal Value is: UGI
U I M \0
char ch2[3]=“UGI";

2. We can also define the string by the string literal in C language. printf("Char Array Value is: %s\n", ch1);
printf("String Literal Value is: %s\n", ch2);
char ch[]=“UIM"; return 0;
}
In such case, '\0' will be appended at the end of the string
by the compiler.

37
01/11/2022

Traversing String-Count Vowels in string: Traversing String-Using the null character

#include<stdio.h> #include<stdio.h>
void main () void main ()
{ {
char s[10] = “allahabad"; char s[11] = “allahabad";
int i = 0; int i = 0;
int count = 0; int count = 0;
while(i<10) while(s[i] != NULL)
{ {
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o') if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
{ {
count ++; count ++;
} Output } Output
i++; The number of vowels :4 i++; The number of vowels :4
} }
printf("The number of vowels %d",count); printf("The number of vowels %d",count);
} }

38
01/11/2022

Accepting string as the input: C gets() functions-


Description
The C library function char *gets(char *str) reads a line from stdin and stores
#include<stdio.h> it into the string pointed to by str.
void main () It stops when either the newline character is read or when the end-of-file is
{ reached, whichever comes first.
char s[20];
Declaration
printf("Enter the string:");
scanf("%s",s); Output char[] gets(char[]);
Enter the string: ram is the best.
printf("You entered: %s",s); You entered: ram #include<stdio.h>
} void main ()
{
NOTE- char s[30];
To make this code working for the space separated strings, the printf("Enter the string? "); Output
Enter the string?
minor changed required in the scanf function, i.e., instead of gets(s); Ram is the best
writing scanf("%s",s), we must write: scanf("%[^\n]s",s) which printf("You entered %s",s); You entered : Ram is the best

instructs the compiler to store the string s while the new line (\n) }
is encountered.

39
01/11/2022

puts() functions-
Example 4: Strings and Pointers
Description
The C library function int puts(const char *str) writes a string to stdout up to but not
including the null character. A newline character is appended to the output. #include <stdio.h>
Declaration void main()
int puts(char[]) {
char name[] = "Harry Potter";
printf("%c", *name);
#include<stdio.h>
printf("%c", *(name+1)); Output
#include <string.h> H
printf("%c", *(name+7));
int main(){ Output a
char name[50]; o
Enter your name: Raj
Your name is: Raj char *namePtr;
printf("Enter your name: "); H
namePtr = name;
gets(name); //reads string from user a
printf("%c", *namePtr); o
printf("Your name is: ");
printf("%c", *(namePtr+1));
puts(name); //displays string
printf("%c", *(namePtr+7));
return 0;
}
}

40
01/11/2022

%c and % s - %c and %s
Conti…

#include <stdio.h> #include <stdio.h>


int main(){ int main(){
Output Output
char *ptr = "I am string"; Output : I I am string char *ptr = "I am string"; Output : I I am string
printf("%c %s",*ptr, ptr ); printf("%c %s",*ptr, ptr );
return 0; return 0;
} }

2. Also, If we specify the format specifier as ‘%s’ and use ‘ptr’


1. Now coming back to the point, any character pointer (which contains the starting address of the string), then the
pointing to a string stores the address of the first character of complete string is printed using printf. The concept is that %s
the string. In the code above, ‘ptr’ holds the address of the specifier requires the address of the beginning byte of string
character ‘I’ ie 1000. Now, when we apply the ‘value of’ to display the complete string, which we provided using ‘ptr’
operator ‘*’ to ‘ptr’, we intend to fetch the value at address (which we know holds the beginning byte address of the
1000 which is ‘I’ and hence when we print ‘*ptr’, we get ‘I’ as string). This we can see as the last print in the output above.
the output.

41
01/11/2022

C String Functions-
strlen()
No. Function Description
1) strlen(string_name) returns the length of string
#include<stdio.h>
name.
#include <string.h>
strcpy(destination, source) copies the contents of int main(){ Output:
2) source string to destination char ch[20]={‘a', ‘s', ‘h', ‘u', 't', ‘o', ‘s', ‘h', '\0'}; Length of string is: 8
string. printf("Length of string is: %d",strlen(ch));
strcat(first_string, concats or joins first string return 0;
3) second_string) with second string. The }
result of the string is strcpy()
stored in first string.
strcmp(first_string, compares the first string #include<stdio.h>
4) second_string) with second string. If both #include <string.h>
strings are same, it returns int main(){
0. char ch[20]={‘i', ‘n', ‘d', ‘i', ‘a', '\0'};
char ch2[20]; Output:
5) strrev(string) returns reverse string. strcpy(ch2,ch); Value of second string is: javatpoint

6) strlwr(string) returns string characters in printf("Value of second string is: %s",ch2);


lowercase. return 0;
}
7) strupr(string) returns string characters in
uppercase.

42
01/11/2022

Ex.1-Passing strings to functions:


Exercise 1-
#include <stdio.h> 1. Write a program in C to find the length of a string without using
void displayString(char []); library function.

int main() 2. Write a program in C to separate the individual characters from a


{ string.
char message[] = "Hello World";
displayString(message); OUTPUT-
return 0; String: Hello World
}

void displayString(char str[])


{
printf("String: %s\n", str);
}

43
01/11/2022

Ex.2-Passing strings to functions:


Exercise 2-
#include <stdio.h>
int length(char []);
void main()
1. Write a program to find whether the given number is palindrome
{
or not. using Array. char str[10];
int l;
2. Write a program to find product of two matrix using 3x3 Array. printf(“\n Enter a string:”)
gets(str);
l=length(str);
printf(“\n Length = %d”, l); OUTPUT-
} Enter a String: UIM
Length = 3
int length(char str[])
{
int l=0, i;
for(i=0;str[i]!=‘\0’; i++)
{
l++;
}
return l;
}

44
01/11/2022

END OF UNIT - III


PROBLEM SOLVING USING C
KCA102
UNIT-III
MCA I YEAR, I SEM.

UNIT – 3 | C PROGRAMMING MR. ASHUTOSH PANDEY

45

You might also like