[cs13001] Practice Exam Question

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Mar 6 10:55:05 EST 2013


> For question 7 on the practice exam could you do it the same way but simply
> add a 'break' after the cout so that it would not repeat anymore?

you can add a "break". Since there are two statements in the "if", you'll have
to enclose them in a block. 

Another variant: you can put the "FOUND" output statement in the
if-statement as well. You will still need a "break" and a boolean
variable to indicate that the number has been found. 

That is, the code may look like this:

    bool located=false;
    for(int i=0; i < SIZE; i++)
       if(myarray[i] == number){
          located = true;
	  cout << "FOUND";
	  break;
       }
   if(!located)
       cout << "NOT FOUND";




> 
> On Tue, Mar 5, 2013 at 11:31 PM, Mikhail Nesterenko <mikhail at cs.kent.edu>wrote:
> 
> > > I am having trouble with question 7 on the practice exam. Can you tell me
> > > what is wrong with this code? I can't get it to work properly.
> > >
> > > for(int i=0; i<SIZE; i++)
> > >  if(myarray[i] == number)
> > >       cout << "FOUND";
> > >  else
> > >       cout << "NOT FOUND";
> > >
> >
> > This code output FOUND or NOT FOUND tem times. Instead, it should
> > output FOUND or NOT FOUND once. You need an extra variable to keep
> > track whether the number is found or not. For example:
> >
> >
> >    bool located=false;
> >    for(int i=0; i < SIZE; i++)
> >       if(myarray[i] == number)
> >          located = true;
> >    if(located)
> >       cout << "FOUND";
> >    else
> >       cout << "NOT FOUND";
> >
> > Thanks,
> > --
> > Mikhail


More information about the cs13001 mailing list