C++ if statement not printing desired output - c++

Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}

Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.

REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}

If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}

Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}

Related

How can I get multiple numbers from a user and add even numbers together and multiply odd numbers?

I want to write a program that takes 5 inputs and adds even numbers and multiplies odd numbers, but I do not know how to do this after I know which number is odd and which is even.
#include<iostream>
using namespace std;
int main(){
int a, b, c, d, e, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9, sum10;
cout<<"Please Enter 5 Integers\t:\t";
cin>>a>>b>>c>>d>>e;
if(a%2==0 && b%2==0)
{
cout<<a+b;
sum1 = a+b;
}
if(a%2==0 && c%2==0)
{
cout<<a+c;
sum2 = a+c;
}
if(a%2==0 && d%2==0)
{
cout<<a+d;
sum3 = a+d;
}
if(a%2==0 && e%2==0)
{
cout<<a+e;
sum4 = a+e;
}
if(b%2==0 && c%2==0)
{
cout<<b+c;
sum5 = b+c;
}
if(b%2==0 && d%2==0)
{
cout<< b+d;
sum6 = b+d;
}
if(b%2==0 && e%2==0)
{
cout<<b+e;
sum7 = b+e;
}
if(c%2==0 && d%2==0)
{
cout<< c+d;
sum8 = c+d;
}
if(c%2==0 && e%2==0)
{
cout<<c+e;
sum9 = c+e;
}
if(d%2==0 && e%2==0)
{
cout<<d+e;
sum10 = d+e;
}
return 0;
}
You don't need all of those variables, and you certainly do not need to check every combination of variables one at a time. A simple loop will suffice.
Try something more like this:
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, product = 1;
cout << "Please Enter 5 Integers\t:\t";
for(int i = 0; i < 5; ++i)
{
cin >> number;
if (number % 2 == 0)
sum += number;
else
product *= number;
}
cout << sum << ' ' << product << endl;
return 0;
}
This is a very rough and relatively simple solution. It throws an exception if the input is not convertible to an int. And since the exception is not caught anywhere, the program exits if the user enters invalid input.
std::vector is roughly the same as an array. It spares you from having to declare 5 variables, and instead stores all the input values in the vector.
The stoi() function converts a string to an integer (stoi = string to integer).
#include <iostream>
#include <vector>
#include <string>
int main() {
bool outputSum, outputProduct = false;
std::vector<int> input;
for (int i = 0; i < 5; i++) {
std::string entered_string;
int entered_value = 0;
std::cout << "Please enter a number: ";
std::cin>>entered_string;
entered_value = stoi(entered_string);
input.emplace_back(entered_value);
}
int sum = 0;
int product = 1;
for (int i = 0; i < 5; i++) {
if (input[i] % 2 == 0) {
sum += input[i];
outputSum = true;
} else {
product *= input[i];
outputProduct = true;
}
}
if (outputSum) {
std::cout << "Sum: " << sum << std::endl;
}
if (outputProduct) {
std::cout << "Product: " << product << std::endl;
}
return 0;
}
I am assuming that you do not want to add the sum and the product at the end, since you didn't specify what exactly you want your output to be.
Understanding of loops makes this code very simple. You store the five numbers, but they're disconnected from each other since they're stored in separate variables. Now you have to write the many tests that you have, and it's a big mess and you feel like there has to be an easier way.
As other answers show, if you don't need to use the numbers later, then you don't need five variables for input; one is sufficient. You store the input into a variable, check if it's even/odd, and update the sum or product variable accordingly. The repetition of a loop makes this work.
If you need to display the numbers or otherwise keep them around for other purposes, an array (or std::vector in this case) comes in handy.
The code below demonstrates a C++ Standard Library function (std::reduce()) that can generate the sum or the product. Other answers do a fine job showing how to calculate those values manually. And just to re-iterate, this solution would be considered viable only if you needed the numbers for some other task.
#include <functional> // std::multiplies
#include <iostream>
#include <numeric> // std::reduce
#include <vector>
void print_container(std::vector<int> v) {
for (auto i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
constexpr int numInputs = 5;
std::vector<int> evenNums;
std::vector<int> oddNums;
for (int tmp, i = 0; i < numInputs && std::cin >> tmp; ++i) {
tmp & 1 ? oddNums.push_back(tmp) : evenNums.push_back(tmp);
}
int sum = std::reduce(evenNums.begin(), evenNums.end(), 0);
int product = std::reduce(oddNums.begin(), oddNums.end(), 1,
std::multiplies<int>());
std::cout << "Even numbers: ";
print_container(evenNums);
std::cout << "Odd numbers: ";
print_container(oddNums);
std::cout << "Sum of evens: " << sum << "\nProduct of odds: " << product << '\n';
}
Output (with input being 1 2 3 4 5):
Even numbers: 2 4
Odd numbers: 1 3 5
Sum of evens: 6
Product of odds: 15

Wrong results for fibonacci-test (C++)

I started to learn C++ and my homework is to write a code where you can enter 5 numbers and the program will tell you for each number whether it is a Fibonacci number or not.
I also tried using a do/while-loop in the isFibonacci function instead of the for-loop, but that did not fix the problem.
#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i)
{
//special cases with 0 and 1:
if ( i == 0 || i ==1) {
return true;
}
//for all other numbers:
int Fib1;
int Fib2;
int Fib3;
for (Fib3=0; Fib3>=i; Fib3++) {
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
if (Fib3==i){
return true;
}
else {
return false;
}
}
}
int main ()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
cout << "Please enter 5 numbers;" << endl;
cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i=0; i<5; i++) {
result=isFibonacci (numbers[i]);
if (result == true) {
cout << "Your number " << numbers[i] << " is a Fibonacci number!" << endl;
}
else {
cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
}
}
return 0;
}
The first Fibonacci numbers are (0),1,1,2,3,5,8,12.
So when I enter 5 numbers, for example 1,2,3,4,5 I should get a "yes" for 1,2,3 and 5, but a "no" for 4.
However, my program claims that except for 1, none of these numbers are Fibonacci numbers.
Basically your approach was a good idea. But you made some implementation errors in your check function. Like not initialized variables and wrong calculations. And look at you for loop.
Additionally. There will be a problem with big numbers.
Many very smart people, explored the Fibonacci numbers. There are whole books available. Also a Wikipedia article. See here.
Or look into that book:
The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
Or also here on stackoverflow
Therefore I will not reinvent the wheel. Here is your revised software:
#include <iostream>
#include <cmath>
#include <numeric>
// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
{
double x1 = 5 * std::pow(w, 2) + 4;
double x2 = 5 * std::pow(w, 2) - 4;
long x1_sqrt = static_cast<long>(std::sqrt(x1));
long x2_sqrt = static_cast<long>(std::sqrt(x2));
return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
}
}
int main()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
std::cout << "Please enter 5 numbers;" << std::endl;
std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i = 0; i < 5; i++) {
result = isFibonacci(numbers[i]);
if (result == true) {
std::cout << "Your number " << numbers[i] << " is a Fibonacci number!" << std::endl;
}
else {
std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
}
}
return 0;
}

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

Copying from input to the output text file

Hi guys here is my functional code but it does not works properly it should do read numbers from input.txt and count the sum of even,odd numbers in each line then conjunction of prime numbers( which does correctly) and also copy all numbers which are prime to the output.txt
here is my code the problem is : it copies also numbers which are not prime numbers. Thanks a lot !!!
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream read;
read.open("input.txt");
ofstream write;
write.open("output.txt");
string line;
int even, odd, primeXprime;
if(read.fail())
cout << "Cant open input.txt" << endl;
int x, p = 0;
if(read.is_open())
{
while(read, line)
{
even = odd = 0;
primeXprime = 1;
istringstream sRead(line);
while(sRead >> x)
{
if(x % 2 == 0)
even += x;
if(x % 2 != 0)
odd += x;
for(int i = 2; i <= x; i++)
{
if(x % i == 0)
p++;
if(p == 2)
{
primeXprime *= x;
write << x << " ";
p = 0;
}
else
break;
}
}
cout << "Sum of even numbers are: " << even << endl;
cout << "Sum of odd numbers are: " << odd << endl;
cout << "Sum of prime numbers are: " << primeXprime << endl;
cout << endl;
}
read.close();
write.close();
system("pause");
return 0;
}
}
Problem is with your Primality Testing algorithm , You cannot determine a number is prime or not until you divide it by all the numbers in the range [2,Sqrt(n)]
In line "if(p == 2)" you are assuming that it wont be divided by any number later on in the range .
Replace your entire for loop by
for(int i = 1; i < x; i++)
{
if(x % i == 0)
p++;
}
if(p < 2)
{
primeXprime *= x;
write << x << " ";
}
p = 0;

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)