Skip to main content

Practice Problem #1 Solutions.

Tutorial on Practice Problem #1.


Problem 1 - It is simply a mixture of if statements.
Solution -

#include<iostream>
using namespace std;
#define and &&		// Defining it to make it easier to think of statements,
			// It will have no effect on runtime of a program,
			// As every "and" will be replaced by && at compile time itself
int main()
{
	int temperature;
	cout << "What is temperature today ? "; cin >> temperature;

	if(temperature > 20 and temperature < 25)
		cout << "The weather is Good" << endl;

	else if(temperature > 15 and temperature < 20)
		cout << "The weather is little cold" << endl;

	else if(temperature < 15)
		cout << "The weather is cold" << endl;

	else if(temperature > 25 and temperature < 30)
		cout << "The weather is little warm" << endl;
	
	else if(temperature > 30 and temperature < 40)
		cout << "The weather is warm" << endl;
	
	else if(temperature > 40)	// Figure out, why I am not writing at it as only "else"
		cout << "The weather is really hot" << endl;

	return 0;
}


Problem 2 - It is simple function implementation.

Solution - 

#include<iostream>
using namespace std;

void initialize(int *arr, int n)
{
	for(int i = 0; i< n; i++)
	{
		arr[i] = (i+1)*2;	// Not taking 0 as multiple, but it's just a choice.
	}
}
int main()
{
	int *arr;
	arr = new int[10];	// size is your choice.

	initialize(arr, 10);

	for(int i = 0; i< 10; ++i)
		cout << arr[i] << " ";
	cout << endl;
}


Problem 3 - This program is little lengthy and you have to use dynamic allocation, because you have to create 2-d array according to the input given by the user and to allocate memory at runtime we use pointer and heap memory.

Explanation of the algorithm - I created two function, one is for multiplying two matrices and storing it in the third matrix and one is for initializing these matrices before doing multiplication.

Also See carefully that while passing two dimensional array two my function I used pointer to pointer.

which means I created whole array in the heap and stored the address of first element in the stack memory. Here, de-allocation is not very important as after the multiplication the program is already at its end position of terminating, so the whole memory will be automatically freed. I declared the dimension (dim) at the top scope (Global scope), because it is needed in every function I used, so better declaring at the top and using it rather than passing it to every function as an argument.

Solution -

#include<iostream>
using namespace std;

// Considering the assumption I provided the function should be
int dim;
void mulitply(int **m1, int **m2, int **res)
{

	for(int i = 0; i< dim; i++)
	{
		for(int j = 0;j < dim; j++)
		{
			int temp = 0;
			for(int k = 0;k < dim; k++)
			{
				temp += (m1[i][k] * m2[k][j]);
			}
			res[i][j] = temp;
		}
	}
}
void initialize(int **matrix)
{
	for(int i = 0; i < dim; ++i)
	{
		for(int j = 0; j < dim; j++)
		{
			cout << "Enter " << i+1 << "," << j+1 << " element ";
			cin >> matrix[i][j];
		}
	}
}
int main()
{
	cout << "Enter the dimension of your square matrix : "; cin >> dim;

	int **matrix1 = new int*[dim];
	for(int i = 0; i< dim; i++)
		matrix1[i] = new int[dim];

	int **matrix2 = new int*[dim];
	for(int i = 0; i< dim; i++)
		matrix2[i] = new int[dim];

	int **matrix3 = new int*[dim];
	for(int i = 0; i< dim; i++)
		matrix3[i] = new int[dim];


	cout << "Initialize first matrix"<< endl;
	initialize(matrix1);
	cout << "Initialize second matrix"<< endl;
	initialize(matrix2);

	mulitply(matrix1, matrix2, matrix3);

	for(int i = 0 ;i< dim; i++)
	{
		for(int j = 0; j < dim; j++)
			cout << matrix3[i][j] << " ";
		cout << endl;
	}

}

You have to be very careful while using pointers, as while using these, the chances of mistakes are very high.


Problem 4 - It is very simple program you can even define macros for doing tasks like this.

Solution -

#include<iostream>
using namespace std;

int Area(int n)
{
	return n*n;
}

int Volume(int n)
{
	return (n*n*n);
}
int main()
{
	int a;	// We only need one dimension for square or cube.
	cout << "Enter the dimension of your cube/square : "; cin >> a;

	cout << "Area of square with side " << a << " is : " << Area(a);
	cout << "Volume of cube with side " << a << " is : " << Volume(a);
}


Problem 5 - In this problem also you have to use dynamic allocation, I will showing some ways, where we can try to reduce the use of dynamic allocation, but better thing is to practice as much as you can.

Solution - 

#include<iostream>
using namespace std;
int *func(int *arr, int n)
{
	int *temp = new int[n];		// n value is evaluated at runtim so dynamic allocation
	for(int i = 0; i< n;i++)
	{
		temp[i] = 2*arr[i];
	}
	return temp;
}
int main()
{
	int arr[] = {1,2,3,5,6,6,7,8,9};
	int n = sizeof(arr)/sizeof(arr[0]); // To find number of elements in an array(here arr)
	int *another = func(arr, n);

	for(int i = 0; i< n; i++) 	cout << another[i] << " ";
	cout << endl;

	return 0;
}


Bonus Problem

I have provided the solution already, Now, let's discuss what was wrong in our problem. Why the last number is printed as negative? 

The reason - We already have discussed about long long integers in data types sections and we very well know that long long integer has ranges from (-2^63-1 to 2^63), but when we found 91st and 92nd fibonacci numbers and add them we get some value which is even greater than 2^63(positive range), so, what happens is when the range reached 2^63 it again starts counting from (-2^63-1), which is the reason of getting negative values, and the thing we discussed just now is called overflow, means Overflowing the datatypes with some number greater than its range, underflow is just reverse, means giving so smaller value than number have in its negative range. We could have avoided it for 93rd value of fibonacci number by using unsigned long long int array but after that overflow would again occur.

Comments

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                        Abacus How computer works? The computer's internal functionality is a whole separate bra

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class . So, let's start by giving you the introduction. C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased. String Class is a Built-in class that provide us much more functionality than C-Style String. C-STYLE STRINGS Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String. C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters. Let's first start by showing a

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin