Problem Solving
caution
https://www.geeksforgeeks.org/why-global-array-has-a-larger-size-than-the-local-array/
declaring inside main() | declaring OUTSIDE main() [Global Variables] | .... | .... | |
bool | 107 | 108 | ||
double | ||||
long long | ||||
long double | ||||
When to use Global Variables
Use global Variables wherever you can
by CONSTANT I mean variabled declared above
main()
- if lets say I have to find prime numbers till n, then I can declare the
is_prime
from [Sieve of Eratosthenes] as a CONSTANT decalred before main(). By this will have a bool array with all prime numbers lesss than given contraint such as 106. So this will be inside a method of Time ComplexityO(n.log(log n))
.- IF I did it without a declaring
is_prime
vector of type bool asCONSTANT
then I would have to make this bool vector for each given test case, here the no. of test cases are 105. Then the method for creating theis_prime
bool vector with primes true will be insite the test case loopwhile(t--)
. So the Time Complexity will becomeO(T*n.log(log n))
- IF I did it without a declaring
Eat up a unnecessary
string or char
Below program takes input 12/78
as fraction and then char ignore
takes in the /
fraction divider and thus other variables can take up required integer values
#include <iostream>
int main()
{
// Our first fraction
int num1 {};
int den1 {};
// Our second fraction
int num2 {};
int den2 {};
// Used to eat the slash between the numerator and denominator
char ignore {};
cout << "Enter a fraction: ";
cin >> num1 >> ignore >> den1;
cout << "Enter a fraction: ";
cin >> num2 >> ignore >> den2;
cout << "The two fractions multiplied: "
<< num1 * num2 << '/' << den1 * den2 << '\n';
return 0;
}
DRY (don’t repeat yourself) principle
- if some operations are done repetitively then we must create a
funtion()
to do it.