C++/c++

Advertisement


Question
Hi,
If you have a random sequence of numbers    e.g    2, 5, 6, 7, 5, 8, 9, 5 how do you write a program which counts the numbers of times the second number occurs. In the above example the 2nd number 5 occurs 3 times, it should for  any set of numbers.This is what should be output. My attempt is as follows,what am I doing wrong.
#include <iostream>
using namespace std;
int main(){
bool finished = false;
int num1;
int count=0;
cin>>num1;
while ( ! finished){
int num;
cin >> num;

if ( cin.fail() )
finished = true;
else if(num==num1)
count=count+1; else cout<<count<<endl;

}

return 0;}


Dav  

Answer
This is very similar to your previous question. But this time you should read number two times before you enter the loop.
Also you have the same error of putting cout<<count<<endl; inside the loop.
Make sure you know how to use cin.fail() because it is a bit tricky.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Sam

Expertise

You may ask me about simple to complicated C/C++ programming methods/style and most like questions about network programming in C++.

Experience

I'm a professional programer in C++ and network/internet programming.

©2016 About.com. All rights reserved.