This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?
#include <iostream>
using namespace std;
int main()
{
int n, sum, a;
a = 0;
sum = 0;
cin >> n;
while (n>0)
{
a = n % 10;
sum = sum * 10 + a;
n = n / 10;
}
cout << sum;
return 0;
}
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:
#include <iostream>
int main( )
{
std::cout << "Enter a number: ";
int num { };
std::cin >> num;
int sum { };
while ( num > 0 )
{
const int remainder { num % 10 };
sum = sum * 10 + remainder;
num = num / 10;
}
std::cout << "The reversed number: " << sum << '\n';
}
A few general things to keep in mind:
Do not use using namespace std;. That's a bad practice. See Why is "using namespace std;" considered bad practice?.
Do not declare multiple variables in a single statement. That can lead to various issues.
Make sure to initialize your variables before using them if their initial values will be read and used in some operation. If the initial value is not used by anyone, then do not initialize the variable since it would be a waste of computing power.
Try to shrink the scope of variables as much as appropriate to reduce the risk of them being used accidentally by another statement that is not supposed to access those variables. In the above example, I declared remainder inside the scope of the while loop because it was not being used outside the loop.
And last but not least, avoid ambiguous identifiers like int a, int n, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.
int n,sum,a=0;
the above expression only initializes the last variable 'a', leaving 'n' and 'sum' uninitialized.
although n is assigned a value in
cin >> n;
the variable 'sum' is likely to have a garbage value. That explains the different results.
Related
A drawer contains socks of n different colors. The number of socks available of i'th color is given by a[i] where a is an array of n elements. Tony wants to take k pairs of socks out of the drawer. However, he cannot see the color of the sock that he is picking. You have to tell what is the minimum number of socks Tony has to pick in one attempt from the drawer such that he can be absolutely sure, without seeing their colors, that he will have at least k matching pairs.
My solution:
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int find_min(int a[], int n, int k) {
int total , total_pairs , total_socks ;
for (int i = 0 ; i < n ;i++)
{
total_socks += a[i];
total_pairs += (a[i]/2) ;
}
total = total_socks - total_pairs + k ;
a = (int)total_socks ;
n = total_socks;
k = total;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n, k;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
cin >> k;
Solution obj;
cout << obj.find_min(a, n, k) << endl;
}
return 1;
}
But I get this error:
Error : error: invalid conversion from int to int* [-fpermissive]
a = (int)total_socks ;
The problem is because your trying to assign an int to a variable of type int* here: a = (int)total_socks ; I think what your looking for is a = (int*)total_socks ;. But still it is pointless as your not using the variable again (unless your actually planning on returning it). So is the rest of them, n and k.
Theres another problem with your code, the function int find_min(int a[], int n, int k) is of return type int. But in the function body, your not returning anything. This will result in undefined behavior. So make sure that you return something in that function.
Additional: Make sure you initialize all your variables. Over here: int total , total_pairs , total_socks ; you don't initialize it to any value so later on, it might not give you the result you require because it already contains junk.
And try not to use using namespace std; as its not a good practice. So is #include <bits/stdc++.h>. Include the files you want and use the :: operator to access their namespace instead.
Unrelated: Do you need a class just for that function? It seems like you don't (by looking at the code you have provided). Just keep the function in the global namespace but if you want it to be inside a namespace, put it inside one (ie: namespace Solution { ... }).
I am suppossed to sum the squares of the all the natural numbers until it reaches some input, but the result becomes larger than it should. As I set 3 as input, the outcome becomes 3*10⁹ or so, could you please tell if I am missing a mistake with data types or operations?
BTW, when does using functions become more efficient than writing whatever in the main code? I have quite a few doubts on when I should or should not use them.
Thanks to whomever might read it.
#include <iostream>
using namespace std;
int main(){
int input, sum;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
You should initialize the variable sum with 0 and then the program will be run successfully. When you use sum without initializing it, the behaviour of your program is undefined.
Also you can use below formula instead of the for loop:
sum = n * (n + 1) * (2 * n + 1) / 6
You never initialize sum, so there is no guarantee that the value starts at 0. In fact, it's initial value is essentially undefined. You should simply add the line sum = 0; before your for loop.
#include <iostream>
using namespace std;
int main(){
int input, sum;
sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
"BTW, when does using functions become more efficient than writing whatever in the main code"
It isn't necessarily more efficient, but for larger projects it is easier to read code when common functionality has been grouped into reusable functions. As a general rule of thumb, if you are writing the same code/algorithm more than once, you should write a function for that code/algorithm.
NOTE - As pointed out by others there happens to be a formula for calculating the sum of squares without a loop.
sum = n * (n + 1) * (2 * n + 1) / 6
This is what is known as an order of 1, or O(1), solution because a single atomic operation can be performed to achieve the results you are looking for. On the other hand, the loop solution is considered order of n, or O(n), since n iterations of the loop must be performed to achieve the results of the routine. The O(1) solution is considered optimal. If you use large values as your input then you will see why. However, if you are new to programming then your teachers will not expect you to know much about algorithm analysis and the original solution above should be fine.
There are two approaches to resolve your problem.
The first one is to place the declaration of the variable sum before main. For example
#include <iostream>
using namespace std;
int sum;
int main(){
int input;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
In this case the variable will have the static storage duration and will be initislized by the compiler with 0.
Otherwise the variable have the automatic storage duration and must be initialized explicitly like
#include <iostream>
using namespace std;
int main(){
int input, sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
Pay attention to that it is better to declare the variable as having the type long long int because the sum of squares can be too big and will not fit into an object of the type int. For example
#include <iostream>
using namespace std;
int main(){
int input;
long long int sum =0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += ( long long int )i*i;
}
cout << sum << endl;
}
You do not initialize sum. So whenever you do sum += i * i, you are adding numbers to a trash value.
This is the reason you get incorrect results.
To fix this, simply replace int input, sum; with int input, sum(0);.
i need to store number and sum it , but the compiler say the a.num[i] is inaccessible... Here my code
class number{
private:
int num[12];
public:
number(){
}
int totalnumber(){
int total =0;
for( int i=0 ; i<12 ; i++){
total= total + num[i];
}
return total;
}
};
int main(){
number a;
int a;
cout<<"Enter number :";
cin>>a.num[i];
while(a.num[i] < 0){
cout<<"You've entered invalid input."<<endl;
cout<<"Enter number :"<<endl;
cin>>a.num[i];
}
cout<<"Total amount saved is : RM"<<number.totalnumber()<<endl;
return 0;
}
I think the number constructor need to do something, but i cant figure it out:( . Is there any way i can store the array inside a private array as declare in class number?
There are a couple of problems with your code:
First you defined 2 variables with the same name in the "main" function:
number a;
int a;
Then you try to access the variable "i" in "cin>>a.num[i];" but "i" has not be declared yet assigned in the "main" function.
I guess and think what you may try to achieve with your code is to sum a couple of numbers that are entered by the user.
In this case you may want to to use "for" loop to iterate over "i" and store the numbers read into the array in your object of the "number" class.
To store the numbers, you may want to implement a method for your class, like this, because you can't access a member variable like "int num[12]" from the ouside when it is declared as a private member:
void storeNum(int num, int i){
num[i] = num;
}
Third, you create an object of the class "number" with the name "a", but in the last line of your code, you tried to access the method "totalnumber" but you did not specify the object to invoke the method on, instead to wrote the class name.
And then you forget to
#include <iostream>
which is required by the C++ standard if you want to access library functions, which are defined the in the "iostream" header file. Additionally, you may want to write
using namespace std;
at the top of your file to tell the compiler that you want to import all the identifiers from the std namespace into your current namespace; That is, you wan't to write "cout" instead to "std::cout".
( Edit: To make this clear: You should never never never write "using namespace std" in production code... Never. Unless you're learning the language and trying things out.. Then it's okay. Just to keep this in mind for later... )
For example, the finished code could look like this:
#include <iostream>
using namespace std;
class number{
private:
int num[12];
public:
number(){};
int totalnumber(){
int total =0;
for( int i=0 ; i<12 ; i++){
total= total + num[i];
}
return total;
}
void storeNum(int number, int i) {
num[i] = number;
}
};
int main(){
number a;
for(int i = 0; i < 12; i++) {
cout << "Enter Number:";
int num = 0;
cin >> num;
a.storeNum(num,i);
}
cout<<"Total amount saved is : RM"<< a.totalnumber()<<endl;
return 0;
}
Hopefully, I could resolve your problem I helped you to understand the C++ language a little bit better.
Edit:
I noticed you tried to handle invalid user input in your code. That was a good idea (I assume you know at least another language ;) ). But it's more important to get you syntax correct. You can worry about error handling later...
I am writing a simple code to calculate Fabonacci numbers as an exercise. The code works, but i don't get why. I have some special cases for n=1 and n=2 which is the place of the number in the sequence (the numbers are 0 and 1). However after those, the number is calculated in this loop.
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
Going in to the loop, Fib_1=0, Fib_2=0, and Fib_n=1. Why does not this loop just spit out 0 no matter what? The whole code is below.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >>n;
cout <<endl;
int Fib_n;
int Fib_1;
int Fib_2;
int LoopCount=1;
if(n>1)
{
Fib_n=1;
LoopCount++;
while(n>LoopCount)
{
Fib_n=Fib_1+Fib_2;
Fib_2=Fib_1;
Fib_1=Fib_n;
LoopCount++;
}
}
cout <<Fib_n;
return 0;
}
int Fib_1;
int Fib_2;
were never initialized. Therefore, the first time you calculate Fib_n=Fib_1+Fib_2;, Fib_n will get the sum of two uninitialized variables.
I have modified your code so it would work.
#include <iostream>
using namespace std;
int main()
{
cout <<"Which number of the Fibonacci sequence do you want to calculate?" <<endl;
int n;
cin >> n;
cout << endl;
int Fib_1 = 1;
int Fib_2 = 1;
int count = 0;
while(n > count)
{
Fib_1 = Fib_1 + Fib_2;
Fib_2 = Fib_1 - Fib_2;
count++;
}
cout << Fib_1;
return 0;
}
Fib_1
You have that as an uninitalized variable, so you may get a garbage value for output.
Fib_2 = Fib_1
Next, you initialize Fib_2 with Fib_1, meaning they both share the same (random) value.
In debug mode, these are both initialized to 0, and adding them:
Fib_n=Fib_1+Fib_2;
makes the sum equal 0. In release mode, you can expect random values from the compiler. Here is more info on Uninitialized Variables.
I am trying out the first part of my code, I am trying to eliminate all numbers up to the inputted number that are divisible by 2 without using (vector, division, or modulus)
#include <iostream>
using namespace std;
int main()
{
int num;
int array [num];
cout << "Please enter a number" << endl;
cin >> num;
cout << endl;
if(num == 0)
{
return 0;
}
int var = 2;
int check;
for(int x = 0; x < num;x++)
{
array[x] = var;
check = var;
while(check > 0) // This loop checks if a number is divisible by 2
{
check = var - 2;
}
if(check == 0)
{
array[x] = 0;
}
else
{
cout << array[x];
}
var++;
}
}
int array [num];
This should ideally generate a compiler warning which should look something like:
ISO C++ forbids variable-size array
Note that the above line from your code doesn't necessarily lands you into undefined behavior territory. You are in the implementation defined territory .
Now as to why your code is failing it's because num in uninitialized. This is undefined behavior. So no surprises that your code is showing random behavior.
Moving the definition of the array below the point where you are inputting num will work.
Although if you truly want a variable sized array want your code to be portable across compilers, allocate it on heap.
cin >> num;
int *array = new int[num]; // don't forget to delete this, or even better use unique_ptr
Better would have been std::vector but then the question puts an artificial restriction on its usage.
Also please rename the array variable to something else. c++11 has a standard container with the same name.