anni saini
anni saini

Reputation: 403

Unexpected results from a simple code

Q) Write a program to accept the age of n employees and count the number of persons in the following age group: (i)26-35
(ii)36-45
(iii)46-55

I wrote this program:

#include<iostream.h>
#include<conio.h>
int main(){
 clrscr();
 unsigned int a, i,ii,iii,ch;
 while(1){
  cout<<"Enter age: ";
  cin>>a;
  if(a>=26 && a<=35){i++;};
  if(a>=36 && a<=45){ii++;};
  if(a>=46 && a<=55){iii++};
  cout<<"continue...[0/1]: ";
  cin>>ch;
  if(!ch){break;}else{continue;};
 };
cout<<"26-35: "<<i<<"/n 36-45: "<<ii<<"\n 45-55: "<<iii;
return 0;
};

the first version of this program include goto statements rather that while loop but the fact is that the results were wrong in both the cases.

the answers were after running this code:

26-35: 1515
36-45: 1539
46-55: 1

here you can see that only the last age group count is correct because i entered 27, 37 and 54 only once when the code was running.

Upvotes: 0

Views: 628

Answers (1)

user2736738
user2736738

Reputation: 30906

  1. Initialize i=0,ii=0,iii=0. You have forgot to initialize them.(This is the reason for wrong answer)

  2. Don't use redundant extra logic. else {continue;}. You don't need it.

Upvotes: 4

Related Questions