F.E. PPS Unit 3 Practical 9 solution

Practical 9: Program That Counts the Occurrences of a Character in a String Without Using Built-in Functions.

Problem Statement

Write a Python program that accepts a string from the user and a character to search for. The Program That Counts the Occurrences of a Character in a String Without Using Built-in Functions.

Solution Code

				
					# Program to count occurrences of a character in a string without using built-in functions

# Taking input from the user
string = input("Enter a string: ")
char_to_find = input("Enter the character to count: ")

# Initializing counter variable
count = 0

# Loop through each character in the string
for char in string:
    if char == char_to_find:
        count += 1  # Increment count if match is found

# Displaying the result
print(f"The character '{char_to_find}' appears {count} times in the string.")


				
			

Output

  • The program takes a string and a character as input.
  • It loops through the string and manually counts the number of occurrences of the given character.
  • Finally, it displays the count.

Example output:

				
					 Enter a string: Banana
Enter the character to count: a
The character 'a' appears 3 times in the string.
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 3 Practical 9 solution where we have written Python Program That Counts the Occurrences of a Character in a String Without Using Built-in Functions.

  1. Taking User Input:
    • The user enters a string and a character to search for.
  2. Initializing the Counter:
    • A variable count is initialized to 0 to keep track of occurrences.
  3. Iterating Through the String:
    • A for loop is used to traverse each character in the string.
    • If the character matches the user-provided character, count is incremented.
  4. Displaying the Count:
    • The total occurrences of the character are displayed after the loop completes.

Key Concepts Learned

  • String Traversal Using Loops
    • Using a for loop to iterate over a string.
  • Manual Counting Without Built-in Functions
    • Implementing character counting logic manually.
  • Conditional Statements (if)
    • Checking for character matches within the loop.
Tech Amplifier Final Logo