Are my parameters sorted? - c++

I try to check are my parameters are sorted. I have code but it doesn't work... Could you tell me what should I fix? I think the problem is in first loop because result can be 0 in the end of list of parameters. I don't know how should I change it, I try to make that: when atof(argv[i]) <= atof(argv[i + 1]) is not true, program should go to next for loop... It is my first C++ program.
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
int result;
for (int i = 1; i < argc - 1; i++) {
if (atof(argv[i]) <= atof(argv[i + 1])) {
result = 0;
}
}
if (result == 0) {
cout << "Sorted!" << endl;
system("pause");
}
for (int i = 1; i < argc - 1; i++) {
if (atof(argv[i]) >= atof(argv[i + 1])) {
result = 2;
}
}
if (result == 2) {
cout << "Sorted!" << endl;
system("pause");
}
else {
cout << "Bad." << endl;
system("pause");
}
system("pause");
return 0;
}

You will have to initialize result by changing int result; to int result = -1;.
Replace -1 with your desired initial value if you want.

Think about the first loop a little more. The logic you have says "if any number is less than the next number, set result to 0." So if you have a list like 5 3 4 2 1, then when 3 and 4 are compared, result will be set to 0. And because the remaining numbers are decreasing, the value of result will not change for the remainder of the loop.
One solution you may want to consider is to assume the list is sorted, then if a number is encountered that is not in sorted order, set result to -1 and break out of the loop.

Related

For reversing a number in C++ which ends with zeros

I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method:
#include<iostream>
using namespace std;
int main()
{
int l;
cin>>l;
bool leading = true;
while (l>0)
{
if ((l%10==0)&& (leading==true))
{
l /= 10;
leading = false; // prints 032 as output
continue;
}
// leading = false; this prints correct 32
cout<<l%10;
l /= 10;
}
return 0;
}
The instruction of assigning boolean leading false inside the if statement is not giving a valid answer, but I suppose assigning it false should give 32 as output whether we give it outside or inside if statement as its purpose is just to make it false once you get the last digit to be a non zero.
Please tell the reason of difference in outputs.
The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it.
When you make leading = false outside the if statement, you are basically waiting till you encounter all zeroes before making it false.
If you are looking to reverse a number, this is the well known logic to do so:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
rev = rev*10 + r;
n /= 10;
}
return rev;
}
EDIT:
The above code snippet is fine if you just want to understand the logic to reverse a number. But if you want to implement the logic anywhere you have to make sure you handle integer overflow problems (the reversed number could be too big to be stored in an integer!!).
The following code will take care of integer overflow:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
if(INT_MAX/10 < rev)
{
cout << "Reversed number too big for an int.";
break;
}
else if(INT_MAX-r < rev*10)
{
cout << "Reversed number too big for an int.";
break;
}
rev = rev*10 + r;
n /= 10;
}
if(n != 0)
{
//could not reverse number
//take appropriate action
}
return rev;
}
First, rewrite without continue to make the flow clearer,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
l /= 10;
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
l /= 10;
}
}
and move the division common to both branches out of the conditional,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
}
l /= 10;
}
and now you see that the only difference between the two is the condition under which the assignment leading = false happens.
The correct version says, "If this digit is non-zero or a non-leading zero, remember that the next digit is not a leading zero, and print this digit. Then divide."
Your broken version says, "If this is a leading zero, the next digit is not a leading zero." which is pretty obviously not the case.
Just try this ,
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Working for me...
When reversing digits of numbers or generally when working with digits and the actual
value does not matter then treating the number as an array of digits is simpler than working with the whole int. How to treat a number as an array of digits conveniently? std::string:
#include <iostream>
#include <string>
#include <sstream>
int reverse_number(int x) {
std::string xs = std::to_string(x);
std::string revx{ xs.rbegin(),xs.rend()};
std::stringstream ss{revx};
int result;
ss >> result;
return result;
}
int main() {
std::cout << reverse_number(123) << "\n";
std::cout << reverse_number(1230) << "\n";
}
std::to_string converts the int to a std::string. std::string revx{ xs.rbegin(),xs.rend()}; constructs the reversed string by using reverse iterators, and eventually a stringstream can be used to parse the number. Output of the above is:
321
321

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

C++: find first prime number larger than a given integer

Question: How to find, for a given integer n, the first prime number that is larger than n?
My own work so far
I've managed to write a program that checks whether or not a given integer is a prime or not:
#include <iostream>
#include <cmath>
using namespace std;
bool is_prime (int n)
{
int i;
double square_root_n = sqrt(n) ;
for (i = 2; i <= square_root_n ; i++)
{
if (n % i == 0){
return false;
break;
}
}
return true;
}
int main(int argc, char** argv)
{
int i;
while (true)
{
cout << "Input the number and press ENTER: \n";
cout << "To exit input 0 and press ENTER: \n";
cin >> i;
if (i == 0)
{
break;
}
if (is_prime(i))
cout << i << " is prime" << endl;
else
cout << i << " isn't prime'" << endl;
}
return 0;
}
I'm struggling, however, on how to proceed on from this point.
You have a function is_prime(n), and a number n, and you want to return the smallest number q such that is_prime(q)==true and n <= q:
int q = n;
while (!is_prime(q)) {
q++;
}
// here you can be sure that
// 1. q is prime
// 2. q >= n -- unless there was an overflow
If you want to be a bit more efficient, you can check explicitly for the even case, and the increment by 2 each time.
It's a concrete example of a general theme: if you have a test function and a method for generating elements, you can generate the elements that pass the test:
x = initial_value
while (something) {
if (test(x)) {
// found!
// If you only want the first such x, you can break
break;
}
x = generate(x)
}
(note that this is not a valid C++ code, it's pseudocode)
int i;
**int k_koren_od_n = (int)(sqrt(n) + 0.5)**
for (i = 2; i <= k_koren_od_n ; i++){
To get around casting issues, you might want to add this fix.

Whats wrong in my code! I want to print Fibonacci Series with values less than 4000000

I think I there is some problem in implementation of my loop!
Here's my code.
#include <iostream>
using namespace std;
int main()
{
int i=2;
long long int FiboNo[100];
FiboNo[0] = 1;
FiboNo[1] = 2;
do{
FiboNo[i]=FiboNo[(i-1)]+FiboNo[(i-2)];
cout<<FiboNo[i]<<endl;
i++;
}while(FiboNo[i]<4000000);
return 0;
}
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
i++;
} while (FiboNo[i] < 4000000);
You are incrementing i before you compare.
do {
FiboNo[i] = FiboNo[(i - 1)] + FiboNo[(i - 2)];
cout << FiboNo[i] << endl;
} while (FiboNo[i++] < 4000000);
is what you want to do.
Here's what's happening:
i 2
fibo[2] is 2
now i is 3
fibo[3] is 0
This has no problem, when fibo[someIndex] reaches the limit. It wont come out, because your value is always a 0.

C++ removing leading zeros in a binary array

I am making a program that adds two binary numbers (up to 31 digits) together and outputs the sum in binary.
I have every thing working great but I need to remove the leading zeros off the solution.
This is what my output is:
char c[32];
int carry = 0;
if(carry == '1')
{
cout << carry;
}
for(i = 0; i < 32; i++)
{
cout << c[i];
}
I tried this but it didn't work:
char c[32];
int carry = 0;
bool flag = false;
if(carry == '1')
{
cout << carry;
}
for(i=0; i<32; i++)
{
if(c[i] != 0)
{
flag = true;
if(flag)
{
for(i = 0; i < 32; i++)
{
cout << c[i];
}
}
}
}
Any ideas or suggestions would be appreciated.
EDIT: Thank you everyone for your input, I got it to work!
You should not have that inner loop (inside if(flag)). It interferes with the i processing of the outer loop.
All you want to do at that point is to output the character if the flag is set.
And on top of that, the printing of the bits should be outside the detection of the first bit.
The following pseudo-code shows how I'd approach this:
set printing to false
if carry is 1:
output '1:'
for each bit position i:
if c[i] is 1:
set printing to true
if printing:
output c[i]
if not printing:
output 0
The first block of code may need to be changed to accurately output the number with carry. For example, if you ended up with the value 2 and a carry, you would want either of:
1:10 (or some other separator)
100000000000000000000000000000010 (33 digits)
Simply outputting 110 with no indication that the leftmost bit was a carry could either be:
2 with carry; or
6 without carry
The last block ensures you have some output for the value 0 which would otherwise print nothing since there were no 1 bits.
I'll leave it up to you whether you should output a separator between carry and value (and leave that line commented out) or use carry to force printing to true initially. The two options would be respectively:
if carry is 1:
output '1 '
and:
if carry is 1:
output 1
set printing to true
And, since you've done the conversion to C++ in a comment, that should be okay. You state that it doesn't work, but I typed in your code and it worked fine, outputting 10:
#include <iostream>
int main(void)
{
int i;
int carry = 0;
int c[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
bool print = false;
// This is the code you gave in the comment, slightly modified.
// vvvvvv
if(carry == 1) {
std::cout << carry << ":";
}
for (i = 0; i < 32; i++) {
if (c[i] == 1) {
print = true;
}
if (print) {
std::cout << c[i];
}
}
// ^^^^^^
std::cout << std::endl;
return 0;
}
const char * begin = std::find(c, c+32, '1');
size_t len = c - begin + 32;
std::cout.write(begin, len);
Use two fors over the same index. The first for iterates while == 0, the second one prints starting from where the first one left off.