How does the "if block" work in this code? - c++

Please consider the following code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int a, b;
cout << "Enter two integer: ";
cin >> a >> b;
if (a > b) {
int temp = a;
a = b;
b = temp;
}
cout << a << "<=" << b << endl;
}
The above code yields the minimum of the two inserted numbers. Can anyone explain how the if block works?

It's the idiomatic way of swapping two numbers.
There are more efficient ways: to exploit those use std::swap instead.
(The statement int temp=a; sets the variable temp to the value of a. The statement a=b; sets a to the value of b. Finally, b=temp; sets b to temp which was the original value of a. The overall effect therefore is to exchange the values of a and b.)

Related

Simple C++ calculator always outputs 16

I'm new to programming so please write your answer as basic as possible. I made a simple calulator in C++. It's supposed to add 2 numbers but for some reason the output is always 16, no matter the numbers. Can someone explain this to me? This is the code:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum = a + b;
cout << "Enter a number: ";
cin >> a;
cout << "Enter a second number: ";
cin >> b;
cout << sum;
return 0;
}
But, when i do this (creating the int sum first and then assigning it later), it works:
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum;
cout << "Enter a number: ";
cin >> a;
cout << "Enter a second number: ";
cin >> b;
sum = a + b;
cout << sum;
return 0;
}
int sum = a + b;
Is not an algebraic rule, it is a statement evaluated at that point in the sequence of statements.
Just do it after your inputs.
In the first example, you're initializing the sum variable before the initialization of a and b so before initialization, the a and b will contain some garbage value and that's why you're getting output 16 the garbage value can be anything. Just initialize your sum variable after a and b variables have some user inputted values.
And if you're doing some addition then it's a good practice to initialize your result variable(sum) with zero sum=0 so it also doesn't contain any garbage values
When you use
int sum = a + b;
sum initilized to whatever a + b evaluates to. The value of sum does not change when you set the values of a and b after that statement. In your case, neither a nor b has been initialized before that statement. Hence, it causes undefined behavior.
The second version of your program works correctly since you are assigning a + b to sum after a and b have been assigned values from user input.

How to use Complex numbers in Class/Object C++

Im strugling to implement complex numbers into my code. When I compile it gives me random numbers. It should use imaginary number i = sqrt(-1). It should output realPart + imaginaryPart * i.
#include <iostream>
#include <complex>
using namespace std;
class Complex
{
private:
double i;
complex<double> imaginarypart = i*sqrt(1);
double realpart;
public:
void seti(double a1) {
i = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart + imaginarypart;
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.seti(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}
The point is that an the type double cannot store imaginary values.
Yet you try to do so, e.g. with sqrt(1); (though you probably meant -1).
The complex<double> is indeed able to store imaginary values, but on the one hand it won't work by assigning the product of the non-initialised i with 1 and on the other hand you seem to try to implement complex numbers yourself. Using the provided complex standard type somewhat defeats that. If you use it, then you just need to learn outputting it in the format you want, instead of doing all the implementation work.
Lets assume that you are more interested in getting it done yourself first.
What you need to do is to always represent complex numbers as two numbers.
I hence propose to change your code likes this.
#include <iostream>
using namespace std;
class Complex
{
private:
/* double i; Won't work, it cannot store imaginary values. */
double imaginarypart;
double realpart;
public:
void setimaginarypart(double a1) {
imaginarypart = a1;
}
void setrealpart(double a2) {
realpart = a2;
}
void printwhole() {
cout << realpart << '+' << imaginarypart << 'i'; // To get the output you want.
}
};
int main()
{
double a, b;
cout << "Enter your realpart" << endl;
cin >> a;
cout << "Enter your imaginarypart " << endl;
cin >> b;
Complex num1;
num1.setimaginarypart(b);
num1.setrealpart(a);
cout << endl;
num1.printwhole();
}
Alternatively use existing solutions (e.g. std::complex), instead of trying to program one yourself. Outputting them in the shape you want (r+i*I) does not require to implement the whole thing yourself.
Have a look at https://en.cppreference.com/w/cpp/numeric/complex to learn about what it offers.
As you figured out, complex numbers have a real and an imaginary part. And in std::complex<double>, those two parts are combined.
But in your class Complex, you have Complex::i, Complex::realpart, Complex::imaginarypart::real() and Complex::imaginarypart::imag(). That's 4 parts!
Furthermore, complex<double> imaginarypart = i*sqrt(1); means that Complex::imaginarypart is set to i*sqrt(1) when a Complex object is created. But at that time, i is still uninitialized! So that won't work either. This is why you get random numbers (or a crash, depending on your luck).
The simple solution is to drop your whole class Complex. std::complex<double> already has functions to set the real and imaginary parts, namely std::complex<double>::real(double) and std::complex<double>::imag(double)
(Note: real and imag are setters if you pass a value, getters if you don't).

C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}

std::cin while loop gives a strange result

As of late, I've been doing a complete review of C++ and came across a code snippet containing the following:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a)
{
b+=a;
}
cout << b << endl;
return 0;
}
The code snippet seems very straightforward: it puts input from the console into a and adds this onto b, for as long as valid input is presented. However, whenever I try to run this program with an input of integers, seperated with spaces, it gives a very large negative integer (-1218019327 being the most recent result, when the entire input only consisted of the number '1'). Only when I modify the code does it give correct output:
#include <iostream>
using namespace std;
int main()
{
int a, b;
while (cin >> a)
{
cout << a << endl;
b+=a;
}
cout << b << endl;
return 0;
}
Why does adding a cout statement change the result of my code so thouroughly (yet positively)?
Both programs result in undefined behavior, you did not initialize b. Try:
int b = 0;
You have to initialize b=0;. Or b will give you garbage value.
#include <iostream>
using namespace std;
int main()
{
int a, b=0;
while (cin >> a)
{
cout << a << endl;
b+=a;
}
cout << b << endl;
return 0;
}
By pressing ctrl-z you will get the value of b.

double conditions don't work in c++

First: I'm begginer. :) I've got a problem with my c++ code.
#include <iostream>
using namespace std;
int main()
{
int a,b;
do {
cout << "a= ";
cin >> a;
if (a<=0) {
cout << "This number is not positive!\n";
}
}
while (a<=0);
do {
cout << "b= ";
cin >> b;
if (b<=0) {
cout << "This number is not positive!\n";
}
}
while ((a==b) and (b<=0));
}
Have you got any ideas?
Thanks!
It is not possible for that condition to be true. We already know that a is positive, so it can't both equal b and b be negative.
Sounds to me like you want or instead. This would mean that b also has to be positive and must not be the same as a. Note that it is typical to use && instead of and and || instead of or:
while ((a==b) || (b<=0));
Think about it like this: we can't to continue asking for b if they input is negative or if the input is the same as a.