Practical-20
Write a program using pointer to determine the length of a character string.
Introduction
In this program, we will learn to write a program using pointer to determine the length of a character string.
Algorithm
- Start
- Declare a string pointer.
- Declare a length variable.
- Input the string.
- Scan the string.
- Run a loop till the last character of the string.
- Print the length of the string.
- End
Code
Practical-20.c
#include<stdio.h> // header file
void main(){ //function start
char* str; //declare string pointer
int len=0; //declare length
printf("Enter the string:"); //Inputiing the string
scanf("%s",str); //scanning the string
while(*str){ //will run till last character of string
len++; //incrementing length
str++; //incrementing pointer
}
printf("Length of the string is %d\n",len); //printing length
//ending main function
}
Output
Enter the string:Hello
Length of the string is 5
Explanation
In this program, we have declared a string pointer and a length variable. Then we have inputted the string and scanned it. Then we have run a loop till the last character of the string. In the loop, we have incremented the length and the pointer. Then we have printed the length of the string.