Skip to main content

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

  1. Start
  2. Declare a string pointer.
  3. Declare a length variable.
  4. Input the string.
  5. Scan the string.
  6. Run a loop till the last character of the string.
  7. Print the length of the string.
  8. 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.

Related Resources