#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;
}
Related
Total Noob here, I am having a hard time with an assignment. I am taking a beginner course in C++ and have to figure out how to calculate the sum of negative integers and their avg. Sum of positive integers and the avg. And the sum of all numbers and the avg. I have gotten the last part already but how do I calculate the sum of negative integers and avg, and positive integers and avg using a while loop?
I provided my code below.
#include <iostream>
using namespace std;
#include <iomanip>
int main(int argc, const char * argv[]) {
int x;
double avg = 0.0;
int count = 0;
int sum = 0;
// ask users for input
cout << ("Welcome to the greatest calculator!\n");
cout << ("Please enter 10 integers seperated by spaces \n");
do {
std::cin >> x;
sum = sum + x;
count = count + 1;
}
while (count < 10);
// calculate average
avg = sum/10.0;
// output average
cout << fixed;
cout << "For all 10 numbers the sum is " << sum << "." "The average is " << setprecision (2) << sum/10.0 <<".\n";
return 0;
}
The output should look something like this.
Please enter 10 integers separated by spaces:
1 -1 45 17 28 -2 0 9 -14 11
Upon our intelligent calculations, here is the result:
+ There are 7 positive numbers, sum = 111.00 and average = 15.86
+ There are 3 negative numbers, sum = -17.00 and average = -5.67
+ For all 10 numbers, sum = 94.00 and average = 9.40 */
Use two variable int negativeVar=0 , PositiveVar=0 . In the loop try a condition if(GivenNumber<0) to detect the given number is negative or positive. Then add all positive and negative value separately and make avarage.
(Sorry for bad english)
You can do like this (notice comments):
#include <iostream>
int main(void) {
// Declaration and initialization of the required variables
float cPositive = 0.0f;
float cNegative = 0.0f;
int it = 0;
std::cout << "Enter 10 numbers (floating point assignable): \n";
// Looping till 10 iterations
do {
float temp;
std::cin >> temp;
// If the number is greater than zero, i.e. (+ve) then cPositive sums up
// otherwise, cNegative
if (temp > 0) cPositive += temp;
else if (temp <= 0.0f) cNegative -= temp;
} while (++it < 10); // Increment and comparison together
// Final results
std::cout \
<< "Sum of positive: " << cPositive << std::endl
<< "Sum of negative: -" << cNegative << std::endl;
return 0;
}
A simple test case:
Enter 10 numbers (floating point assignable):
10.5
-1.5
2.2
5.5
-3.8
-99.3
10
4.5
-1.0
0
Sum of positive: 32.7
Sum of negative: -105.6
Moreover, if you want to see average, then declare two variables, pos and neg where both are initially zero. After that, when a positive number or negative number occurs, just increment pos or neg and divide with them by cPositive or cNegative respectively.
#include <iostream>
#include <string>
using namespace std;
int main()
{
// lets declare some variable first.
int positiveSum =0; //this will hold sum of positive nums
int negativeSum =0; // this will hold sum of negative nums
int totalSum =0; // this will hold sum of all the nums
int number=0; // user input for number
for (int i = 1; i <=10; i++) // loop from 1 to 10 times
{
cout << " Enter a number: ";
cin >> number;
// now check if number is positive or negative
if (number >=0)
{
positiveSum += number; // adds this number to positiveSum
}
else if (number < 0)
{
negativeSum += number; // adds this number to negativeSum
}
}
// So finally add the positiveSum and negativeSum to get the totalSum
totalSum = positiveSum + negativeSum;
cout << endl;
cout << " Total of Positive numbers is: " << positiveSum << endl;
cout << " Total of Negative numbers is: " << negativeSum << endl;
cout << " Total of all numbers is: " << totalSum << endl;
return 0;
}
The code below produces the following output:
$ ./main
The (sum, avg) of negative integers = (-15, -5)
The (sum, avg) of positive integers = (6, 2)
The (sum, avg) of all numbers = (-9, -1.5)
Please read the comments because they are in fact the detailed answer.
#include <array>
#include <iostream>
int main()
{
// For convenience, keep the numbers in an std::array. std::vector is
// equally convenient.
std::array<int, 6> integers { 1, -4, 2, -5, 3, -6 };
// Define variables that store the sums and the counts.
int positiveSum = 0;
int positiveCnt = 0;
int negativeSum = 0;
int negativeCnt = 0;
// Iterate over the numbers taking one of them at a time.
int i = 0;
while (i < integers.size())
{
int number = integers[i];
// Is the number positive?...
if (number >= 0)
{
// ... it is - add it to the positive sum and increment the count.
positiveSum += number;
++positiveCnt;
}
// The number is not positive, so it must be negative...
else
{
// ... add it to the negative sum and increment the count.
negativeSum += number;
++negativeCnt;
}
// Get ready for the next number.
++i;
}
// Time to print out the results.
// Note that before we calculate the average, we have to cast at least one
// of the terms of the division to floating point type. Otherwise the
// division will be done with integers where the result is also an integer
// (e.g. 3 / 2 -> 1).
// Only affter the casting you will be getting expected answers
// (e.g. double(3) / 2 -> 1.5).
std::cout <<
"The (sum, avg) of negative integers = (" <<
negativeSum << ", " <<
double(negativeSum) / negativeCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of positive integers = (" <<
positiveSum << ", " <<
double(positiveSum) / positiveCnt << ")" << std::endl;
std::cout <<
"The (sum, avg) of all numbers = (" <<
negativeSum + positiveSum << ", " <<
double(negativeSum + positiveSum) / (negativeCnt + positiveCnt) << ")" << std::endl;
}
#include <iostream>
using namespace std;
int main()
{
char op;
float num1,num2;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
//If the operator is other than +,-,*,/, error message is shown.
cout << "Error! operator is not correct";
break;
}
return 0;
}
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
I spent a day on this code for count even and zero and odd numbers
From long datatype I used a function to send data. Here is the code
#include <iostream>
using namespace std;
void digitCount(long long int &num);
int main ()
{
long long int num;
cout <<"Enter any No. " <<endl;
cin >>num;
cout <<endl;
digitCount(num);
return 0;
}
void digitCount(long long int &num)
{
int e = 0, z = 0, o = 0, x = 0;
for (int i = 0; i <= num; i++)
{
x= num % 10;
if(x == 0)
{
++z;
num = num / 10;
}
else if(x%2==1)
{
++o;
num = num / 10;
}
else
{
++e;
num = num / 10;
}
}
cout << "No of zeros Digits = " << z<< endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
the problem is when I count odd numbers there is a number missed
for example when i input : 12345
the result is
no of even : 2
no of odd : 2 (should be 3)
no of zero : 0
and here the question :
Write a function that takes as parameter an integer (as a long value) and returns the number of odd, even, and zero digits. Also write a program to test your function. Use pass by reference method.
Instead of the for loop you should use:
while (num > 0)
You're constantly changing num and when it gets to 1 (in your 12345 example), i is at 3. I also modified your digitcount to demonstrate some decent formatting for readable code.
void digitCount(long long int &num) {
int e(0), z(0), o(0), x(0);
while (num > 0) {
x = num % 10;
if (x == 0) {
z++;
}
else if (x % 2 == 1) {
o++;
}
else {
e++;
}
num /= 10;
}
cout << "No of zeros Digits = " << z << endl;
cout << "No of odd Digits = " << o << endl;
cout << "No of Even Digits = " << e << endl;
}
If you believe this solves your problem && is the best answer, please click the checkmark next to this answer. Thanks
I am working on an exercise from my C++ book and I'm not sure how to fix it. I am supposed to get an int from the user and display the individual digits in the order they were entered. For instance 12345 would be displayed 1 2 3 4 5. 7365 would be displayed 7 3 6 5. I have most of the code written but there is a logical error and I can't figure it out. Here is my code:
int main()
{
int number = 0;
int digit = 0;
int temp = 0;
int counter = 0;
int sum = 0;
int divisor = 0;
cout << "Please enter a nonzero number.";
cin >> number;
cout << "\nThe number you entered was " << number;
// Determine the number of digits
temp = number;
while (temp != 0)
{
temp = temp / 10;
counter++;
}
cout << "\nThere are " << counter << " digits in your number.";
// Separate the digits
temp = number;
cout << "\nSeparating the digits\n";
do
{
divisor = (pow(10.0, --counter));
digit = temp / divisor;
temp = temp % divisor;
cout << digit << " ";
sum = sum + digit;
}
while (counter != 0);
cout << "\nThe sum of the number is " << sum;
return 0;
}
When I enter 5555 the output is 5560. When I enter 1234 the output is 1236. Can anyone help me find my error?
Here's one version:
// If the number is only one digit, print it.
// Otherwise, print all digits except the last, then print the last.
void digits(int x)
{
if (x < 10){
cout << x;
}
else{
digits(x / 10);
cout << " " << x % 10;
}
}
Thank you all for your help :-) Turns out my code works fine in another compiler so I guess it's just a netbeans glitch.
I have been trying to finish this code (function) for a while now, but am stuck on the last part. In this code, I prompt the user to select a number of integers and any number of digits and then find the smallest and largest value within these digits. On the next part, I am supposed to determine which of the given digits the smallest and largest are located such that the output should be:
Digit _ can be found in integer number(s): _, _
I apologize in advance if my code is sloppy; I just started learning C++ and haven't fully grasped the language yet.
int digitSizeLoca() {
int userNumInteger;
int* iPtr;
int* iPtr2;
int* iPtr3;
int value;
int value2;
int value3;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
iPtr2 = new int[userNumInteger];
iPtr3 = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++) {
*(iPtr3 + 1) = *(iPtr2 + 1) = *(iPtr + 1);
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + 1);
}
value = *(iPtr + 1);
value2 = *(iPtr2 + 1);
value3 = *(iPtr3 + 1);
if (value != 0, value2 != 0, value3 != 0) {
if (value <= 0)
value = -value;
if (value2 <= 0)
value2 = -value2;
if (value3 <= 0)
value3 = -value3;
int lDigit;
int sDigit;
int curDigit;
int pot = 10;
lDigit = sDigit = value % pot;
while (value, value2, value3) {
if (value / pot == 0, value2 / pot == 0, value3 / pot == 0) break;
curDigit = (value / pot, value2 / pot, value3 / pot) % 10;
if (curDigit < sDigit)
sDigit = curDigit;
if (curDigit > lDigit)
lDigit = curDigit;
pot*=10;
}
std::cout << "\nThe smallest digit: " << sDigit << std::endl
<< "\n Digit " << sDigit
<< " can be found in integer number(s): ";
std::cout << "\nThe largest digit: " << lDigit << std::endl
<< "\n Digit " << lDigit
<< " can be found in integer number(s): ";
}
return 0;
}
Example of what output should be given user input:
If user chooses 2 for userNumInteger, and inputs the digit values 1234 and -1578,
the output for my question should be:
Smallest digit: 1
Digit 1 can be found in integer number(s): 1, 2
.
.
.
Thank you!
If digits matter, then input 02 is not the same as 2 (even if both means the number 2; beware that 02 could be an octal notation). So you should read a std::string, check that it has digits appropriately using isdigit, then use std::stol (in C++11) or strtol to do the conversion.
You'll better use some std::vector<int> instead of initializing a pointer with new int[userNumInteger] ...
Since you mentioned that you can only use integer for now, it makes your life a bit difficult. Basile was right when he mentioned that you should use string. That would help you iterating through the numbers over and over again like I did below but it does the task - the drawback being that you will have to iterate 3 times but if you do not want to sort or do anything special then it is good enough....
int digitSizeLoca()
{
int userNumInteger;
int* iPtr;
int lowest = 9;
int highest = 0;
std::cout << "\nHow many integers? ";
std::cin >> userNumInteger;
iPtr = new int[userNumInteger];
for (int i = 0; i < userNumInteger; i++)
{
std::cout << "\nEnter digit #" << i + 1 << ": ";
std::cin >> *(iPtr + i);
}
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
std::cout << "You Entered (" << i << "): " << *(iPtr + i) << std::endl;
do
{
int remainder = number % 10;
if (remainder > highest) highest = remainder;
if (remainder < lowest) lowest = remainder;
number = number / 10;
}
while (number > 0);
}
std::cout << "\nThe largest digit: " << highest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == highest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
std::cout << "\nThe smallest digit: " << lowest << std::endl
<< " can be found in integer number(s): ";// Notice no endl here
for (int i = 0; i < userNumInteger; i++)
{
int number = *(iPtr + i);
do
{
int remainder = number % 10;
if (remainder == lowest)
{
std::cout << (i+1) << ",";
break;
}
number = number / 10;
}
while (number > 0);
}
std::cout << std::endl;
}