How to prevent a final cout in a loop from being executed? - c++

I am trying to write a code which gives the prime factorization of given integer.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void primefactor(int a);
int main()
{
int n;
cout<<" Enter the value of n "<<endl;
cin>>n;
primefactor(n);
return 0;
}
void primefactor(int a){
while(a%2==0){
cout<<"2*";
a/=2;
for(int i=3; i<=sqrt(a); i+=2){
while(a%i==0){
cout<<i<<"*";
a=a/i;
}
}
if(a>2){
cout<<a<<endl;
}
}
however when i run the output at the last factor i am getting an additional * in factorization. How can I remove this?

You can use
if (a != 2)
cout<<"2*";
else
cout<<"2";
instead of cout<<"2*";

I had the same issue and solved it with a goto statement.
#include <iostream>
#include <math.h>
using namespace std;
void primeFactorization(int number) {
cout << number << ": ";
// WHILE number is even
while (number % 2 == 0) {
// SET number = number / 2
number = number / 2;
// PRINT 2
cout << 2 << " " ;
// END WHILE
}
// GOTO TERMINAL
reloop:
// FOR factor in 3 to the sqrt(number), by 2
for (int factor = 3; factor <= sqrt(number); factor = factor + 2) {
// IF number modular factor equals 0 THEN
if (number % factor == 0) {
// PRINT factor
cout << factor << " " ;
// SET number = number / factor
number = number / factor;
// GOTO INITIAL
goto reloop;
// END IF
}
// END FOR
}
//IF number > 2 THEN
if (number > 2) {
//PRINT number
cout << number;
//END IF
}
cout << endl;
}
int main() {
int usersNumber;
bool userWants2Play = true;
while (userWants2Play) {
cout << "Please enter a number to be factored: " ;
cin >> usersNumber;
primeFactorization(usersNumber);
cout << "Do you want to play again? 1 or 0: " ;
cin >> userWants2Play;
}
return 0;
}
The goto statement allows for the new odd number to go through the loop again. This lets the odd prime factors print and allows the new old number to be factored again, if the factor exists.

Related

C++ if statement not printing desired output

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";
}

write program to display odd and even numbers

im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}

Use while loop to print series of even and odd numbers

I know I'm missing something real simple but I can't seem to get the numbers to print out in rows of just odd or just even numbers using a while loop or loops. Also It keeps printing out "the even numbers are:"/ "the odd numbers are:" for every number.
#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
while (n <= 100) //loop only if n equals 100 or less
{
for(number = n; number <= n; number++) //for loop to increment int value
{
if(number % 2 !=0) //determines if odd
{
cout << "The odd numbers are:" <<number << endl; //prints odd values
}
}
for(number = n;number <= n; number++) // for loop to increment int value
{
if(number % 2 ==0) //determines if even
{
cout <<"The even numbers are:" <<number <<endl; //prints even values
}
}
n++;
}
return 0; //end of program
}
You may want this:
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
// print odd values
cout << "The odd numbers are:";
for (number = n + 1 - (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
// print even values
cout << "The even numbers are:";
for (number = n + (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
return 0; //end of program
}

Checking Palindrome numbers function recursively in C++

I don't how to get it work recursively.
I'm trying to code the Palindrome function recursively. I understand what should i do like that:
1 => single digit, therefore yes
--------
12 => 1 != 2, therefore no
--------
121 => 1 == 1, therefore yes
2 => single digit, therefore yes
--------
1234421 => 1 == 1, therefore yes
23442 => 2 == 2, therefore yes
344 => 3 != 4, therefore no
However, i got a question. It doesn't work recursively. I need help.
Do i miss something?
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace std;
bool isPalindrome(int number, int factor);
int main()
{
int number; // a positive integer
cout << "Enter a positive integer: ";
cin >> number;
// puts 10^(numDigits-1) (i.e., the smallest numDigits-digit positive integer) into factor
int temp = number;
int factor = 1; // power of ten
while (temp > 9)
{
temp /= 10;
factor *= 10;
}
// print whether the number is a palindrome
if (isPalindrome(number, factor))
cout << endl << number << " is a palindrome." << endl << endl;
else
cout << endl << number << " is not a palindrome." << endl << endl;
system("pause");
}
bool isPalindrome(int number, int factor){
int checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
isPalindrome(number / 10, factor / 10);
}
else
{
return false;
}
}
else
{
return true;
}
}
Two things.
The return value of isPalindrome() is not used when called recursively. Add it as a return statement.
return isPalindrome(number / 10, factor / 10);
Also the factor reduces by 100 every time you check two digits. So divide factor by 100.
return isPalindrome(number / 10, factor / 100);
Thanks a lot!!
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace std;
bool isPalindrome(int number, int factor);
int main()
{
int number; // a positive integer
cout << "Enter a positive integer: ";
cin >> number;
// puts 10^(numDigits-1) (i.e., the smallest numDigits-digit positive integer) into factor
int temp = number;
int factor = 1; // power of ten
while (temp > 9)
{
temp /= 10;
factor *= 10;
}
// print whether the number is a palindrome
if (isPalindrome(number, factor))
cout << endl << number << " is a palindrome." << endl << endl;
else
cout << endl << number << " is not a palindrome." << endl << endl;
system("pause");
}
bool isPalindrome(int number, int factor){
int checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
return isPalindrome(number / 10, factor / 100);
}
else
{
return false;
}
}
else
{
return true;
}
}

Reversing a number C++

Looking for some advice here on what I'm getting wrong. Everything in my main should be fine and left unchanged. My problem is in my reverse function. It's printing the reversed number right before the cout statement of "The number is" instead down below where it should be. I spent awhile trying to fix but can't come up with a solution.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NUM_VALS = 10; //the maximum number of values to use
int reverse(int num);
bool isPrime(int num);
int main()
{
int number, //Holds the random number that is manipulated and tested
loopCnt; //Controls the loop
//set the seed value for the random number generator
//Note: a value of 1 will generate the same sequence of "random" numbers every
// time the program is executed
srand(1);
//Generate 10 random numbers to be manipulated and tested
for( loopCnt = 1; loopCnt <= NUM_VALS; loopCnt++ )
{
//Get a random number
number = rand();
//Display the sum of adding up the digits in the random number, the reversed
//random number, and whether or not the number is palindromic or a prime number
cout << "The number is " << number << endl
<< "----------------------------------------" << endl
// << "Adding the digits result" << setw(16) << sumDigits( number ) << endl
<< "Reversing the digits result" << setw(13) << reverse(number) << endl
// << "Is the number a palindrome?" << setw(13) << (isPalindrome(number)? "Yes" : "No") << endl
// << "Is the number prime?" << setw(20) << (isPrime(number)? "Yes" : "No") << endl
<< endl << endl;
}
return 0;
}
int reverse(int num)
{
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
cout << rem;
quo /= 10;
}
}
bool isPrime(int num)
{
int i;
if (num % 2 == 0)
return false;
for (i = 3; i*i <= num; i+=2)
{
if (num % i == 0)
return false;
}
return true;
}
You need to have your reverse function return the number as reversed, because the return value is used in main.
You can build the reversed number by multiplying a "reversed" value by 10, then adding in the remainder:
int reverse(int num)
{
int reversed = 0;
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
reversed = reversed * 10 + rem;
quo /= 10;
}
return reversed;
}
You can also use this method to reverse a number by taking string input and then reverse it and convert it to int.
#include <iostream>
#include<string>
using namespace std;
int reverse_num(string a)
{
string s;
for(int i=a.length()-1;i>=0;i--)
{
s+=a[i];
}
int n;
n=stoi(s);
return n;
}
int main()
{
string a;
cin>> a;
cout<<reverse_num(a);
return 0;
}