Monday, April 28, 2025

C Program - Get the String Length with While Loop

This C program prompts the user to enter a string and then calculates and displays the length of the string. 

#include <stdio.h>

int main()
{

    char some_string[100];
    int x;

    printf("Enter Some String: \n");
    scanf("%s", some_string);

    while (some_string[x] != '\0')
    {
        x++;
    }
    printf("Total Length: %d \n", x);

    return 0;
}

Result: 

Enter Some String:
something
Total Length: 9

Process returned 0 (0x0)   execution time : 2.677 s
Press any key to continue.
Line by line explanation: 
#include <stdio.h>

This line includes the standard input-output library header file, which is needed for using standard functions like printf() and scanf()

int main()
{

This is the starting point of the program where the main() function is defined. This function is required in every C program and serves as the entry point of the program. The function signature int main() indicates that the function returns an integer value upon completion. 

    char some_string[100];
    int x;

This code block declares two variables: some_string, which is a character array of size 100 and x, which is an integer variable. 

    printf("Enter Some String: \n");
    scanf("%s", some_string);

These lines of code print a prompt to the user to enter a string using printf() and then reads in the input string using scanf(). %s format specifier in the scanf() function indicates that it will read in a string of characters from the user. 

    while (some_string[x] != '\0')
    {
        x++;
    }

This code block uses a while loop to iterate through the character array some_string until it reaches the null character '\0'. The null character marks the end of a C-style string. In each iteration, the loop increments the value of the x variable, which keeps track of the number of characters in the string. 

    printf("Total Length: %d \n", x);
    return 0;
}

Finally, this code block uses printf() to display the length of the string by printing the value of the x variable. The program then returns 0 to indicate successful execution of the program.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...