Thursday, 3 September 2020

Published September 03, 2020 by Kashif with 0 comment

Top 8 interview questions about variables| conceptual questions

c++ interview questions


This article covers all the tricky and conceptual questions related to the c++ variables that are likely to be asked in interviews. We also have a detailed article with programs about c++ variable. The main purpose is to elevate your concepts and strengthen your basics. If you are learning to program then you should know the answers to these questions.

What is the difference between the declaration and initialization of a variable?

When we talk about the variable declaration, we basically reserve space in memory depending upon the variable type. Every type has a different size and needs different space in memory. For example, int requires 4 bytes.
Initialization means storing some initial value in the variable that can be used in the program. Values stored in the variables are actually stored in the reserved space in memory for that variable.


#include <iostream>
using namespace std;
int main()
{
 char a, b, c;
 int num1, num2;  // declaration
 float f1, f2;

 //--------------------------------
 a = b ='n';
 c = 't';

 num1 = num2 = 100; //initialization

 f1 = f2 = 25.5;

 system("pause");
 return 0;
}


What is the difference between local and global variables?

The variables declared inside a block are called local variables for the block. Local variables can be accessed only within the braces in which it is declared. These variables do not exist outside the curly braces.
The variables declared outside all the blocks of code or outside all the functions are global variables. These variables can be accessed in all the blocks or functions. In other words, they can be assessed throughout the file.


#include <iostream>
using namespace std;

int marks1=10;//global variable
int main()
{
 int marks2 = 15;//local
 if (true) {
  int marks3 = 20;//local
 }
 system("pause");
 return 0;
}
In the above code, marks1 can be accessed throughout the source file, marks2 can be accessed throughout the main, and marks3 can only be accessed inside the block of if statement.

If there are a global variable and a local variable with the same name, which one has higher precedence?

In order to understand this concept, let's consider the below code.

#include <iostream>
using namespace std;

char capital='A';//global 
int main()
{
 char capital = 'B';//local
 cout << capital;
 system("pause");
 return 0;
}


As you can see the above code has a local and a global variable with the same name capital. In this situation, the compiler prefers the local variable on the global variable. That's why the output of the program is B rather than A.

How to access a local or a global variable if they have the same name in a program?

If we have a local and a global variable in a program with the same name then we can access the global variable with a scope resolution operator. By default, precedence is given to the local variable with the name. By using the scope resolution operator, the compiler lets you access the global variable.

#include <iostream>
using namespace std;

int marks=10;
int main()
{
 int marks = 15;
 if (true) {
  int marks = 20;

  cout << marks;//accessing local#1
 }
 cout << marks;//accessing local#2 
 cout << ::marks;//accessing global

 system("pause");
 return 0;
}
Let's take an example of the above code. we have three variables with the same name marks. One is local with respect to if statement block, the second one is local with respect to the main function block and the third one is the global variable. We wrote a cout statement within if block to access local variable#1. Then we wrote another cout statement outside if block to access local variable#2.
Then we used the scope resolution operator to access the global variable.

How to declare and define a constant in c++?

It is important to first understand what are constants in c++. The value of a constant remains unchanged throughout the program that's why its called constant. For example the value of pi.

In c++ constant is declared and initialized using the const keyword. It is the same as variables but its value cannot be changed throughout the program execution. It can only be used in operations with other variables like multiplication.


#include <iostream>
using namespace std;
int main()
{
 const float pi = 3.14;//constant
 float r, AreaofCircle;
 AreaofCircle = pi * r * r;
 cout << "Area of the circle:\t" << AreaofCircle;

 system("pause");
 return 0;
}

Is there any difference between the lifetime and scope of a variable?

The lifetime of the variable is the time when the variable is declared to its time of destruction. On the other hand scope of the variable is the point where the variable is accessible. So the lifetime and scope are two different things and it is also possible for a variable to have different lifetime and scope which is explained in the next question.

Is it possible for a variable to have different scope and lifetime?

Yes, a variable can have different scope and lifetime. Take an example of a variable declared with a static keyword. As we know that the lifetime of a variable declared with the static keyword is from the start till to the end of the program. But if this static variable is declared inside the braces of the function then it is accessible only inside the block which means that it has local scope. It means that this variable exists from the start till to the end of the program but it can only be accessed inside of the block. In other words, it has local scope and a global lifetime.

What is the difference between external and global variables?

Global variables can be globally accessed by any block of code in one source file. But it can not be accessed in other source files of the same module or project. In order to share the global variable with other source files, we use the extern keyword to access the global variable of other source files.

That's it for this article. If you have any conceptual questions about variables then write it in the comments below. I will surely answer your question. Thanks for reading and supporting us.

Read More

Sunday, 23 August 2020

Published August 23, 2020 by Kashif with 0 comment

Arrays in c++

Arrays in c++

We have studied storing data in variables so far. Every variable has a unique identifier and stores one single data value which can be overwritten. Therefore, if we want to store a large collection of data of the same type, we need a large number of variables. It is a very slow and steady approach to deal with such a scenario. So, c++ has a data structure called arrays which make it easy to do. Arrays in c++ are sequence or collection of contiguous memory locations used to store data of the same type with a single identifier. Arrays are also called the collection of variables of the same type with the same name(identifier). Arrays are transversed with an integer value called index. The main feature of the array is its contiguous/ continuous memory locations. it makes arrays easier to access. If we know the starting address then we can transverse the whole array.

Why we need Arrays?

Consider an example of storing marks of 100 students. We need 100 different variables to store this data. It's a very slow and time-consuming approach which is not recommended. Displaying this data stored in variables is also very time taking. Instead of 100 variables, we can declare an array of 100 elements in just one line. It's very easy to store and display data in an array with indexes.

How to declare and initialize an array?

When it comes to declaring and initializing an array,  there are multiple ways to do it depending on the circumstances you are dealing with. Let's start learning all the possible ways.

  1. If you want to simply declare an array and store the user's input values in it, you can simply write the data type, identifier, and the size of an array in square brackets. Then you can use for loop to take input of the user in the array.
  2. But If you want to declare an array and initialize hardcoded values, you can write empty square brackets and equals it to the values enclosed in curly braces. If you write 4 values inside curly braces, the compiler will create an array of size 4. It means that in this method, the array size is equal to the number of values enclosed in braces.
  3. Another way of declaring an array is to write the size of the array in square brackets and equals it to the values/data enclosed in curly braces. In this method, we cannot initialize values more than the array size.
  4. There is another possible way of declaring and initializing an array. The declaration is the same as in the first point by specifying the size in square brackets. After the declaration, elements of the array are initialized through the assignment operator. This method is not recommended but can be useful in some scenarios.
The below programs is written to explain all the above method of declaration and initialization.

    #include <iostream>
    using namespace std;
    int main()
    {
     //------------#1---------------
     int ArrofStdnt1[5];
     for (int i = 0; i < 5; i++)
     {
      cin>>ArrofStdnt1[i];
     }
     //------------#2----------------
     int ArrofStdnt3[] = { 3,5,7,9,8 };
     
    //------------#3---------------
     int ArrofStdnt2[5] = {3,5,7,9};
     // since the last element is not initialized so it is equaled to 0.
    
     
     //------------#4----------------
     int ArrofStdnt4[5];
     ArrofStdnt4[0] = 4;
     ArrofStdnt4[1] = 3;
     ArrofStdnt4[2] = 8;
     ArrofStdnt4[3] = 7;
     ArrofStdnt4[4] = 9;
     system("pause");
     return 0;
    }
    


    What is the Array index?

    The array index is an integer value that is used to access different elements of an array. It starts from zero to the size of the array. If you have an array of size 5 then indexes will be from 0 to 4.e.g.(0 to access the first element of the array and 4 to access the last one).

       How to access an element of an Array?

      In c++, we can access each of the elements of the array through its index. If we want to access the first element of the array"arr", we can write arr[0] to access it. We can access the fourth element like this arr[3]. We can perform different operations on the array element though this way. For example, we can reinput the value of this array element cin>>arr[0];. We can add, subtract, multiply, etc any number with the array element like arr[3]=arr[3] +5;. We can also print the data of the array element like cout<<arr[3];.To summarize, we can access elements of the array individually and perform different operations on it though its index.


      #include <iostream>
      using namespace std;
      int main()
      {
       //----array declaration and initialization------
       int ArrofStdnt[5] = {3,5,7,9};
       //----displaying last element of array----------
       cout << ArrofStdnt[4];
       //----reinput of 2nd element--------------------
       cin >> ArrofStdnt[1];
       //---------addition operation-------------------
       ArrofStdnt[3] += 5;
       system("pause");
       return 0;
      }
      

      How to access the whole array?

      In the above paragraph, we discussed how can we access individual elements of the array and perform different operations on it like displaying, etc. Now we will discuss how can we access the whole array data and perform different operations on it like displaying, sorting, searching, etc. We use for loop to start accessing data of the array from the first index 0 to the last index. The below code is a very good example of accessing the whole array and performing different operations on it.

      #include <iostream>
      using namespace std;
      int main()
      {
       //----Array declaration and initialization------
       int ArrofStdnt[5] = {3,5,7,9,4};
       //----Accessing the whole array through loop----
       for (int i = 0; i < 5; i++) {
       //----Performing different operation-----------
        ArrofStdnt[i] *= 3;
        cout << ArrofStdnt[i] << endl;
       }
       system("pause");
       return 0;
      }
      
      Here is the stepwise explanation of the above code.

      • First and foremost, we declared and initialized an array of integers called ArrofStdnt of size 5 with the third method of declaration and initialization as mentioned earlier in this article.
      • Then we run a for loop to access the whole array.
      • In the body of the loop, we perform two operations on the whole array, multiplying 3 with the whole array and displaying the whole array.
      • In the first iteration of the above code when the value of loop counter i is zero, the array element at index zero is multiplied with 3 and then printed with cout statement written in the next line. Then at the end of the first iteration, the loop counter value is incremented and is now 1. 
      • Now in the second iteration, the array element at index 2 is multiplied by 3 and then printed. Again the loop counter is incremented at the end of the second iteration.
      •  Third, fourth, and fifth iterations are executed in the same way as above two. 
      note that the number of iteration will always be equal to the array size. In the above example, the array size was five so we executed five iterations from index 0 to 4.

      How to store user input values in an array?

      To input values in the whole array, we use "cin" statements inside a loop body. The index is also written after the array identifier to store data at the specified location of the array. Let's see how we input data in an array with the below code example.

      #include <iostream>
      using namespace std;
      int main()
      {
       //----Array declaration-----------------
       int ArrofStdnt[5];
       //----initializing user input values----
       for (int i = 0; i < 5; i++) {
        cout << "enter marks of the student#" << i;
        cin >> ArrofStdnt[i];
       }
       system("pause");
       return 0;
      }
      

      How an array is stored in Memory?

      Let's say we want to create an array of integers to store marks of 5 students. We will need an array of size 5. It does not mean we reserved 5 bytes of memory. As we know the size of the integer is 4 bytes. So,  5 consecutive/continuous/contiguous blocks of size 4 bytes each are reserved in memory. It means that the total reserved space for this array in memory is 5*4=20 bytes. 

      This article was about the basic concepts of arrays. There are many complex concepts related to arrays like dynamic arrays, multidimensional-array, passing arrays to functions, etc. We will discuss all these topics in our upcoming articles.



      Read More

      Sunday, 16 August 2020

      Published August 16, 2020 by Kashif with 0 comment

      c++ program to print the Fibonacci series incrementally using nested for loop

       c++ program to print the Fibonacci series incrementally using nested for loop

      We have studied a lot about loops and their types in our previous posts. Besides, we also studied the demonstration of different types of loops with different example programs. In this short and brief article, we will demonstrate nested loops with an example c++ program to print the Fibonacci series incrementally using a nested loop. The main purpose of writing is to make you understand when and why to write nested loop? How to write a nested loop?

      C++ program to print Fibonacci series incrementally using nested loop

      In order to demonstrate nested loops, I am going to write a basic c++ program to print the Fibonacci series incrementally using nested loop. The program should first ask the user to enter a number. Then, it should print the first term of the Fibonacci series in the first line, second-term in the second line, third in the third line, and so on up to the number entered by the user. Before starting the guide, we must know what is the Fibonacci series. Let's see what it is?

      What is the Fibonacci series?

      In the Fibonacci series, the first two terms are always 0 and 1. Next to the first two terms, all the terms are the sum of the preceding(previous) two terms. Let's understand the first five terms of the Fibonacci series.e.g 0,1,1,2,3. As said earlier the first two terms are always 0 and 1. The third term is the sum of the first and second term.e.g. (0+1=1). Similarly, the fourth term is the sum of the second and third term.e.g(1+1=2). likewise, the fifth term is also the sum of the third and fourth term.e.g(1+2=3). The same sequence continues up to n number of terms.

      Now we know about the Fibonacci series and our problem statement. We are ready to go for the code.

      #include<iostream>
      using namespace std;
      int main()
      {
       int n,  prevnum, currentnum, nextnum;
       cout<<"Enter a number: ";
       cin>>n;
       for (int j = 0; j <n; j++) {
       prevnum = 0;
       currentnum = 1;
        for (int i = 0; i <= j; i++)
        {
         cout <<" " <<prevnum<<" ";
         nextnum = prevnum + currentnum;
         prevnum = currentnum;
         currentnum = nextnum;
         
        }
        cout << endl;
       }
       
       system("pause");
       return 0;
      }
      

      If we take a look at the code above, we can understand that we have variable n, prevnum, currentnum and nextnum. Variable n is declared to take input from the user. Prevnum and currentnum are variables that store the two preceding terms. Next num is the sum of the preceding two numbers. Here is the stepwise explanation of the code. Let's see what we did in the above code.

      • First of all, we took input from the user in variable n. 
      • Then we wrote a nested loop. The outer loop is restricted to iterate n time which is the input of the user.e.g(5 iterations if the user enters 5)
      • Inside the body of the outer loop, prevnum and currentnum are initialized with 0 and 1 because the first two terms of the Fibonacci series are always 0 and 1.
      • Then, we wrote the inner loop that will iterate j times. It means that the inner loop will iterate until the value of I<=j.
      • Inside the body of the inner loop, we printed prevnum as a term of the Fibonacci series.
      • Then, we calculated the next term of the Fibonacci series by adding prevnum and currentnum.
      • Now prevnum is overwritten with the value of currentnum to print it in the next iteration.
      • In the same way, currentnum is overwritten with the value of the nextnum. 
      • Then we wrote a cout statement for a line break.
      • Here is the end of the first iteration of the outer loop. All the above steps will repeat in the next iteration.
      output
       c++ program to print the Fibonacci series incrementally using nested for loop

      Nested loops are helpful when you want to repeat some actions on every pass of the outer loop. In our example, we are printing terms of the Fibonacci series on every execution of the outer loop. In the above example, the outer loop is creating a sequence of execution for the inner loop while the inner loop is printing terms of the Fibonacci series. Hence, we are executing two interdependable iterations. That's all related to nested loops and c++ program to print the Fibonacci series incrementally using nested for loop. We have demonstrated nested loops with for loop but you can nest other loops in the same way. thanks for reading and supporting us.

      Read More

      Friday, 14 August 2020

      Published August 14, 2020 by Kashif with 0 comment

      C++ program to show questions until the user gives the wrong answer


      I am sure you all are very clear about infinite loops that we have already discussed in our previous post. We discussed how while true can be used to implement an infinite loop in c++. The majority thinks that there is no logical need for while true in c++ programming. Besides, they think infinite loops are not worthy to use. But I think there are some situations where while true and infinite loops can help us reduce complexity. So in this article, I want to demonstrate the importance of while true in c++ programming with a C++ program to show questions until the user gives the wrong answer. This program is a simple c++ game that can help us understand when to use while true or infinite loops. Let's get started.

      C++ program to show questions until the user gives the wrong answer

      For the purpose of demonstration, we want to write a c++ program to show questions. The questions will consist of two random numbers and the user will be asked to answer their sum. The program will keep on asking questions until he is answering correctly. When he gives the wrong answer, the game will end showing the message that your answer is wrong. In other words, we will break the infinite loop when he gives the wrong answer.


      #include <iostream>
      #include <stdlib.h>// for generating random number
      #include <time.h> // for using time ftn
      using namespace std;
      int main() {
      //1)------------declaring variables--------------
      
       int num1,num2, answer;
       srand(time(0));
      //2)------------creating while true loop--------------
      while (true) {
        int sum = 0;
      //3)------------generating and saving random numbers in variables------------
        num1=rand() % 1000 + 1;
        num2 = rand() % 1000 + 1;
      //4)------------displaying question-----------
        cout << "What is the sum of " << num1 << "and " << num2<<"?" << endl;
        sum = num1 + num2;
      //5)------------getting and comparing answer----------------
        cin >> answer;
      
        if (answer == sum) {
         cout << "hurrah!your answer in correct" << endl;
        }
        else {
         cout << "alas!your answer is wrong" << endl;
         cout << "game over" << endl;
         break;
        }
       }
       system("pause");
       return 0;
      }
      


      There are a few things that I think I must address before starting the explanation of the code. We used stdlib and time.h library to use their built-in functions for generating random numbers.

      Rand() function

      This function is responsible for generating random numbers. We use the modulus operator to limit the random numbers up to a specific number e.g generate random numbers less than 100. We use +1 to avoid zero as a random number. This function is available in stdlib library.

      Srand() function

      This function seeds the random numbers used by rand(). This function is helpful if you want to get different random numbers on every program call. The best practice of calling this function is to avail the call to srand(time(0)). Time() function returns a value which varies every time and allows us to get varying random numbers on every call.

      I hope you got the basic idea about the built-in functions. Now let's look at the code.

      If you look at the above code, you can understand that while true is crucial in this situation because we have no condition to control the loop. The above code is divided into few parts to make it easy to understand.
      • First of all, we declared variables num1, num2, and answer. Num1 and num2 are declared to hold two random numbers.
      • Then we wrote while true infinite loop. We also took one more variable sum to store the sum of two random numbers.
      • Thirdly, we generated and stored the random numbers using rand() function in variable num1 and num2.
      • Then we displayed the question to the user to answer. In addition, we also calculated the sum of num1 and num2.
      • In the last part, we took input from the user in variable answer and then compared it with sum using if-else. If the value answer is equal to sum then the program prints that your answer is correct. If the value of answer is not equal to sum, the program prints that your answer is not correct. 
      Output of the program

      That's all about while true. We can conclude that while true or infinite loops are useful when there is no condition to control the loop. We can break the loop using if-else when some undesired action is done. In our above demonstration, the undesired action was the wrong answer. Hope you understood the concept and my point. thanks for reading and supporting us.


        




      Read More

      Tuesday, 4 August 2020

      Published August 04, 2020 by Kashif with 2 comments

      c++ program to print tables from 2 to 10 using nested loop



      As prominent from the title, we are going to write a c++ program to print tables from 2 to 10 using nested loops. We have already discussed all the basics in the previous post about loops and now, we will learn how to nest for and while loops in c++. For this purpose, we will write the same program using nested for loop as well as nested while loop to feel the difference. The comparison between both will help you understand when to use which loop. so let's start.

      c++ program to print tables from 1 to 10 using nested for loop

      Let's consider we want to write a program to print the table of numbers from 2 to 10. In this program, we will first print the title of the table e.g(table of 2). Then, we will print ten multiples of that table. This whole process will repeat 9 times to print the table of all numbers between 2 to 10 with their respective title and ten multiples. We will print the tables according to the format(2 X 1=2).


      #include <iostream>
      using namespace std;
      int main()
      {
       //Outer loop
       for (int i = 2; i <=10; i++) {
        cout << "Table of " << i << endl;
        //Inner loop
        for (int j = 1; j <= 10; j++) {
         cout <<i<<" X "<<j<<"=" << i * j <<"  ";
        }
        cout << endl;
       }
       system("pause");
       return 0;
      }
      


      Now Just look at the above code. Its printing table of numbers between 2 to 10. The first and important thing to notice is there are two loops in this program. Its a nested for loop comprised of an outer and an inner loop. The outer loop is independent while the inner loop is dependent on the outer loop for its execution. Let's see what happens when we run the above program.

      1. First and foremost, the outer loop is executed and it prints the cout statement in the first iteration.
      2. Then the control is passed to the inner loop and it starts printing multiples of i.
      3. Once all the 10 iterations of the inner loop are completed, the cout statement followed by the inner loop is printed which completes the first iteration of the outer loop after updating the loop counter(i) value. The control is again passed to the outer loop for the second iteration. 
      4. The above three steps are repeated until the outer loop completes its 9 iterations. In this way the above c++ program to print tables from 1 to 10 using nested for loop works. 

        c++ program to print tables from 1 to 10 using nested while loop

        Now let's see how can we write the same program using nested while loop. As we have discussed in our previous post with an example that while loops are better to use in circumstances where the number of iterations are unknown. This program also has a known number of iterations. Let's see what complexity while loops create in this program.

        #include <iostream>
        using namespace std;
        int main()
        {
         int i = 2;
         //Outer loop
         while (i <=10) {
          int j = 1;
          cout << "Table of " << i << endl;
          //Inner loop
          while ( j <= 10) {
           cout <<i<<" X "<<j<<"=" << i * j <<"  ";
           j++;
          }
          cout << endl;
          i++;
         }
         system("pause");
         return 0;
        }
        

        Here is the code of the same program using nested while loop. There is not a big difference between the two loops. We easily wrote the program but few things were a little disturbing that give for loops a plus point. Unlike for loop, we have to manage counter variable, condition, and increment statements separately which slightly increase our effort and complexity. So, in circumstances where iterations are known for loops are highly recommended whether it is nested or simple. While loops/nested while loops are better to implement infinite loops, loops where iterations are unknown, loops where iterations depend on user input, etc.

        Output of both programs

        c++ program to print tables from 2 to 10 using nested loop
        c++ program to print tables from 2 to 10 using nested loop 
         That's all about nesting for and while loops and their comparison. Thanks for reading...
        Read More

        Wednesday, 22 July 2020

        Published July 22, 2020 by Kashif with 0 comment

        Loops in c++


        loops in c++

        while writing code, we face situations where we need to repeat things a number of times. In such situations, we can use loops to make our work easy and fast. If we try to handle such situations manually then it can be hardly possible for easy and small tasks. But its not possible when we are solving complex problems(1 thousand repetitions). Let's consider some situations to understand why loops are so important in programming.
        1.  Consider a simple program to print numbers from 1 to 5. This is very easy and one can solve this program using cout statements without using loops. At the same time, if we consider a program to print numbers from 1 to 1000 then only we can understand the importance of loops. It's impossible to print numbers from 1 to 1000 using cout statements because it needs 1000 cout statements. It's tedious and wastage of our precious time. 
        2. int main()
          {
          //printing numbers from 1 to 5 without using loops
           cout << "We are printing " << 1 << endl;
           cout << "We are printing " << 2 << endl;
           cout << "We are printing " << 3 << endl;
           cout << "We are printing " << 4 << endl;
           cout << "We are printing " << 5 << endl;
          //printing numbers from 1 to 1000 with loop
           for (int i = 1; i <= 1000; i++) {
           cout <<"We are printing "<< i <<endl;
           }
           return 0;
          }
          
        3. Consider a program where you have an array of size 10 storing marks of a class. You want to calculate the average marks of the whole class. In this situation, we need a loop to iterate 10 times for calculating the sum of all 10 numbers. Then we will divide the sum with 10(total numbers) to get the final answer.
        4. int main()
          {
           // array storing marks of students
           int marks[10] = {20,21,23,22,27,26,25,19,24,17};
           //variables for storing sum and avg
           int sum=0;
           int avg = 0;
           //for loop for calculating sum
           for (int i = 0; i < 10; i++) {
            sum = sum + marks[i];
           }
           //calculating average 
           //:. formula avg=sum/array size(no of students)
           avg = sum / 10;
           cout << "sum of marks:\t" << sum<<endl;
           cout << "average marks are:\t" << avg << endl;
           system("pause");
           return 0;
          }
          
        Output:
        loops examples
        loops examples

        Now I am sure you are all clear about why we use loops in c++ and programming. Both of the cases were very simple and do not reflect the real programming scenarios but still, it shows the importance of loops. To summarize, loops are useful when you want to
        1. Repeat similar code several times.e.g( print hello world 100 times)
        2. Repeat code when a certain condition is met.e.g( print "its even" only if the number is even)
        3. Repeat code until it reaches its maximum limit using increment and decrement.e.g( calculate the sum of numbers from 1 to 10). 
        These are some uses of loops. Loops are usually implemented through two ways in computer programming.
        1. We can implement loops with previously specifying and defining the number of repetitions/iterations. In this case, the number of iterations are known. For example, consider a program to print hello world 100 times. The number of iterations are already defined(100 iterations).
        2.  We can implement loops with a variable specifying the number of iterations. In this case, the number of iterations are always unknown. 

        Loops in c++

        C++ language has three most popular loops used to repeat or iterate block of code under certain conditions. Let's discuss each of them one by one.

        for loop in c++

        In c++, for loop parentheses is comprised of three statements. The first statement initializes the loop counter variable to some initial value and executes before the execution of the block of code. The second one is used to define conditions for the execution of code. Once the block of code is executed, the third statements update the loop counter variable for the next iteration.e.g(i++,i--). This statement is executed after the execution of the code block. 


        int main()
        {
         for (int x = 0; x <= 10; x++) {
         cout <<"value of x is "<< x <<endl;
         }
         return 0;
        }
        

        For loop is preferred over a while loop when you know exactly how many times you want to iterate through the code block. If the number of iteration is known, for loop can be effectively used to get the job done. One easy example is demonstrated in the above code.  

        while loop in c++

        The while loop loops through the instructions until its expression which is a condition is true. The while expression is a boolean expression which is either true or false. This condition is checked before the execution of the code block. The code is executed only if the expression returns true.

        int main()
        {
         int x = 0;
         int a;
         cout << "how many times you want to print your name" << endl;
         cin >> a;
         while(x!=a) {
          cout << "My Name"<< endl;
          x++;
         }
         return 0;
        }
        

        While loop should be preferred when the number of iteration is unknown and depends on some variable. This type of situations are very easy to code through while loop as you can see in the above code. 

         While and for loops are quite similar to each other in action but do-while loop has something different to do than while and for loops.

        Do-while loops in c++

        The do-while loop executes its code block once without checking its boolean expression(condition).
        Once the code is executed for the first time, it checks the boolean condition to iterate the loop further.


        int main()
        {
         int choice = 0;
         do
         {
          cout << "enter your choice" << endl;
          cout << "1: to enter the program" << endl;
          cout << "0: to to exit the program" << endl;
          cin >> choice;
        
         } while (choice!=0); 
        
         return 0;
        }
        

        Do-while loops are used in menu-driven programs. They are used in programs where the code needs to be executed at least once. You can understand do-while loops easily from the above code. The cout statements are written inside the do-while loop body still it will be printed for the first time. And then the next iteration will be according to the input of user and loop condition.

        Nested loops in c++

        When a loop is written in the body or bases({}) of another loop then such loops are called nested loops. In nested loops, we have an outer independent loop and an inner dependent loop. The inner loop is dependent because it's working completely depends on the outer loop. The inner loop cannot execute until the outer loop is executed.  

        int main()
        {
         for (int j = 0; j < 5; j++)
         {
          for (int x = 0; x <= j; x++)
          {
           cout << "#";
          }
          cout << endl;
         }
        
         
         system("pause");
         return 0;
        }
        


        What is the difference between break and continue statements in c++?

        The break statement is used to terminate the loop. No further iteration takes place when the break statement is written within the braces of a loop. In nested loops, If we write the break statement in the braces of child/inner loop then only the inner/child loop will terminate and not the outer parent loop.
        The parent loop will further iterate.
        The continue statement is very different from the break statement. It only skips one iteration of the loop but does not terminate the loop completely. When written inside the braces of the child/inner loop in nested loops, it only skips the child loop once.



        int main()
        {
         for (int j = 0; j <= 8; j++)
         {
          if (j == 2) {
           continue;
          }
          else if (j == 6) {
           break;
          }
          cout << "current number is :\t" << j << endl;
         }
         
         system("pause");
         return 0;
        }
        

        See output of this program
        break and continue statements in c++
        break and continue statements in c++



        The break and continue statements are usually used with conditional statements like if, switch, etc.

        Why we use while true?

        As we have already discussed that while loop expression is a boolean expression and is evaluated to true or false. When we write true instead of any condition then it means the while loop will iterate infinitely. Such loops are called infinite loops.

        int main()
        {
         while (true) {
        
          cout << "it is infinte loop." << endl;
         }
         
         system("pause");
         return 0;
        }
        

        Infinite loops are used to run code over and over again. These loops can be terminated using a break statement when some undesired action is done. e.g (when the user enters the wrong input ). It is probably used when there is no condition available.

        Read More

        Thursday, 9 July 2020

        Published July 09, 2020 by Kashif with 0 comment

        Conditional statements in c++

        In computer programming, we make decisions based on different conditions to write programs. We either execute a given set of instructions when a certain condition is met or omit some instruction if the condition is false. These statements have boolean conditions that are either evaluated as true or false.C++ has a variety of methods to do the decision making. In this post, we will discuss different conditional statements in c++ with different code examples.


        Conditional statements in c++
        Conditional statements in c++

        Conditions

        C++ has simple conditions that allow us to make decisions and pursue our logic. These simple conditions need two operands and a comparison operator. These conditions are boolean expressions that are either true or false. The working of six comparison operators is as follows.

        Comparison operators and their use in decision making

        ==
        It is evaluated  true if left and right operands are equal
        !=
        It is evaluated  true if left and right operands are not equal
        It is evaluated  true if the left operand is less than the right operand
        It is evaluated  true if the left operand is greater than the right operand
        <=
        It is evaluated  true if the left operand is less than or equal to the right operand
        >=
        It is evaluated  true if the left operand is greater than or equal to the right operand


        If statement c++

        if statement is a statement that executes its block of code only if its condition is satisfied. Its block is ignored if its condition is not true and the program starts the execution of the instructions following this block.


        if (a>10) {//either true of false
        cout<<"value of a is greater than 10";
        //this code will run when condition is true
        }
        

        If else statement c++

        It is a statement with a boolean condition that is either evaluated as true or false. When the condition is true then the set of instructions following if statement is executed. If the condition is false then all the instructions following if statement is omitted and the control of the program goes to else. Then the program executes all the instructions inside the braces of else. 


        if (a>10) {//either true of false
        cout<<"value of a is greater than 10";
        //this code will run when condition is true
        }
        else{
        cout<<"value of a is not greater than 10";
        //this code will run when condition is not true
        }
        

        If else if statement in c++

        In certain circumstances, we need to check more than one condition in a code. If else if statement is used in such circumstances. In this method of decision making, we provide multiple options or restrictions using else if statements. Else if statement also has a boolean condition that is either evaluated as true or false. Unlike if statement, else if statement can be used multiple times to check multiple conditions in a given scenario. In c++, if-else-if statements are executed from top to bottom.


        if (a>10) {//either true of false
        cout<<"value of a is greater than 10";
        //this code will run when condition is true
        }
        else if(a>20){//either true of false
        cout<<"value of a is greater than 20";
        //this code will run when else if condition is true
        }
        else if(a>30){//either true of false
        cout<<"value of a is greater than 30";
        //this code will run when else if condition is true
        }
        else if(a>40){//either true of false
        cout<<"value of a is greater than 40";
        //this code will run when else if condition is true
        }
        else{
        cout<<"value of a is not greater than 10";
        //this code will run when all conditions are not false
        }
        


        Nested if else in c++

        When we write if-else statement inside the braces of a parent if or else statement than it is called nested if-else in c++. Nested if-else means writing if statement inside the braces of a parent if or else statement.  It is used to apply some minor or less important conditions when a major condition is satisfied.


        if (a>0) {// parent if else statement with outer major(most important) condition
        
         
         if (a%2==0) {//child if else statement with inner minor(less important) condition
          cout << "The number positive even number" << endl;
         }
         else {
          cout << "The number positive odd number" << endl; }
        } 
        else {
         cout << "the number is negative" << endl;
        }
        



        The concept of nested if-else can be better understood through grade calculating program.

        Switch Statement in c++

        We can also use the switch statements for decision making instead of if-else-if(ladder) statements in some cases. In the switch statement, the switch expression(with a variable being switched) is executed and evaluated first. then the value of the switch expression /variable is matched with the values of switch cases. If the value matches then the associated switch case is executed. The break statement should be used at the end of the case's block to avoid the execution of other cases. The default case runs when the expression doesn't equal any case and it's optional. 


        switch (num) {// switch expression
        case 1: //switch case 
         cout << "english language" << endl;
         break;
        case 2: {//switch case
         cout << "computer studies" << endl;
         cout << "seats full";
         break;
         }
        case 3://switch case 
         cout << "Medicine" << endl;
         break;
        case 4://switch case 
         cout << "Economics" << endl;
         break;
        default://runs when there is no match
         cout << "Invalid course code" << endl;
        }
        


        Ternary operator in c++

        Instead of writing an if-else statement, we can also use a ternary operator. It is a conditional operator that operates on three operands. It is used for decision-making and it also diminishes your lines of code. Ternary operator has many benefits over simple if-else statements but it cannot execute multiple instructions when the condition is met.  


        int main() {
         int num = 3;
         string ans = (num % 2 == 0) ? "Even." : "Odd.";
         cout << ans;
         return 0;
        }
        



        Compound conditional statements and logical operators

        We can write compound conditional expressions by using the logical operators AND, OR, and NOT in c++. Compound conditional statements can be used to replace many lines nested if-else statements with few lines. We can use multiple boolean conditions through a logical operator to write a compound conditional expression using if statement. let's see how it happens.

        Logical operator AND:
        && is the symbol of AND operator. The braces of compound if statement is only executed if all the conditions are true. If any of the conditions is false then the block of code is not executed.

        Logical operator OR:
        || is the symbol of OR operator. The block of code is executed if one of the conditions is true. If both conditions are false then the braces of the compound if statement will not run.

        Logical operator NOT:
        ! is the symbol of NOT operator. The block is only executed if the condition is false.

        void main() {
         int a = 15;
         if (a > 10 && a < 100) { //AND operator used
          cout << "a is greater than 10 and less than 100";
         }
         else if (a > 10 || a < 100) { //OR operator used
          cout << "a is either greater than 10 or less than 100 or both";
         }
         else if (!(a > 10 && a < 100)) {//NOT operator used
          cout << "a is either less than 10 or greater than 100";
         }
         else {
          cout << "All conditions are false";
         }
        }
        


        Practice programs:
        These programs are written to compare different methods of decision making to find which method is good and why? Obviously, every method has pros and cons. You can understand when to use which method through these practice program.
        Find the largest value between three variables
        c++ program to check whether a character is vowel or consonant

        Read More