For Loop

 


 

 

In computer programming, loops are used to repeat a block of code.

For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.

That was just a simple example; we can achieve much more efficiency and sophistication in our programs by making effective use of loops.

There are 3 types of loops in C++.

  • for loop
  • while loop
  • do...while loop

C++ for loop

The syntax of for-loop is:

for (initialization; condition; update) {
    // body of-loop 
}

Here,

  • initialization - initializes variables and is executed only once
  • condition - if true, the body of for loop is executed
    if false, the for loop is terminated
  • update - updates the value of initialized variables and again checks the condition


Example: Printing Numbers From 1 to 5

#include <iostream>

using namespace std;

int main() {
        for (int i = 1; i <= 5; ++i) {
        cout << i << " ";
    }
    return 0;
}

Output

1 2 3 4 5

Here is how this program works

Iteration  Variable i <= 5 Action
1st              
i = 1 true      
1 is printed. i is increased to 2.
2nd i = 2 true 2 is printed. i is increased to 3.
3rd i = 3 true 3 is printed. i is increased to 4.
4th i = 4 true 4 is printed. i is increased to 5.
5th i = 5 true 5 is printed. i is increased to 6.
6thi = 6false  The loop is terminated             

 

Ranged Based for Loop

In C++11, a new range-based for loop was introduced to work with collections such as arrays and vectors. Its syntax is:

for (variable : collection) {
    // body of loop
}

Here, for every value in the collection, the for loop is executed and the value is assigned to the variable.


Example: Range Based for Loop

#include <iostream>

using namespace std;

int main() {
  
    int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
    for (int n : num_array) {
        cout << n << " ";
    }
  
    return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

In the above program, we have declared and initialized an int array named num_array. It has 10 items.

Here, we have used a range-based for loop to access all the items in the array.


C++ Infinite for loop

If the condition in a for loop is always true, it runs forever (until memory is full). For example,

// infinite for loop
for(int i = 1; i > 0; i++) {
    // block of code
}

In the above program, the condition is always true which will then run the code for infinite times.

 

0 comments:

Switch Statement

 

Switch Statement

The switch statement allows us to execute a block of code among many alternatives.

The syntax of the switch statement in C++ is:

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

  • If there is a match, the corresponding code after the matching label is executed. For example, if the value of the variable is equal to constant2, the code after case constant2: is executed until the break is encountered.
  • If there is no match, the code after default: is executed.

Note: We can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.

 

C++ switch...case flowchart 

 

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement
#include <iostream>
using namespace std;

int main() {
    char oper;
    float num1, num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> oper;
    cout << "Enter two numbers: " << endl;
    cin >> num1 >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            cout << num1 << " / " << num2 << " = " << num1 / num2;
            break;
        default:
            // operator is doesn't match any case constant (+, -, *, /)
            cout << "Error! The operator is not correct";
            break;
    }

    return 0;
}

Output 1

Enter an operator (+, -, *, /): +
Enter two numbers: 
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -
Enter two numbers: 
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *
Enter two numbers: 
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /
Enter two numbers: 
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?
Enter two numbers: 
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition, subtraction, multiplication, and division.

How This Program Works

  1. We first prompt the user to enter the desired operator. This input is then stored in the char variable named oper.
  2. We then prompt the user to enter two numbers, which are stored in the float variables num1 and num2.
  3. The switch statement is then used to check the operator entered by the user:
    • If the user enters +, addition is performed on the numbers.
    • If the user enters -, subtraction is performed on the numbers.
    • If the user enters *, multiplication is performed on the numbers.
    • If the user enters /, division is performed on the numbers.
    • If the user enters any other character, the default code is printed.

Notice that the break statement is used inside each case block. This terminates the switch statement.

If the break statement is not used, all cases after the correct case are executed.

 

0 comments:

C++ Ternary Operator

 

 

 

Ternary Operator in C++

A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.

Its syntax is

condition ? expression1 : expression2;

Here, condition is evaluated and

  • if condition is true, expression1 is executed.
  • And, if condition is false, expression2 is executed.

The ternary operator takes 3 operands (condition, expression1 and expression2). Hence, the name ternary operator.


Example : C++ Ternary Operator

#include <iostream>
#include <string>
using namespace std;

int main() {
  double marks;

  // take input from users
  cout << "Enter your marks: ";
  cin >> marks;

  // ternary operator checks if
  // marks is greater than 40
  string result = (marks >= 40) ? "passed" : "failed";

  cout << "You " << result << " the exam.";

  return 0;
}

Output 1

Enter your marks: 80
You passed the exam.

Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first expression "passed" is assigned to result.

Output 2

Enter your marks: 39.5
You failed the exam.

Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false. Hence, the second expression "failed" is assigned to result.

 

When to use a Ternary Operator?

In C++, the ternary operator can be used to replace certain types of if...else statements.

 

Nested Ternary Operators

It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary operator in C++.

Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.

#include <iostream>
#include <string>
using namespace std;

int main() {
  int number = 0;
  string result;

  // nested ternary operator to find whether
  // number is positive, negative, or zero
  result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

  cout << "Number is " << result;

  return 0;
}

Output

Number is Zero

In the above example, notice the use of ternary operators,

(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

Here,

  • (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string value "Zero" to result.
  • Else, the second test condition (number > 0) is evaluated if the first condition is false.

 

 

0 comments:

If,If...Else & Nested If...Else

 


 

In computer programming, we use the if statement to run a block code only when a certain condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.

  • if the percentage is above 90, assign grade A
  • if the percentage is above 75, assign grade B
  • if the percentage is above 65, assign grade C

There are three forms of if...else statements in C++.

  1. if statement
  2. if...else statement
  3. if...else if...else statement

 

C++ if Statement

The syntax of the if statement is:

if (condition) {
   // body of if statement
}

The if statement evaluates the condition inside the parentheses ( ).

  • If the condition evaluates to true, the code inside the body of if is executed.
  • If the condition evaluates to false, the code inside the body of if is skipped

 

Example: C++ if Statement

// Program to print positive number entered by the user
// If the user enters a negative number, it is skipped

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter an integer: ";
    cin >> number;

    // checks if the number is positive
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    }
    cout << "This statement is always executed.";
    return 0;
}

Output 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

When the user enters 5, the condition number > 0 is evaluated to true and the statement inside the body of if is executed.

Output 2

Enter a number: -5
This statement is always executed.

When the user enters -5, the condition number > 0 is evaluated to false and the statement inside the body of if is not executed.

 

 

C++ if...else

The if statement can have an optional else clause. Its syntax is:

if (condition) {
    // block of code if condition is true
}
else {
    // block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.

If the condition evaluates true,

  • the code inside the body of if is executed
  • the code inside the body of else is skipped from execution

If the condition evaluates false,

  • the code inside the body of else is executed
  • the code inside the body of if is skipped from execution

 

C++ if...else...else if statement

The if...else statement is used to execute a block of code among two alternatives. However, if we need to make a choice between more than two alternatives, we use the if...else if...else statement.

The syntax of the if...else if...else statement is:

if (condition1) {
    // code block 1
}
else if (condition2){
    // code block 2
}
else {
    // code block 3
}

Here,

  • If condition1 evaluates to true, the code block 1 is executed.
  • If condition1 evaluates to false, then condition2 is evaluated.
  • If condition2 is true, the code block 2 is executed.
  • If condition2 is false, the code block 3 is executed.

 

Example: C++ if...else...else if

// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main() {
     int number;

    cout << "Enter an integer: ";
    cin >> number;
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    } 
else if (number < 0) {
      cout << "You entered a negative integer: " << number << endl;
     } 
else {
        cout << "You entered 0." << endl;
    }
     cout << "This line is always printed.";
    return 0;
}

Output 1

Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.

Output 2

Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.

Output 3

Enter an integer: 0
You entered 0.
This line is always printed.

In this program, we take a number from the user. We then use the if...else if...else ladder to check whether the number is positive, negative, or zero.

If the number is greater than 0, the code inside the if block is executed. If the number is less than 0, the code inside the else if block is executed. Otherwise, the code inside the else block is executed.

 

C++ Nested if...else

Sometimes, we need to use an if statement inside another if statement. This is known as nested if statement.

Think of it as multiple layers of if statements. There is a first, outer if statement, and inside it is another, inner if statement. Its syntax is:

// outer if statement
if (condition1) {
    // statements

    // inner if statement
    if (condition2) {
        // statements
    }
}

Notes:

  • We can add else and else if statements to the inner if statement as required.
  • The inner if statement can also be inserted inside the outer else or else if statements (if they exist).
  • We can nest multiple layers of if statements.

 


Example: C++ Nested if

// C++ program to find if an integer is even or odd or neither (0)
// using nested if statements

#include <iostream>
using namespace std;

int main() {
    int num;
    
    cout << "Enter an integer: ";  
     cin >> num;    

    // outer if condition
    if (num != 0) {
        
        // inner if condition
        if ((num % 2) == 0) {
            cout << "The number is even." << endl;
        }
         // inner else condition
        else {
            cout << "The number is odd." << endl;
        }  
    }
    // outer else condition
    else {
        cout << "The number is 0 and it is neither even nor odd." << endl;
    }
    cout << "This line is always printed." << endl;
}

Output 1

Enter an integer: 34
The number is even.
This line is always printed.

Output 2

Enter an integer: 35
The number is odd.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither even nor odd.
This line is always printed.

In the above example,

  • We take an integer as an input from the user and store it in the variable num.
  • We then use an if...else statement to check whether num is not equal to 0.
    • If true, then the inner if...else statement is executed.
    • If false, the code inside the outer else condition is executed, which prints "The number is 0 and neither even nor odd."
  • The inner if...else statement checks whether the input number is divisible by 2.
    • If true, then we print a statement saying that the number is even.
    • If false, we print that the number is odd.

 



 

 

0 comments:

Hello World

 

 

C++ "Hello World!" Program

// Your First C++ Program

#include <iostream>

int main() {
    std::cout << "Hello World!";
    return 0;
}


Output 

Hello World!

 

 

 

Working of C++ "Hello World!" Program

  1. // Your First C++ Program

    In C++, any line starting with // is a comment. Comments are intended for the person reading the code to better understand the functionality of the program. It is completely ignored by the C++ compiler.
  2. #include <iostream>

    The #include is a preprocessor directive used to include files in our program. The above code is including the contents of the iostream file.

    This allows us to use cout in our program to print output on the screen.

    For now, just remember that we need to use #include <iostream> to use cout that allows us to print output on the screen.
  3. int main() {...}

    A valid C++ program must have the main() function. The curly braces indicate the start and the end of the function.

    The execution of code beings from this function.
  4. std::cout << "Hello World!";

    std::cout prints the content inside the quotation marks. It must be followed by << followed by the format string. In our example, "Hello World!" is the format string.

    Note: ; is used to indicate the end of a statement.
  5. return 0;

    The return 0; statement is the "Exit status" of the program. In simple terms, the program ends with this statement.

0 comments:

ABOUT C++

 

 


 

 

C++ is a general-purpose object-oriented programming language developed by Bjarne stroustrup of Bell Labs in 1979. C++ was originally called ‘C with classes,’ and was built as an extension of the C language. Its name reflects its origins; C++ literally means ‘increment C by 1.’

It was renamed C++ in 1983, but retains a strong link to C, and will compile most C programs. Compared to C, C++ added object-oriented features to C such as classes, abstraction, and inheritance.

C++ is considered a mid-level programming language, combining some elements of low-level programming languages, such as the need to learn memory management, with high-level features.C++ is a high-level object-oriented programming language that helps programmers write fast, portable programs. C++ provides rich library support in the form of Standard Template Library (STL).

 

C++ Language Features

Some of the interesting features of C++ are:

  • Object-oriented: C++ is an object-oriented programming language. This means that the focus is on “objects” and manipulations around these objects. Information about how these manipulations work is abstracted out from the consumer of the object.
  • Rich library support: Through C++ Standard Template Library (STL) many functions are available that help in quickly writing code. For instance, there are standard libraries for various containers like sets, maps, hash tables, etc.
  • Speed: C++ is the preferred choice when latency is a critical metric. The compilation, as well as the execution time of a C++ program, is much faster than most other general purpose programming languages.
  • Compiled: A C++ code has to be first compiled into low-level code and then executed, unlike interpreted programming languages where no compilation is needed.
  • Pointer Support: C++ also supports pointers which are widely used in programming and are often not available in several programming languages.

It is one of the most important programming lanugage because almost all the programs/systems that you use have some or the other part of the codebase that is written in C/C++. Be it Windows, be it the photo editing software, be it your favorite game, be it your web browser, C++ plays an integral role in almost all applications that we use.

Uses/Applications of C++ Language

After exploring C++ features, let's have look at some interesting areas where C++ is popularly used.

Operating Systems

Be it Microsoft Windows or Mac OSX or Linux - all of them are programmed in C++. C/C++ is the backbone of all the well-known operating systems owing to the fact that it is a strongly typed and a fast programming language which makes it an ideal choice for developing an operating system. Moreover, C is quite close to the assembly language which further helps in writing low-level operating system modules.

Browsers

The rendering engines of various web browsers are programmed in C++ simply because if the speed that it offers. The rendering engines require faster execution to make sure that users don’t have to wait for the content to come up on the screen. As a result, such low-latency systems employ C++ as the programming language.

Libraries

Many high-level libraries use C++ as the core programming language. For instance, several Machine Learning libraries use C++ in the backend because of its speed. Tensorflow, one of the most widely used Machine Learning libraries uses C++ as the backend programming language. Such libraries required high-performance computations because they involve multiplications of huge matrices for the purpose of training Machine Learning models. As a result, performance becomes critical. C++ comes to the rescue in such libraries.

Graphics

All graphics applications require fast rendering and just like the case of web browsers, here also C++ helps in reducing the latency. Software that employ computer vision, digital image processing, high-end graphical processing - they all use C++ as the backend programming language. Even the popular games that are heavy on graphics use C++ as the primary programming language. The speed that C++ offers in such situations helps the developers in expanding the target audience because an optimized application can run even on low-end devices that do not have high computation power available.

Banking Applications

One of the most popularly used core-banking system - Infosys Finacle uses C++ as one of the backend programming languages. Banking applications process millions of transactions on a daily basis and require high concurrency and low latency support. C++ automatically becomes the preferred choice in such applications owing to its speed and multithreading support that is made available through various Standard Template Libraries that come as a part of the C++ programming kit.

Cloud/Distributed Systems

Large organizations that develop cloud storage systems and other distributed systems also use C++ because it connects very well with the hardware and is compatible with a lot of machines. Cloud storage systems use scalable file-systems that work close to the hardware. C++ becomes a preferred choice in such situations because it is close to the hardware and also the multithreading libraries in C++ provide high concurrency and load tolerance which is very much needed in such scenarios.

Databases

Postgres and MySQL two of the most widely used databases are written in C++ and C, the precursor to C++. These databases are used in almost all of the well-known applications that we all use in our day to day life - Quora, YouTube, etc.

Embedded Systems

Various embedded systems like medical machines, smartwatches, etc. use C++ as the primary programming language because of the fact that C++ is closer to the hardware level as compared to other high-level programming languages.

Telephone Switches

Because of the fact that it is one of the fastest programming languages, C++ is widely used in programming telephone switches, routers, and space probes.

Compilers

The compilers of various programming languages use C and C++ as the backend programming language. This is because of the fact that both C and C++ are relatively lower level languages and are closer to the hardware and therefore are the ideal choice for such compilation systems. These are a few uses and applications of C++ programming language. Now, let's know more about C++ advantages over other programming languages.

Advantages of C++ Language

C++ has the following 2 features that make it a preferred choice in most of the applications:

  • Speed: C++ is faster than most other programming languages and it provides excellent concurrency support. This makes it useful in those areas where performance is quite critical and the latency required is very low. Such requirements occur all the time in high-load servers such as web servers, application servers, database servers, etc. C++ plays a key role in such servers.
  • Closer to hardware: C++ is closer to hardware than most other programming languages like Python, etc. This makes it useful in those areas where the software is closely coupled with hardware and low-level support is required at the software level.

0 comments: