i dont understand looping at all.
plese help if you can.
i know its like doing my work for me but yeah i dont know looping.

create a program that keeps reading a sentence and a character and displays how many times the character appears in the sentence until user enters a $ for the character at which point the program displays the number of times a sentence was entered. Each sentence is considered finished when the user enters a period.


example of program

Enter the character to count: a

Enter a sentence ending in a period: i like red apples.

a appeard 1 time.

Enter the character to count: o

Enter a sentence ending in a period: tomorrow im going to play soccer.

o appeared 6 times.

Enter the character to count: $ (stops program)

2 sentences were entered.

Press any key to continue.

Recommended Answers

All 4 Replies

anybody? =/

Looping just means do the same thing one or more times. So if you can write code to determine if a given char has a given value, then you use that in a loop using a counter to determine how many of a given char there are in a given string. The tricky part sometimes comes in determining what information to use starting and stopping the loop. Basically any loop can do anything any other loop can. However, int general, if you know the number of times you want to do something then for loops come to mind and if you have some condition that isn't necessarily known ahead of time, then the syntax of while loops frequently seems more comfortable.

well, use sentinel value $ to terminate your loop. You should use while loop here
so something like ( while value!=$)...

Do some work and come for help. I can't write whole code for u!

Here's a working example (I wrote in ~5 minutes), but write your own and use mine as an example on a way to approach it.

#include <cstdlib>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    char value[50] = {0}; /* our character array */
    char c_tmp[2] = {0};
    char c; /* character to count */
    
    while(strcmp(value, "$") != 0) { /* keep looping until value is $ (then stop) */
        memset(value, 0x0, sizeof(value)); /* empty value (null it) */
        
        int num = 0; /* numbers of times it appeared */
        
        cout << "enter a character: ";
        cin.getline(c_tmp, sizeof(c_tmp));
        
        c = *c_tmp;
        
        cout << "enter a sentence: ";
        cin.getline(value, sizeof(value));
        
        for(int i=0;i<strlen(value);i++) {
                if(value[i] == c) num++;
        }
        
        cout << c << " appeared " << num << " times." << endl;
    }
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.