This program takes a string input from the user using the scanf()
function and stores it in the some_string
character array. It then uses a for
loop to iterate over the characters of the string until it encounters the null terminator character '\0'
. During each iteration of the loop, it prints the length of the string up to that point using the printf()
function.
Therefore, the program calculates and outputs the length of the input string entered by the user.
#include <stdio.h>
int main()
{
char some_string[100];
int x;
printf("Enter Some String: \n");
scanf("%s", some_string);
for(x = 0; some_string[x]!='\0'; x++)
{
printf("Length atm: %d \n", x+1);
}
return 0;
}
Result:
Enter Some String:
test
Length atm: 1
Length atm: 2
Length atm: 3
Length atm: 4
Process returned 0 (0x0) execution time : 1.031 s
Press any key to continue.
Here's a line-by-line explanation of the code:
#include <stdio.h>
This line includes the standard input/output library, which contains functions for input/output operations.
int main()
{
This is the beginning of the main function, which is the entry point for the program.
char some_string[100];
int x;
Here, we declare a character array variable named some_string
that can hold up to 100 characters and an integer variable named x
that will be used to keep track of the loop iterations.
printf("Enter Some String: \n");
scanf("%s", some_string);
This code prompts the user to enter a string and stores it in the some_string
variable using the scanf()
function.
for(x = 0; some_string[x]!='\0'; x++)
{
printf("Length atm: %d \n", x+1);
}
This is a for
loop that iterates through the string some_string
until it encounters the null character \0
, which marks the end of the string. The loop body simply prints the current length of the string on each iteration, starting from 1 because the x
variable starts at 0.
return 0;
}
This line simply ends the program and returns 0 to indicate successful execution.
No comments:
Post a Comment