Ex: Write a C program to find length of string using pointers. How to write a C program to find length of string using pointers. C program to find length of string using pointers.
Input from user:
Enter the string:
Hi this is codeforhunger
Expected output:
Length of string= 24
Step by step logic of the given program:
1. Accept input(string) from user store it in some variable say str.
2. After that use while loop(here you can use any other loop also) to iterate string through last element:
while(*ptr!='\0')
3. Inside the loop increment counter by 1(to calculate length of string). i.e, count++;
4. After that print value of count(length of string) on the output screen.
Program to find length of string using pointers:
#include<stdio.h>
int main()
{
char str[100];//declare string size 100
char *ptr=str;/*declare pointer which points to string(str)*/
int count=0;
printf("Enter the string:\n");
gets(str);
/*Iterate string through last element*/
while(*ptr!='\0')
{
count++;
ptr++;
}
printf("Length of string= %d",count);
return 0;
}
Above program shows the following output: