Home CPSC 110

Lab 6: Character Counter

 

Objective

To gain experience with for loops.


 

Task

For this lab you will write a program to count how many times a character appears in a string.


 

Details

  1. Start by asking the user to enter a string. Be sure to save it into a variable.
  2. Next, ask them to enter a character to search for, saving this into a variable as well.
  3. Write a for loop to go through every character in the first string they entered.
  4. Inside the loop, check if the character we are on is equal to the one we are searching for. If it is, then add one to the number we have seen so far
  5. At the end, print out the number of occurrences of the character we're searching for.

 

Example Run

Below is an example run of how this program should work:

Enter a message: hello
Enter a character: l
There are 2 occurences of l in hello

And here is another:

Enter a message: this is a longer test string
Enter a character: t
There are 4 occurences of t in this is a longer test string

 

Submitting

When you are finished, please submit the .py file for the lab on Canvas. To do so, you'll need to navigate to where you saved the file on your computer.

Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.