Coding C++ Advanced PDF
Document Details
Uploaded by RetractableTrumpet4904
Greenfields School
Tags
Summary
This document provides an introduction to C++ programming language. It contains instructions on writing basic programs, conditional constructs, loops and includes practice exercises. It is useful for beginners.
Full Transcript
# Program Coding C++ Advanced ## Connect **Write the output of the following program.** ```c++ #include<iostream.h> void main() { cout<<45+90<<endl; cout<<4+5*2<<endl; cout<<4*5+9*10<<endl; cout<<15%4<<endl; cout<<(4+5)*9-10<<"and"; cout<<4/2*3<<endl; } ``` ## Learn * Conditional constructs:...
# Program Coding C++ Advanced ## Connect **Write the output of the following program.** ```c++ #include<iostream.h> void main() { cout<<45+90<<endl; cout<<4+5*2<<endl; cout<<4*5+9*10<<endl; cout<<15%4<<endl; cout<<(4+5)*9-10<<"and"; cout<<4/2*3<<endl; } ``` ## Learn * Conditional constructs: If ... else; switch case * Loops: for loop; while loop; do-while loop ## Task You understood the need and importance of a programming language and how to write simple programs. Let us further learn the concepts of conditional construct and loops to write error-free programs ## Practise ### Activity 1 **A. Accept the principle, rate of interest, and time from the user to calculate the simple interest. Write the input and output you get.** ```c++ #include<iostream.h> void main() { float Principle, Rate, Time, SimpleInterest; cout<<"Principle:"; cin>>Principle; cout<<"Rate:"; cin>>Rate; cout<<"Time:"; cin>>Time; SimpleInterest= Principle * Rate * Time /100; cout<<"Simple Interest: "<<SimpleInterest<<endl; } ``` You can declare an identifier to assign a constant value, that is a representation for a constant, whose value will remain the same during the execution of the program. **B. Find the output.** ```c++ const int Age=60; void main() { int MyAge=5; } cout<<"60 Years Later"<<MyAge+Age; ``` **C. Find the output.** ```c++ const float PIE=3.1416; void main() { float Radius=5, Area; Area=PIE*Radius*Radius; cout<<"Area:"<<Area<<endl; } ``` ## Unary Operators Unary operators work on a single operand. The three types of unary operators are given in Table 7.1. | Operator | Meaning | Usage | Evaluation | Output (if int x=10) | | --------- | ------------------------------------- | ----- | ----------- | ------------------- | | ++ | It is the increment operator | X++ | X=X+1 | 11 | | -- | It is the decrement operator | X-- | X=X-1 | 9 | | ! | It is the logical NOT operator | !(X) | !(X==5) | True | **Tech Fact** The increment and decrement operator can be used in two ways: as a prefix or as a postfix to a variable. ## Binary Operators Binary operators work on two operands. They have the following three categories (Table 7.2). | Operator | Usage | | ------------------ | ----------------------------------------------- | | Arithmetic Operator | Used to do arithmetic calculations | | Relational Operator | Used to compare two values/variables | | Logical Operator | Use to combine two conditions | ### Arithmetic Operators: Arithmetic operators are as follows: | Operator | Description | | --------- | ---------------- | | + | Addition | | - | Subtraction | | * | Multiplication | | / | Division | | % | Remainder | ## Relational Operators: Relational operators are used to compare values of two operands. Table 7.3 shows Relational operators. | Operator | Description | Sample condition | Description | | --------- | ----------------- | ----------------- | ------------------------------------------------ | | == | Equal to | A==B | Will be TRUE **if** A and B are equal | | > | Greater than | A>B | Will be TRUE **if** A is greater than B | | < | Less than | A<B | Will be TRUE **if** A is less than B | | >= | Greater than or Equal to | A>=B | Will be TRUE **if** A is greater than or equal to B | | <= | Less than or Equal to | A<=B | Will be TRUE **if** A is less than or equal to B | | != | Not Equal to | A!=B | Will be TRUE **if** A is not equal to B | ## Logical Operators: Logical operators are used to combine two conditions or negate a condition. While execution, it follows the order of procedure as (),!, &&, ||(i.e. Brackets, NOT, AND, OR). Logical operators are shown in Table 7.4. | Operator | Description | Sample Compound Condition | Description | | --------- | ------------ | -------------------------- | ------------------------------------------------------------------------ | | && | AND | Age>=60 && Gender=='M' | Will be TRUE **if** both conditions are TRUE | | || | OR | Age>=60 || Gender=='M' | Will be TRUE **if** any one of the conditions is TRUE | | ! | NOT | !(Amount>1000) | Will be TRUE **if** the condition mentioned in brackets is **NOT** TRUE | ## Ternary Operators Ternary operators work on three operands. Ternary operators are like a conditional statement. The syntax of a ternary operator is as follows: (condition) ? (if_true) : (if_false) **For example:** int x=15; int\_y=(x==15)? 10:20; //here it means if x is equal to 15 then y will be assigned 10 otherwise 20 cout<<(x<=10)?"Good": "Not so good"; ## Arithmetic Assignment Operators You can use the assignment operator (=) to assign the value of the right operand to the left operand. An arithmetic assignment operator combines an arithmetic operator and an assignment operator. The arithmetic assignment operators present in C++ are: +=, -=, *=, /=, %= . Table 7.5 shows different arithmetic assignment operators: | Operator | Description | Example | Explanation | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------- | | += | It adds the operands and assigns the result value to the left operand | x+= y | x= x+ y | | -= | It subtracts the right operand from the left operand and stores the result in the left operand | x-= y | x=x-y | | *= | It multiplies the operand and stores the result in the left operand | x*= y | x=x*y | | /= | It divides the left operand by the right operand and stores the result in the left operand | x/=y | x=x/y | | %= | It divides the left operand by the right operand and stores the remainder in the left operand | x%=y | x= remainder of x/y | ## Operator Precedence The operator precedence specifies the order in which the operator will be executed in an expression. If there are two operators with the same precedence, evaluation is done from left to right. Table 7.6 specifies the precedence of different operators in C++. The precedence decreases as we move down the table. | Precedence | Operator | | ----------- | ---------------- | | Brackets | [ ], () | | Unary Operators | ++, --, ! | | Arithmetic Operators | *, /,% | | Arithmetic Operators | +,- | | Insertion/ Extraction Operator | <<, >> | ## Conditional Constructs Conditional constructs help us execute a set of statements based on a condition. The result of the decision made based on a given condition in a program defines the sequence of execution of the program. You can use conditional constructs to control the flow of execution of a program. There are four conditional constructs present in C++ 1. if construct 2. if...else construct 3. if...else if construct 4. switch...case construct ### The if Construct **Syntax**: if (condition) { // statements } The if statement evaluates the condition. If the test expression is evaluated to true, statements inside the body of if are executed followed by the rest of the statements. The flowchart of If construct is given in Fig. 7.1. If the test expression is evaluated to false, statements inside the body of if are skipped. **Example:** if (a = 5) { cout<<“a is equal to 5"; } cout<<"this statement will be executed"; ### The if... Else Construct **Syntax:** if (condition) { statement1; } else { statement2; } The if... else executes the codes inside the body of if statement if the condition is true and skips the codes inside the body of else. If the condition is false, it executes the codes inside the body of else statement and skips the codes inside the body of if. The flowchart of If...else construct is given in Fig. 7.2. **Example:** if (a>b) { cout<<"a is greater than b”; } else { cout<<"b is greater than a"; } ### The if...Else If Construct **Syntax:** if (condition1) { // statements to be executed if condition 1 is true } else if (condition 2) { // statements to be executed if condition 1 is false and condition 2 is true } else if (condition 3) { // statements to be executed if condition 1 and condition 2 are false and condition 3 is true { else { // statements to be executed if all conditions are false } The if...else if statement executes three different codes depending upon whether the condition is true or false. Sometimes, a choice has to be made from more than 3 possibilities. It allows you to check for multiple conditions. **Example:** { int number; cout<<“Enter an integer: “; cin >> number; if (number > 0) { number << “You entered a positive integer: “ << 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."; } ### Comparing If and Switch Conditional Statements The following table compares the if construct with switch construct. | Syntax: | if | switch | | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | if (<condition>) <Statement1>; else if (condition>) <Statement2>; else <StatementN>; | switch (<Variable>) { case <Value>:<Statement1>; case <Value2>:<Statement2>; case <Value3>:<Statement3>; default:<Statement>; } | | Allows | conditions with all relational operators conditions with all logical operators conditions with variables of all data types | conditions with equal to/not equal to conditions catering to or operator conditions with char and int variables only Note: Conditions with <,> <=,>= will not be possible in **switch** | ## Loops in C++ Loops in programming languages are used for repeating the execution of the same statements again and again. In C++, there are three types of loops, for loop, while loop and do...while loop. ### For Loop **Syntax:** for(<init>;<condition>;<inc/decrement>) <Statement>; **Example:** for(int i=0;i<=5;i++) cout<<i<<":"; You will get the output as: 1:2 : 3: 4: 5 : In For loop the condition is at the beginning. The loop works best when the loop is to be executed for a finite sequence. If the condition is not true in the beginning, the loop statements are not executed even once. For more than one statement in the loop we require to enclose them in curly braces. The flowchart of for loop is given in Fig. 7.3. **Working of For Loop** 1. The initialization statement is executed only once at the beginning. 2. The test expression is evaluated. 3. If the test expression is false, for loop is terminated. But if the test expression is true, statements inside the body of for loop are executed and expression is updated. 4. The test expression is evaluated and this process repeats until the test expression is false. ### While Loop **Syntax:** while(<Condition>) Statement; **Example:** int i=1; while(i<=5) cout<<i++<<":"; You will get the output as: 1:2:3:4: 5: In while loop the condition is in the beginning. This is best when you require to execute the loop statements only if the condition is true. The number of iterations may not be known at the start of the loop. For more than one statement in the loop we require to enclose them in curly braces. The flowchart of while loop is given in Fig. 7.4. **Working of While Loop** 1. The while loop evaluates the test expression. 2. If the test expression is true, statements inside the body of while loop are evaluated. 3. The test expression is evaluated again. This process goes on until the test expression is false. 4. When the test expression is false, while loop is terminated. ### Do..While Loop **Syntax:** do { <Statement>; } while(<condition>); **Example:** int i=1; do { cout<<i++<<":"; } while(i<=5); You will get the output: 1: 2: 3: 4: 5: In the do...while loop the condition is placed at the end. The loop is ideal when you require to execute the loop statement(s) at least once. The number of iterations is not known at the starting of the loop. Curly braces are required even for a single statement in the loop. The flowchart of do...while loop is given in Fig. 7.5. **Working of Do...While Loop** 1. The statements inside the body of loop are executed at least once. 2. Only the test expression is checked. 3. If the test expression is true, the body of loop is executed. This process continues until the test expression becomes false. 4. When the test expression is false, do...while loop is terminated. ## Activity 4 **A. Write the C++ code to display N even numbers.** ```c++ int N; cout<<"N:";cin>>N; for(int i=1;i<=N;i++) cout<<2*i<<":"; ``` **B. Write the C++ code to find and display the sum of the following series: 3+8+13+.... Nth term** ```c++ int N, Suma=0, Sumb=0; cout<<"N:";cin>>N; //Sum of series a for(int i=1;i<=N;i++) { cout<<2*i-1<<"+"; Suma+=2*1-1; } cout<<"\b="<<Suma<<endl; //Sum of series b for(i=1;i<=N;i++) { cout<<5*1-2<<"+"; Sumb+=5*1-2; } cout<<"\b="<<Sumb<<endl; ``` **C. Check if a number is a prime or not (A prime number is a number that is divisible by 1 and self).** ```c++ int N, IsPrime=1; cout<<"Enter N:";cin>>N; for(int i=2; IsPrime && i<=N/2;i++) if(N%i==0) IsPrime=0; if (N>1 && IsPrime) cout<<N<<"is a prime number"<<endl; ``` **D. Write a C++ code for calculating LCM of two numbers.** ```c++ int N1, N2, Big; cout<<"N1:";cin>>N1; cout<<"N2:";cin>>N2; Big= (N1>N2)?N1:N2; while(Big%N1!= 0 || Big%N2!=0) Big++; cout<<"LCM:"<<Big<<endl; ``` **E. Write a C++ code for reversing a number up to 4 digits.** ```c++ int N, TN, Rev = 0; cout<<"N:";cin>>N; TN=N; while(TN>0) { Rev=Rev*10+TN%10; TN=TN/10; } cout<<N<<"Reversed: "<<Rev<<endl; ``` ## Recap * Unary operators work on a single operand. Increment, Decrement and Not operators are examples of unary operators. * Binary operators work on two operands. Arithmetic, Relational and Logical operators are examples of Binary operators. * Ternary operators work on three operands. They are like a conditional statement. * There are two conditional contracts present in C++ if...else construct and switch...case construct. * In C++, There are three types of loops, for loop, while loop and do-while loop. ## Checklist | Term | I got it! | I need help! | | ----------------------------- | -------- | ------------ | | Operators | | | | If...else statement | | | | Switch Case statement | | | | For Loop | | | | While loop | | | | Do... While loop | | | ## Evaluate **A. Fill in the blanks with the help of the given words.** += left to right if Relational do...while 1. ____ operator is used to compare two values/variables. 2. ____ operator adds the operands and assigns the result value to the left operand 3. If there are two operators with same precedence, evaluation is done from ____. 4. The ____ conditional construct is followed by a logical expression where the variables are compared and a decision is made. 5. In ____ loop curly braces are required even for a single statement in the loop.