Why is my code stopping prematurely? what have i done wrong? - c++

I'm just starting so I'm trying to write a program which determine if a number is positive or negative.
#include <iostream>;
int step_function(int x) {
int result = 0;
if (x > 0)
result = 1;
else if (x < 0)
result = -1;
else
result = 0;
return result;
}
using namespace std;
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
int a = step_function(num);
if (a == 1)
printf("%d is positive", num);
else if (a == -1)
printf("%d is negative", num);
else
printf(" it is zero");
return 0;
}

There is a few things you should do:
First things first you should get yourself a Good Book for C++.
Second thing is read why using namespace std; is a bad idea.
Lastly here is your code fixed. You needed to remove the semicolon as well as removing the printf(). I also removed the using namespace std; which made it more readable.
#include <iostream>
int step_function(int); //Function prototype
int main() {
int num;
std::cout << "please enter number : ";
std::cin >> num;
int a = step_function(num);
if (a == 1)
std::cout << num << " is postive";
else if (a == -1)
std::cout << num << " is negative";
else std::cout <<" it is zero";
return 0;
}
int step_function(int x)
{
int result = 0;
if (x > 0) result = 1;
else if (x < 0) result = -1;
else result = 0;
return result;
}

Don't use semicolon after #include <iostream>.
I think for C++ cout is more standard whereas printf is from C.
You can also include printing of the text in the step_function. Also, it's better to use braces {} after if and else statements for clarity especially if the code becomes complex.
#include <iostream>
using namespace std;
void step_function(int x) {
if (x > 0) {
cout << x << " is positive" << endl;
}
else if (x < 0) {
cout << x << " is negative" << endl;
}
else {
cout << "it is zero" << endl;
}
}
int main() {
int num;
cout<< "please enter number : ";
cin >> num;
step_function(num);
return 0;
}

Related

display all the Prime numbers which are less than certain number

I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
if (isPrime(Num))
{
cout << " is a Prime number." << endl;
}
else
cout << " is not a Prime number." << endl;
return 0;
}
//isPrime
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else if
for(int n = 2; n < 200; n++) { // HERE
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if(isPrime == true)
cout<<n<<" ";
}
return 0;
else
return false;
}
}
}
return false;
}
You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
// Check numbers here
for(int n = 2; n < 200; n++) {
if (isPrime(n)){
cout << n << " is a Prime number." << endl;
}
}
return 0;
}
//isPrime - This is your original isPrime Code
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else
return false;
}
}
}
return false;
}

How to countdown to 0 C++

I need to count down to 0. I am only printing 0 to the screen. How can I print all the count-down characters to the screen? Below is the code I am using right now.
#include <stdio.h>
#include <iostream>
using namespace std;
class Solution {
public:
int num;
int numberOfSteps (int num)
{
while (num != 0)
{
if (num % 2 == 0)
{
num = num / 2;
cout << num;
}
else
{
num = num - 1;
cout << num;
}
}
}
};
int main () {
int num;
Solution myObj;
cin >> num;
cout << myObj.num;
}
You're passing the num to std::cout. You are also not calling numberOfSteps(...) anywhere in your code.
Replacing the line with cout << myObj.numberOfSteps(num); fixes the problem, but a tidier solution would be as follows:
#include <stdio.h>
#include <iostream>
void countDown (int num) {
while (num != 0) {
if (num % 2 == 0) {
num = num / 2;
std::cout << num << std::endl;
} else {
num = num - 1;
std::cout << num << std::endl;
}
}
}
int main () {
int num;
std::cin >> num;
countDown(num);
}
Class is not necessary as there is no state and the function is void since it does not return anything.
I am revisiting this question and have created a simpler solution than my original post:
#include <iostream>
using namespace std;
int num;
int main()
{
cout << "Please enter the number you would like to count down to zero : ";
cin >> num;
while (num > 0)
{
cout << num << endl;
num--;
}
cout << "The number is now zero.";
return 0;
}

Roman Numeral Output in C++ is always "-858993460", not sure why?

I am relatively new to C++ and have some experience in Java with classes and functions but now very much, so this program is giving me some issues. Below is the code I have, everything seems right now to me and even though I have set "num" to 0, it always prints out "-858993460".
Here are my header files:
#include <string>
using namespace std;
class romanType
{
public:
void setRoman(string n);
void romanToPositiveInteger();
void printPositiveInteger() const;
romanType();
romanType(string n);
void printNum();
private:
string romanString;
int num;
};
Here is my implementation file:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "romanType.h"
using namespace std;
int value(char num) {
if (num == 'I')
return 1;
if (num == 'V')
return 5;
if (num == 'X')
return 10;
if (num == 'L')
return 50;
if (num == 'C')
return 100;
if (num == 'D')
return 500;
if (num == 'M')
return 1000;
return -1;
}
void romanType::setRoman(string n) {
romanString = n;
}
void romanType::romanToPositiveInteger() {
num = 0;
for (int i = 0; i < romanString.length(); i++)
{
// Getting value of symbol s[i]
int s1 = value(romanString[i]);
if (i + 1 < romanString.length())
{
// Getting value of symbol s[i+1]
int s2 = value(romanString[i + 1]);
// Comparing both values
if (s1 >= s2)
{
// Value of current symbol is greater
// or equal to the next symbol
num = num + s1;
}
else
{
num = num + s2 - s1;
i++; // Value of current symbol is
// less than the next symbol
}
}
else
{
num = num + s1;
i++;
}
}
}
void romanType::printPositiveInteger() const {
cout << num << endl;
}
romanType::romanType(string n) {
romanString = n;
}
romanType::romanType() {
}
void romanType::printNum() {
cout << num << endl;
}
And here is my main file:
#include "stdafx.h"
//Main program
#include <iostream>
#include <string>
#include "romanType.h"
using namespace std;
int main()
{
romanType roman;
string romanString;
while (romanString != "EXIT") {
cout << "Enter a roman number: ";
cin >> romanString;
roman.printNum();
roman.setRoman(romanString);
cout << "The equivalent of the Roman numeral "
<< romanString << " is ";
roman.printPositiveInteger();
cout << endl;
cout << endl;
}
//Pause the program
std::cout << "\n\n---------------------------------\n";
system("pause");
//Exit the program
return EXIT_SUCCESS;
}
As I said previously, I am currently held up on the output part, but since I am new and this code is most likely horrid, I am accepting any critique on it. I will be a pretty busy today with work and wont be able to implement any suggestions until the next day, but I will get back to anyone that has a solution as soon as I am able to! Thanks in advance for any help :)
You need to call roman.romanToPositiveInteger() at some point between roman.setRoman(romanString); and roman.printPositiveInteger();

Prime-testing program not working

#include "stdafx.h"
#include "math.h"
#include <string>
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 1;
int i = 0;
while (i == 0 && y < sqrtf(x))
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
if (i == 1)
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
}
return 0;
}
This is a code I created to test for primes. After sorting out several debugging issues I was able to run it.
It opened the command window, read 'Enter a number' and closed itself the second I entered a number.
Help?
You have to:
close the while loop in the correct place
change the if (i == 1) condition (i==1 means x is divisible by some y)
start with y = 2 (every number is divisible by one)
include sqrtf(x) in the loop (y <= sqrtf(x) or 15, 25, 35... are primes).
So:
int main()
{
int x;
cout << "Enter a number." << endl;
cin >> x;
int y = 2; // <-- changed
int i = 0;
while (i == 0 && y <= sqrtf(x)) // <-- changed
{
if (fmodf(x,y) == 0)
{
i = 1;
}
else
{
i = 0;
}
y++;
} // <-- moved here
if (i == 0) // <-- changed
{
cout << "Your number is prime." << endl;
}
else
{
cout << "Your number is composite." << endl;
}
return 0;
}
works (more or less...).
Anyway:
don't use using namespace std; (Why is "using namespace std" considered bad practice?)
\n should be your default ("\n" or '\n' or std::endl to std::cout?)
y and x are integers so you can use % instead of fmodf
avoid premature pessimization: prefer preincrement, only use postincrement if you're going to use the original value
else { i = 0; } is superfluous
you can change y < sqrtf(x) with y * y <= x (and you don't need math.h anymore) or find square root of number then start the loop
Somewhat better (but far from perfect):
#include <cmath>
#include <iostream>
int main()
{
int x;
std::cout << "Enter a number.\n";
std::cin >> x;
int square_root = std::sqrt(x);
int y = 2;
int i = 0;
while (i == 0 && y <= square_root)
{
if (x % y == 0)
i = 1;
++y;
}
if (i == 0)
std::cout << "Your number is prime.\n";
else
std::cout << "Your number is composite.\n";
return 0;
}
Now:
input validation, i.e. check for bad input values (How to check if input is numeric in C++)
special cases checking (is the number one a prime number?)
a bool would express your intentions better than int i;
improve the algorithm (Determining if a number is prime, Which is the fastest algorithm to find prime numbers?, Primality tests)

Where is the Error in my C++ code?

Here is the error screenshot: http://prntscr.com/9n6ybt
Here is the code:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{
if (b%i==0)
{
cout << i << " ";
}
}
return 0;
}
for(int i=a;i<=b;i++)
{
if (b%i==0)
{
cout << i << " ";
}
}
Will give a division by zero if i == 0.
You'll have to check the input, or the value of i, for example:
for(int i=a; i<=b; i++)
{
if (i > 0 && b%i==0)
{
cout << i << " ";
}
}
If i == 0, b%i==0 will not be evaluated.
You are not handling the case where i might be 0 (division by 0) so b % i is indetermined. You can solve it by going this way:
if (i==0) continue;
You should handle the case division by "zero". When the value of i = 0 then the code fails and produce an exception.
You should do like this:
#include <iostream>
using namespace std;
int main()
{ int a, b;
cin>>a>>b;
for(int i=a;i<=b;i++)
{ if (i == 0)
continue;
else if (b%i == 0)
cout << i << " ";
}
return 0;
}