How should i solve counting problem in my divisor program C++ - c++

hi guys i recently started learning C++ and today i got a problem with counting divisors in this program
i want my program to count the number of divisors exactly but the output show weird numbers :/
#include <iostream>
using namespace std;
int main(void)
{
int Lowest;
int Highest;
int count = 0;
cout << "Enter The Lowest Number Of Series: ";
cin >> Lowest;
cout << "Enter The Highest Number Of Series: ";
cin >> Highest;
cout << "\n Number -> Divisors ((count)) \n";
for (int i = Lowest; i <= Highest; i++)
{
cout << " " << i << " ->";
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++; // WTF
cout << " " << j;
}
}
cout << " (( count:" << count << " )) " << endl;
}
return 0;
}
for example out put for Lower=1 to Highest=10 is like this:
Enter The Lowest Number Of Series: 1
Enter The Highest Number Of Series: 10
Number -> Divisors ((count))
1 -> 1 (( count:1 ))
2 -> 1 2 (( count:3 ))
3 -> 1 3 (( count:5 ))
4 -> 1 2 4 (( count:8 ))
5 -> 1 5 (( count:10 ))
6 -> 1 2 3 6 (( count:14 ))
7 -> 1 7 (( count:16 ))
8 -> 1 2 4 8 (( count:20 ))
9 -> 1 3 9 (( count:23 ))
10 -> 1 2 5 10 (( count:27 ))
Do you guys have any idea What is Wrong?

As noted by #cigien's comment, your count variable never gets reset to zero so it just keeps counting up. Reset it between each iteration of the outer loop. Better still, move the declaration to the closest place where it's used:
#include <iostream>
using std::cin;
using std::cout; // only using what you need
int main()
{
int Lowest;
int Highest;
cout << "Enter The Lowest Number Of Series: ";
cin >> Lowest;
cout << "Enter The Highest Number Of Series: ";
cin >> Highest;
cout << "\n Number -> Divisors ((count)) \n";
for (int i = Lowest; i <= Highest; i++)
{
int count = 0; // <-- initialize to zero on every pass
cout << " " << i << " ->";
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
count++;
cout << " " << j;
}
}
cout << " (( count:" << count << " )) \n";
}
return 0;
}

Related

the code still print 0 and it can't calculate the required task

#include <iostream>
using namespace std;
int main()
{
int n, G;
float num[500], sum=0.0, average,Grades;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 500 || n <= 0)
{
cout << "Error! number 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 number: ";
cin >> num[G];
sum += num[G];
}
average = sum / n;
Grades = num[G] >= average;
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average : " <<Grades<< endl;
cout << "Number of grades above the Average = "<<(int) Grades;
return 0;
}
i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0
i tried to print the Grades >= the avg but it print 0
also num of Grades also print 0
where is the error ?
I think you was trying to do something like this:
...
int grades_on_avg, upper_grades = 0;
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
for(int i = 0; i < n; ++i) // use separate for loop and redefined index
{
if(num[i] == average) // compare to average
grades_on_avg++;
else if(num[i] > average) // if bigger than average
upper_grades++;
}
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg + upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;
You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:
...
int avgGrades{0};
int avgAboveGrades{0};
for(int i{0}; i < n; ++i)
{
if(num [i] == average)
{
++avgGrades;
}
else if(num [i] > average)
{
++avgAboveGrades;
}
}
If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.

How do you add numbers in a while loop for c++?

#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
int main()
{
// Declarations
int firstNum = 0, secondNum = 0;
cout << "This program will ask you for two numbers, and then output the even numbers between those two numbers" << endl;
cout << "Please enter the lowest number: " << endl;
cin >> firstNum;
cout << "Please enter the highest number: " << endl;
cin >> secondNum;
if (firstNum % 2 != 0 && secondNum % 2 != 0)
{
while (firstNum <= secondNum)
{
if (firstNum % 2 != 0)
{
cout << firstNum << " ";
}
firstNum++;
}
}
else if (firstNum % 2 == 0 && secondNum % 2 == 0)
{
while (firstNum <= secondNum)
{
if (firstNum % 2 == 0)
{
cout << firstNum << " ";
}
firstNum++;
}
}
return 0;
}
I'm doing a coding exercise for c++, if the user inputs two odd numbers the program would then output all of the odd numbers between the first and second number (first number has to be smaller than the second). If both numbers are even then the program will out put the sum of the even numbers between the first and second (again the first has to be the smallest). My problem is that I do not know how to add the numbers together, I only know how to print either the even or odd numbers between them.
An example:
first number = 4
second number = 36
output = 340
how do you add the even numbers between them?
You could have a variable that stores the result. For example
else if (firstNum % 2 == 0 && secondNum % 2 == 0)
{
int sum = 0; // store the sum of all even numbers
while (firstNum <= secondNum)
{
sum += firstNum; // adding the number to the sum
firstNum += 2; // increment by 2 would skip all the odd numbers
}
cout << sum << endl;
}
Hopefully this helps!
My problem is that I do not know how to add the numbers together - If that is the exact question and assuming start and end are the start and end numbers you can do this to get the sum of all numbers between start and end
int sum = 0;
for ( int i = start; i <= end; i++ )
{
sum += i;
}
std::cout << "Sum of numbers between " << start << " and end " << end << " is " << sum ;
to get the sum of all even numbers in that range
int sum = 0;
for ( int i = start; i <= end; i++ )
{
if ( i%2 == 0 ) // even
sum += i;
}
std::cout << "Sum of even numbers between " << start << " and end " << end << " is " << sum ;
I see you wanted it using while loop in which case
int sum = 0;
while ( start <= end )
{
sum += start;
++start;
}

Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s and 2 as last

I need to Write a C ++ program that prompts the user to enter 10 integers in the array.
Input numbers are: 0, 1 or 2.
The program should extract the array that is entered on the screen Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s
and all 2 as the last.
Arranged array displays on the screen.
Have been struggling over this for few hours now. Im stuck and dont know how to show Output .
Input should be for example 0 0 1 0 1 2 2 2 0 1
Output 0000111222
HOW?
int main ()
{
int t [N], i, ;
cout << "Enter 10 arrays from 0-2" << endl;
cout << "Original array:";
for (i = 0; i <N; i ++)
{
cin >> t [i];
}
if (t [i]> = 0 && t [i] <= 2)
{
cout << "Rearranging elements of array:" << ? << endl;
}
cout << "End of the program!"
return 0;
}
when you do
if (t [i]> = 0 && t [i] <= 2)
i equals N so you access out of the array, and of course that does not sort the array
You do not check if cin >> t[i] success so if the user enter something else than an int all the entries from the current will not be set (they will be 0 in case you use a std::vector)
A first way is to do without taking account the range 0..2, replace int t[n] by std::vector<int> t(N) and use sort(t.begin(), t.end()) to sort your array
The complexity is O(N*log(N)) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range 0..2" << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < 0) || (t[i] > 2))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (i = 0; i < N; ++i) cout << ' ' << t[i]; // old way to do
cout << endl;
sort(t.begin(), t.end());
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v; // new way to do
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:aze
not a number
value #0:-2
value out of range
value #0:3
value out of range
value #0:2
value #1:0
value #2:1
value #3:2
value #4:0
value #5:2
value #6:1
value #7:0
value #8:0
value #9:1
Original array: 2 0 1 2 0 2 1 0 0 1
Sorted array: 0 0 0 0 1 1 1 2 2 2
End of the program!
A second way considering a range [min .. max] not too large is to count the number of each value then fill the array to respect these counts
The complexity is O(2N) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MIN 0
#define MAX 2
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range " << MIN << ".." << MAX << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < MIN) || (t[i] > MAX))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
// count numbers
vector<size_t> counts(MAX - MIN + 1);
for (auto v : t) counts[v - MIN] += 1;
// fill again
i = 0;
for (int r = MIN; r <= MAX; ++r) {
size_t n = counts[r - MIN];
while (n--) t[i++] = r;
}
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s2.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:a
not a number
value #0:3
value out of range
value #0:0
value #1:2
value #2:1
value #3:1
value #4:2
value #5:2
value #6:2
value #7:0
value #8:1
value #9:2
Original array: 0 2 1 1 2 2 2 0 1 2
Sorted array: 0 0 1 1 1 2 2 2 2 2
End of the program!
Specifically for values between 0 and 2 (in fact for 3 possible values) as said in a remark by #PaulMcKenzie you can use the Dutch national flag problem and look at that question : R G B element array swap
The complexity is O(N) (here N is 10)
As a beginner, you may want to try this (this is the simplest solution I could think of without using other libraries):
int main () {
const int size = 10;
int arr[size], temp = 0;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
for (int j = 0; j < size - 1; j++) {
for (int k = 0; k < size - j - 1; k++) {
if(arr[k] > arr[k+1]) {
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
else
continue;
}
}
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
I hope this helps you.
1st answer is too difficult for me, im only beginner not knowing what im doing yet.
2nd answer is to that direction where it should be right but i need to put in that input cant be more than 2 or less than numeber 0, thats the problem now :D
Im sorry, i just cant get to that point where i understand that syntax.

Dividing a number in loop until it satisfies a condition = 0

I have to input a value in the program and keep dividing it by 4 until it reaches the number 0. But when I run it, it doesn't stop at 0, it keeps repeating 0 forever. What is wrong with the code?
#include <iostream>
using namespace std;
int main(){
double input;
cout << "Enter an Integer: ";
cin >> input;
cout << input << "/ 4 ";
do
{
input = input / 4;
if (input >= 0)
cout <<" = "<< input << endl;
cout <<input << " /4";
}
while ((input >= 0) || (input != 0));
return 0;
}
Here are my three cents.:)
#include <iostream>
int main()
{
const long long int DIVISOR = 4;
while ( true )
{
std::cout << "Enter an Integer (0 - Exit): ";
long long int n;
if ( not ( std::cin >> n ) or ( n == 0 ) ) break;
std::cout << std::endl;
do
{
std::cout << n << " / " << DIVISOR;
n /= DIVISOR;
std::cout << " = " << n << std::endl;
} while ( n );
std::cout << std::endl;
}
return 0;
}
The program output might look like
Enter an Integer (0 - Exit): 1000
1000 / 4 = 250
250 / 4 = 62
62 / 4 = 15
15 / 4 = 3
3 / 4 = 0
Enter an Integer (0 - Exit): 0

Output odd numbers between 2 integers in C++

I have completed code that works for the majority of cases for outputting odd numbers between two integers in C++. However it doesn't work for negative numbers and/or if the two values are less than 3 in difference from one another (e.g. it works if the two numbers are 2 & 5, but does not work if the two numbers are 2 & 4).
I know that it is a cause of my code which adds 2 every time the while loop iterates, I'm just not sure how to rectify it.
while (secondOddNum - firstOddNum > 2)
{
if (firstOddNum % 2 > 0) //positive numbers
{
firstOddNum += 2;
sumOdd += pow(firstOddNum,2);
cout << firstOddNum << endl;
} else // even numbers
{
firstOddNum += 1;
sumOdd += pow(firstOddNum,2);
cout << firstOddNum << endl;
}
Thanks
I think your logic is overcomplicating the problem a little bit. Did you mean to do something like this?
void OutputOdds(int min, int max)
{
for(int i = min; i <= max; i++)
{
if(i % 2 == 1 || i % 2 == -1)
cout << i << " ";
}
}
Tests:
OutputOdds(-25, 6);
cout << endl << endl;
OutputOdds(1, 3);
cout << endl << endl;
OutputOdds(2, 4);
prints
-25 -23 -21 -19 -17 -15 -13 -11 -9 -7 -5 -3 -1 1 3 5
1 3
3
You can try something like this:
void printOddsBetween(int min, int max) {
int t = min + (min % 2 == 0);
while (t <= max) {
cout << t << endl;
t += 2;
}
}
It starts at the closest odd value to min. Then just prints every odd value up to max.
int min = 1;
int max = 11;
int counter = 0;
for (int i = min; i <= max; i++) {
if (i % 2 != 0) {
System.out.println(i);
counter += 1;
}
}
System.out.println("counter" + counter);
int xx[] = new int[counter];
int ii = 0;
for (int i = min; i <= max; i++) {
if (i % 2 != 0) {
xx[ii] = i;
ii += 1;
}
}
int firstNum{}, secondNum{};
cout << "Enter two numbers, the first smaller than the second."
<< endl;
cout << "Enter first integer: \t";
cin >> firstNum;
cout << endl;
while (firstNum < secondNum);
{
cout << "Enter second integer: \t";
cin >> secondNum;
cout << endl;
cout << "\nOdd numbers from " << firstNum << " to " << secondNum << " are \n";
for (int i = firstNum; i <= secondNum; i++)
{
if (i % 2 != 0)
{
cout << i << " ";
}
}
}
Prints: 2 & 19 ARE MY USER INPUTS
Enter two numbers, the first smaller than the second.
Enter first integer: 2
Enter second integer: 19
Odd numbers from 2 to 19 are
3 5 7 9 11 13 15 17 19