#include<iostream>
#include<iomanip>
#include<cmath>
usingnamespace std;
int main ()
{
int num,n,i;
int total=0,count=0;
double average=0;
cout<<"The programe will capture as many number as you want to enter!"<<endl;
cout<<"You may stop by entering any alphabet"<<endl;
cout<<endl;
do
{
cout<<"How many number you want to capture? ";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter number "<<i<<" : ";
cin>>num;
if(num=='a' && num=='z')
break;
count++;
total = total+num;
}
}while(num=='a' && num=='z');
average = total / count;
cout<<"The Average number "<<n<<" is : "<<average<<endl;
system("pause");
return 0;
}
Write a program that reads a series of n integers from the user. Your program should provide a way for the user to prematurely terminate input prior to entering n^th integer by entering an alphabet. Your program should print the average only if there is at least one integer captured. Otherwise there will be no calculation and an appropriate message will be displayed.
Sample output:
This program will capture as many number as you want to enter !
You may stop by entering any alphabet.
How many number you want to enter? 20
Enter number 1: 2
Enter number 2: 4
Enter number 3: 6
Enter number 4: 7
Enter number 5: 8
Enter number 6: p
The average of the 5 numbers is: 5.4
#include<iostream>
#include<iomanip>
#include<cmath>
usingnamespace std;
int main ()
{
int num,n,i;
int total=0,count=0;
double average=0;
cout<<"The programe will capture as many number as you want to enter!"<<endl;
cout<<"You may stop by entering any alphabet"<<endl;
cout<<endl;
do
{
cout<<"How many number you want to capture? ";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter number "<<i<<" : ";
cin>>num;
if(num=='a' && num=='z')
break;
count++;
total = total+num;
}
}while(num=='a' && num=='z');
average = total / count;
cout<<"The Average number "<<n<<" is : "<<average<<endl;
system("pause");
return 0;
}
this is my code.. it since when i type in alphabet it doesnt quit and keep prompt till the number i enter. it Please help check out
Consider line 24 cin >> num I read somewhere that cin does some type checking and when it is expecting an int e.g., digits 0 through 9 it will fail if it is not a number. You can use this in line 25.
Think about line 25, how can num be equal to 'a' and be euqal to 'z' at the same time? Knowing that cin can fail you can use this with if (!cin) and it will reach the break statement to exit the do while loop.
By the description of the program lines 32 and 33 should only be used if count is greater than one.