Program to count the number of characters in a word
Last Updated :
18 Jan, 2024
Write a program to count the number of characters in a word.
Examples:
Input: Word: “programming”
Output: 11
Input: Word: “hello”
Output: 5
Approach: To solve the problem, follow the below idea:
To count the number of characters in a word, maintain a variable to count all the characters. Iterate through each character in the word and increment the counter for every character.
Step-by-step algorithm:
- Initialize a counter variable to 0.
- Iterate through each character in the word.
- For each character encountered, increment the counter.
- After iterating through all characters, the counter will contain the total number of characters in the word.
Below is the implementation of the algorithm:
C++
#include <iostream>
using namespace std;
int main() {
string word = "programming" ;
int count = 0;
for ( int i = 0; i < word.length(); ++i) {
++count;
}
cout << "Number of characters: " << count << endl;
return 0;
}
|
C
#include <stdio.h>
int main()
{
char word[] = "programming" ;
int count = 0;
for ( int i = 0; word[i] != '\0' ; ++i) {
++count;
}
printf ( "Number of characters: %d\n" , count);
return 0;
}
|
Java
public class CharacterCount {
public static void main(String[] args)
{
String word = "programming" ;
int count = 0 ;
for ( int i = 0 ; i < word.length(); ++i) {
++count;
}
System.out.println( "Number of characters: "
+ count);
}
}
|
Python3
word = "programming"
count = 0
for char in word:
count + = 1
print ( "Number of characters:" , count)
|
C#
using System;
class Program {
static void Main()
{
string word = "programming" ;
int count = 0;
foreach ( char c in word) { ++count; }
Console.WriteLine( "Number of characters: " + count);
}
}
|
Javascript
let word = "programming" ;
let count = 0;
for (let i = 0; i < word.length; ++i) {
++count;
}
console.log( "Number of characters:" , count);
|
Output
Number of characters: 11
Time Complexity: O(N), where N is the length of the word.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...