how to count the number of "numbers in for" - c++

everyone, I build a programme to know even and odd number from given numbers.
The even and odd number works just fine, and i want to know the total count of numbers ranging from the start number to the end number but it always says 11 at the output for both.
How do I solve this? and is there any function to count letters/numbers because it will be very helpful.
I did search it up but I can't find any Thank you
#include<stdio.h>
#include <iostream>
using namespace std;
int main(){
int number;
int firstNum,secondNum;
int countOdd,countEven;
cout << "Enter the first number: ";
cin >> firstNum;
cout << "Enter the second number: ";
cin >> secondNum;
if (firstNum>secondNum )
cout << "Sorry the first number must be less than second number";
else
cout << "Odd numbers in given range are: ";
for(number = firstNum;number <= secondNum; number++)
if(number % 2 !=0)
cout << number<< " ";
countOdd = number;
cout << "\nTotal count of odd number is :" << countOdd << endl;
printf("\nEven numbers in given range are: ");
for(number = firstNum;number <= secondNum; number++)
if(number % 2 ==0)
cout << number << " ";
countEven = number;
cout << "\nTotal count of even number is :" << countEven << endl;
return 0;
}

Code to count odd and even numbers:
using namespace std;
// Return the number of odd numbers
// in the range [L, R]
int countOdd(int L, int R){
int N = (R - L) / 2;
// if either R or L is odd
if (R % 2 != 0 || L % 2 != 0)
N += 1;
return N;
}
// Driver code
int main()
{
int L = 3, R = 7;
int odds = countOdd(L, R);
int evens = (R - L + 1) - odds;
cout << "Count of odd numbers is " << odds << endl;
cout << "Count of even numbers is " << evens << endl;
return 0;
}

You are overwriting your counts with every iteration of the for loop. countOdd = number; should be moved inside the if statement and read more like this:
if (number % 2 != 0) {
cout << number << " ";
countOdd++;
}
That way you will actually be counting the numbers as you find them.
This goes the same for the code in the counting of even numbers.
if (number % 2 == 0) {
cout << number << " ";
countEven++;
}
And don't forget to initialize the counters variables before using them:
countOdd = countEven = 0;

Related

Printing on same line and add count in one line one time in c++

how to show output ( Number of grades above the Average + Grades above or equal the Average ) in same line i don't wont new line for each number + how to print these one time not many times , i mean because i use for loop it print Number of grades above the Average every number in one line i want just the count in one line how to do this
#include <iostream>
using namespace std;
int main()
{
int G,N;
float num[100], sum=0.0, average;
cout << "Enter the numbers of Student : ";
cin >> N;
while (N > 500 || N <= 1)
{
cout << "Error ! number of student should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> N;
}
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter " << G + 1 << " Mark : ";
cin >> num[G];
sum += num[G];
}
// find average
average = sum / N;
cout <<endl<< "Grades Average = " << average <<endl<<endl;
// find Grades above or equal the Average
cout<<"Grades above or equal the Average : "<< endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << num[G] << endl;
}
}
// find Number of grades above the Average
cout<<endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << "Number of grades above the Average : " << G + 1 << endl;
}
}
return 0;
}
There are a number of issues with your code:
num[] can hold 100 values max, but you are allowing the user to enter up to 500 values into it, thus you have the potential for a buffer overflow.
you say the valid number of students is 1 to 500, but you are preventing the user from entering 1.
lack of adequate error handling when reading the user's input.
you are outputting "Number of grades above the Average : " inside the loop for every matching grade, which you say you don't want. You should instead output it once before entering the loop, then use the loop to count the matching grades without outputting each one, then output the final count after the loop is finished.
Try this:
#include <iostream>
#include <limits>
using namespace std;
const int maxStudents = 500;
int main()
{
int G, N, nAverages = 0;
float num[maxStudents], sum = 0.0, average;
cout << "Enter the number of Students : ";
do
{
if (cin >> N)
{
if (N >= 1 && N <= maxStudents)
break;
cout << "Error ! Number of students should be in range of (1 to " << maxStudents << ")." << endl;
}
else
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "Enter the number again: ";
}
while (true);
for(G = 0; G < N; ++G)
{
cout << G + 1 << ". Enter Mark : ";
while (!(cin >> num[G]))
{
cout << "Error ! Invalid input." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter the mark again: ";
}
sum += num[G];
}
// find average
average = sum / N;
cout << endl << "Grades Average = " << average << endl << endl;
// find Grades above or equal the Average
cout << "Grades above or equal the Average : " << endl;
for (G = 0; G < N; ++G){
if (num[G] >= average){
cout << G + 1 << ": " << num[G] << endl;
++nAverages;
}
}
// Number of grades above the Average
cout << endl << "Number of grades above the Average : " << nAverages << endl;
return 0;
}

how to exclude the SENTINEL value from the output in c++?

how do you exclude the SENTINEL value from the output in c++?
For a school project.
The SENTINEL value is skewing the output and adding it to the calculations. My professor was vague on how to exclude the SENTINEL from my calculations, but I am still confused as to how to exclude it.
My output for the largest value keeps equaling 99999 which is the SENTINEL value.
It is also adding the SENTINEL value to all the calculations.
#include "stdafx.h"
#include <iostream>
#include <climits>
using namespace std;
int SENTINEL = 99999;
int main()
{
int min = INT_MAX, max = INT_MIN, num = 0, counter = 0, pos = 0, neg = 0, sum = 0, num2 = 0, tot = 0;
int even = 0;
int odd = 0;
double total = 0;
while (num != SENTINEL)
{
cout << "Enter in a number" << endl;
cout << "Enter 99999 to exit" << endl;
cin >> num;
if (num > max)
max = num;
if (num < min)
min = num;
if ((num % 2) != 0)
{
odd++;
}
else if (num % 2 == 0)
{
even++;
}
if (num < 99999) {
neg++;
}
if (num < 99) {
num2++;
}
total += num;
tot += num;
counter++;
}
total = total / counter;
cout << "The smallest Number of the list is: " << min << endl;
cout << "The largest Number of the list is: " << max << endl;
cout << "The sum of all the numbers is: " << tot << endl;
cout << "The average of all numbers is: " << total << endl;
cout << "There are " << neg << " numbers" << endl;
cout << "There are " << even << " even numbers" << endl;
cout << "There are " << odd << " odd numbers" << endl;
cout << "There are " << num2 << " numbers smaller than 99" << endl;
return 0;
}
There are some changes you will have to make:
Read the number at least once before the while loop to ensure that the while
is not executed if number is 99999.
Move the reading of the number to the end of the while loop so that it can be checked right at the beginning before any further
processing.
Have a check to see if any numbers have to been entered to avoid dividing by zero in the statement total = total / counter;
The various statements must be output using cout only if there are any numbers in the list. Otherwise, it does not make much sense.
After the above changes, the code will look like this:
#include <iostream>
#include <climits>
using namespace std;
int SENTINEL = 99999;
int main()
{
int min = INT_MAX, max = INT_MIN, num = 0, counter = 0, pos = 0, neg = 0, sum = 0, num2 = 0, tot = 0;
int even = 0;
int odd = 0;
double total = 0;
cout << "Enter in a number" << endl;
cout << "Enter 99999 to exit" << endl;
cin >> num;
while (num != SENTINEL)
{
if (num > max)
max = num;
if (num < min)
min = num;
if ((num % 2) != 0)
{
odd++;
}
else if (num % 2 == 0)
{
even++;
}
if (num < 99999) {
neg++;
}
if (num < 99) {
num2++;
}
total += num;
tot += num;
counter++;
cout << "Enter in a number" << endl;
cout << "Enter 99999 to exit" << endl;
cin >> num;
}
if(counter != 0)
{
total = total / counter;
cout << "The smallest Number of the list is: " << min << endl;
cout << "The largest Number of the list is: " << max << endl;
cout << "The sum of all the numbers is: " << tot << endl;
cout << "The average of all numbers is: " << total << endl;
cout << "There are " << neg << " numbers" << endl;
cout << "There are " << even << " even numbers" << endl;
cout << "There are " << odd << " odd numbers" << endl;
cout << "There are " << num2 << " numbers smaller than 99" << endl;
}
else
{
cout << "No numbers were entered" << endl;
}
return 0;
}
Sample Output:
./a.exe
Enter in a number
Enter 99999 to exit
99999
No numbers were entered
./a.exe
Enter in a number
Enter 99999 to exit
34
Enter in a number
Enter 99999 to exit
23
Enter in a number
Enter 99999 to exit
12
Enter in a number
Enter 99999 to exit
99999
The smallest Number of the list is: 12
The largest Number of the list is: 34
The sum of all the numbers is: 69
The average of all numbers is: 23
There are 3 numbers
There are 2 even numbers
There are 1 odd numbers
There are 3 numbers smaller than 99

C++ : Making a do while loop repeat

I'm very sorry for the super newbie question, but I cannot for the life of me understand how to make a do while loop repeat. I changed a while loop into a do while loop and now I don't know how to get it to ask "would you like to repeat Y or N?" any explanation?
I've read various posts that accomplish a do while loop repeat, but they don't make sense to me.
Am I essentially going to wrap this code into another do while loop? Do I move the boolean expression to before the while?
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
system("pause");
return 0;
}
}
can do this:
char repeat='y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
for(int i=0;i<n;i++){
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
}
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>repeat;
}while(repeat=='y');
May be this is what you need, with char YorN you are considering if to continue or break the inner do-while.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
char YorN;
do{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>YorN;
} while (YorN=='Y');
return 0;
}
Although there are a ton of ways to do it better, this code allows me to explain what is happening. Do-While loops are definitely pretty tricky. However, just remember that a do-while loop is designed to run at least once.
In the case of our code, we set up if statements to test against running code where it is not appropriate.
Take a look at how the very first if statement is N > 0, the if-statement does execute, please do not forget that. Once more for emphasis, the if statement DOES execute, it just results in false.
With that being said, you use a do-while loop when you want your code block to execute AT LEAST once. Notice how our while statement has two things we're testing for, one, is the answer 'Y' from the user to continue, and if it is, is the newly inputted N value greater than 0?
You might be wondering if the inner most if statement ever executes at least once, well the answer is it depends on the previous if statement result if(N > 0) and if(count == N && N != 0) both execute once every single time the while loop stays true. However that nested if depends on it's parent result.
I hope this cleared some things up for you on do-while loops.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans = 'Y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
if(N > 0){ //THIS IF STATEMENT WILL ALWAYS RUN AT LEAST ONCE
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++;
}
if(count == N && N != 0) {//THIS IF STATEMENT WILL ALSO ALWAYS RUN AT LEAST ONCE
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>ans;
if(ans == 'Y') {//This one depends on it's parents result.
x = 0;
N = 0;
sum = 0;
count = 0;
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
}
}
} while (ans == 'Y' && N != 0);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
system("pause");
return 0;
}

Program hangs and does not loop

I am a beginner in c++. I wrote a program to separate the digits in an integer entered and display them and their sum. However, when the loop repeats, the program hangs even though it compiled perfectly. I tried a '... while' loop and a while loop but the problem persists. What should I do to have it repeat (ask user for next integer, calculate and display the results) without problems? Any help will be appreciated.
//Preprocessor directives
#include <iostream>
#include <cmath>
//Standard library
using namespace std;
//enter function main
int main()
{
int num;
int digit;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
while (num != 0 )
{
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;
if (num < 0)
num = -num;
//find the highest number of 10 that divides the number
while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
pwr++;
while (num > 0)
{
digit = num / static_cast<int>(pow(10.0, pwr));
cout << digit << " ";
sum = sum + digit;
num = num % static_cast<int>(pow(10.0, pwr));
pwr--;
}
if (pwr != -1) //Either num is 0 or there are trailing zeros in num
while (pwr != -1)
{
cout << 0 << " ";
pwr--;
}
cout << endl;
cout << "The sum of the digits = " << sum << endl;
while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;
}
return 0;
}
//Preprocessor directives
#include <iostream>
#include <cmath>
//Standard library
using namespace std;
//enter function main
int main()
{
while (true )
{
//reset initial values every loop
int num;
int digit;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
//same exit condition
if (num == 0)
break;
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;
if (num < 0)
num = -num;
//find the highest number of 10 that divides the number
while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
pwr++;
while (num > 0)
{
digit = num / static_cast<int>(pow(10.0, pwr));
cout << digit << " ";
sum = sum + digit;
num = num % static_cast<int>(pow(10.0, pwr));
pwr--;
}
if (pwr != -1) //Either num is 0 or there are trailing zeros in num
while (pwr != -1)
{
cout << 0 << " ";
pwr--;
}
cout << endl;
cout << "The sum of the digits = " << sum << endl;
//extraneous
/*while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;*/
}
return 0;
}
I think you should use vector to store the digits... also the logic inside should be a bit smaller (see note 1), (note that I didn't test for negatives, you may use abs from cmath)
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
//Standard library
using namespace std;
//enter function main
int main()
{
int num;
std::vector<int> digits;
int sum = 0;
int pwr = 0;
cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
while (num) {
while (num) {
int temp = num % 10;
digits.push_back(temp);
sum += temp;
num /= 10;
}
std::reverse(digits.begin(), digits.end());
cout << sum << endl;
for(auto & a : digits)
{
cout << a << " ";
}
cout << endl;
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;
}
return 0;
}
note 1:
while (num) {
int temp = num % 10;
sum += temp;
num /= 10;
}

Program debugging

The program output should look like this:
Enter an even number: 23
The number is not a positive even number.
Enter an even number: -6
The number is not a positive even number.
Enter an even number: 4
20 20.25 20.50 20.75 21
The sum is 102.5
program doesn't run properly. the odd/ even numbers are identified, but the loop to increment the variables (20 + 1 / (even number entered)) does not work right.
#include <iostream>
int main(int argc, char *argv[])
{
float val, sum, incr;
int num;
cout << "Enter an even number: ";
cin >> num;
if (num % 2 != 0)
cout << "The number " << num << " is not a positive even number." << endl;
else
cout << num << " is even!" << endl << endl;
incr = 1 / num;
for (val = 20.0F; val <= 21.0; val += incr)
{
cout << val;
sum += val;
}
cout << "The sum is " << sum << endl;
return 0;
}
If you divide one integer 1 between another num the result is an integer that as chris said is 0.
You should do:
incr = 1.0F / (float)num;
And for exiting for wrong introduced values you should return from main
#include <iostream>
int main() {
float val, sum, incr;
int num;
cout << "Enter an even number: ";
cin >> num;
if (num < 0 || num % 2 != 0){
cout << "The number " << num << " is not a positive even number." << endl;
return -1;
}
else {
cout << num << " is even!" << endl << endl;
}
incr = 1.0 / num;
for (val = 20.0F; val <= 21.0; val += incr) {
cout << val << " ";
sum += val;
}
cout << "The sum is " << sum << endl;
return 0;
}