Вы находитесь на странице: 1из 64

Session - II

Some More C++ Explicit Casting, some more operators, Conditions, Loops
Engineer Jokhio Sultan Salahuddin Kohistani Lecturer, CSE, MUET Jamshoro

Explicit Casting

Conversion with force or forceful conversion or conversation with brutality. Using static_cast keyword. Syntax

data-type var-name = static_cast<data-type> (value);

The data-type at both sides must be same, in order for conversion to take place.

Explicit Casting 1
#include<iostream> using namespace std; int main(){ float z = static_cast<float>(1)/2; cout<<z; return 0; }

Explicit Casting 2
#include<iostream> using namespace std; int main(){ int asciiCode = static_cast<int>('A'); cout<<asciiCode; return 0; } This program will show the ascii code of the given character.

Task

Write the program which can input roots for a quadratic equation (a,b,c) and solve the equation for that roots and find out the solution.
2 4 = 2

Solution
#include<iostream> #include<cmath> using namespace std; int main(){ float a, b, c; double psX, ngX; cout<<"Enter value of A";cin>>a; cout<<"Enter value of B";cin>>b; cout<<"Enter value of C";cin>>c; psX = ((-1 * b)+sqrt(b*b-4*a*c))/(2*a); ngX = ((-1 * b)-sqrt(b*b-4*a*c))/(2*a); cout<<"Positive roots are "<<psX<<" and negative roots are "<<ngX; return 0; }

Operators

These entities perform some kind of operations over the operands. Three Categories Arithmetic (+, -, *, /, %, op operators, unary increment decrement) Logical (&&, ||, !) Relational (>, <, >=, <=, ==, !=)

Relational Operators

These type of operators compare two values. Value can be built-in data types. Comparison is performed in terms of higher, lower, equal to etc. etc. Operator Purpose These are :
== > < >= Checks for equality Checks is greater than Checks is lower than Checks is greater than or equal to

<=

Checks is lower than or equal to

They return some Boolean value (1, 0 orfor inequality as result != Checks true, false) of comparison

Relational Operators

cout<<5>3; //returns 1 int a = 5; int z = 2; cout<<a<z; //returns 0

Results on next slide

Relational Operators

A common mistake!

People get confused in


Assignment Operator (=) & Equality Relational Operator (==)

Assignment is only used to assign values to the variable at left hand side. While, Equality Relational Operator is used to compare two values for equality. 1==2; //return what?? int a; a = 2; //is a==2; // different from above a=2.

Program
// relat.cpp // demonstrates relational operators #include <iostream> using namespace std; int main() { int numb; cout << Enter a number: ; cin >> numb; cout << numb<10 is << (numb < 10) << endl; cout << numb>10 is << (numb > 10) << endl; cout << numb==10 is << (numb == 10) << endl; return 0; }

Loops

Loops are used to repeat/iterate statements.

Loops

Loops are one of basic features of programming, which allows an statement or a group of statements to be executed multiple times, depending on the condition. Loop continues to execute statements, while the condition remains true. When condition becomes false, loop ends and stops. There are three kinds of loops, For Loop, While Loop, Do loop or Do-While Loop. All are used with different situations.

The for Loop

Used when the exact number of iterations/repetitions are known. Used in case, we know in advance that how much number of times, statements need to execute. To use for loop, we have for (without quotes) C++ keyword. Its one of easiest loops, as all loop elements are contained in place, in one peace. Syntax on the next slide.

for loop syntax


for (initialization expression; test expression; increment expression)
single statement;
If Single Statement is needs to looped.

for (initialization expression; test expression; increment expression){


statement; statement; statement; }
In case of Multiple Statements, enclose them into pair of curly braces to form a code block.

Program
// fordemo.cpp // demonstrates simple FOR loop #include <iostream> using namespace std; int main() { int j; //define a loop variable for(j=0; j<15; j++) //loop from 0 to 14, cout << j * j << ; //displaying the square of j cout << endl; return 0; }

for Loop syntax

for Loop Operation

Have a look at the fordemo.cpp once again.

Some for loops variations

for (int z = 100;z>=1;z--); //loop from 100 to 1 with step of -1. for (int i = 5;i<=100;i+=5); //loop from 5 to 100 with step of +5. for (int i = -100; i<101;i++); //loop from -100 to 100 with step +1

Table Program
#include<iostream> using namespace std; int main(){ int a; cout<<"Input any number, and i will generate its table\n"; cin>>a; cout<<"Upto which extent table must be generated?\n";

int z;
cin>>z; cout<<'\n'; for (int i = 1; i<=z; i++)

cout<<a<<'*'<<i<<'='<<a*i<<'\n';
return 0; }

Factorial Program
// factor.cpp // calculates factorials, demonstrates FOR loop #include <iostream> using namespace std; int main() { int numb; long fact=1L; //long for larger numbers cout << Enter a number: ; cin >> numb; //get number for(int j=numb; j>0; j--) //multiply 1 by fact *= j; //numb, numb-1, ..., 2, 1 cout << Factorial is << fact << endl; return 0; }

Nested for Loop


Nested : one inside other. for loops are also used inside arrays to access different array elements. * One for loop can be nested inside the other one. for each single step of the outer loop, inner for loop will complete its all iterations. Nested for loops have a lot of applications, they are mostly used to access elements in multidimensional arrays.*

Program
#include<iostream> using namespace std; int main(){ for (int j = 1; j<= 10; j++){ for (int i = 1; i<=5; i++) cout<<i+i<< " "; cout<<endl; } return 0; }

Multiple Statements in for


#include <iomanip> //for setw using namespace std; int main() { int numb; //define loop variable for(numb=1; numb<=10; numb++) //loop from 1 to 10 { cout << setw(4) << numb; //display 1st column int cube = numb*numb*numb; //calculate cube cout << setw(6) << cube << endl; //display 2nd column } return 0; }

Variable Scope

Variable Scope is the capability of a variable to be addressed/called. Sometimes called variables visibility. Variables some time depends on the blocks of statements inside { }. In the previous program, cube variable is not accessible outside the for Block. Since it is declared inside its block, so its scope is only limited to that block.

The While Loop

Used when we dont know the exact number of repetitions to be performed in our program. It uses while (without quotes) as a c++ keyword for looping. It continues to execute the statements associated with it, if the condition is true, if suddenly condition become false, it will not execute the statements, and will jump to those statements, which are just below, outside the loop body.

While Syntax

for single statement


while (condition or test expression) Statement;

for multiple statements while (condition or test expression) { statement(s); }

Syntax

Program
// endon100.cpp // demonstrates WHILE loop #include <iostream> using namespace std; int main() { int n; while( n != 100 ) // loop until n is 0 cin >> n; // read a number into n cout << endl; return 0; }

Explanation

Now the loop continues to ask to the user to input a number (n) until 100 is not inputted. As this condition will become true, loop will stop and will execute rest of the statements. So, As long as the test expression is true, the loop continues to be executed. In above, the text expression n != 100 (n not equal to 100) is true until the user enters 100. Since there is not any pair of braces, the single cin statement is inside the loop, while the cout statement is just outside the loop.

Operation of the While loop

#include <iostream> #include <iomanip> //for setw using namespace std; int main(){ int pow=1; //power initially 1 int numb=1; //numb goes from 1 to ??? while( pow<10000 ){ //loop while power <= 4 digits cout << setw(2) << numb; //display number cout << setw(5) << pow << endl; //display fourth power ++numb; //get ready for next power pow = numb*numb*numb*numb; //calculate fourth power } cout << endl; return 0; }

The Fibonacci Series

Write a Program which can print the Fibonacci series.

In the next program we are using unsigned keyword in front data types, which will enforce the compiler to consider only the positive values, while the negative will be omitted. Also depicts the precedence between Relational and Arithmetic operators.

#include <iostream> using namespace std; int main() { const unsigned long limit = 4294967295; //largest long unsigned long next=0; //next-to-last term unsigned long last=1; //last term while( next < limit / 2 ) { cout << last << ; //display last term long sum = next + last; //add last two terms next = last; //variables move forward last = sum; // in the series } cout << endl; return 0; }

Precedence between relational and arithmetic operators

You might be thinking of placing the arithmetic operation inside the pair of Parenthesis i.e. next<(limit / 2) to enforce the arithmetic operation to take place prior than the relational one, but that is not the story at all, because compiler automatically thinks of the precedence, since according to language specifications, arithmetic operators have the higher precedence than relational operators, so they would be evaluated first and then result is operated with relational operator.

The Output

The do loop (or do-while loop)


The do loop is a bit different from the other ones. Unlike while loop, which places the condition at top, do loop places condition at last, at also checks condition after executing the statements. The do loop, despite of having true or false condition, executes the loop statements at least once, and then checks the condition, if then condition is false, it will exit the loop, if it is still true, the do loop will again execute the statement until the condition is not becoming false. It uses do (without quotes) keyword, and while (without quotes) keyword as well

The do loop Syntax


In case of single statement. do

statement;

while (condition); In case of multiple statements. do {

statement; statement; }

while (condition);

#include <iostream> using namespace std; int main(){ long dividend, divisor; char ch; do { cout<<Enter dividend: ; cin>>dividend; cout<<Enter divisor: ; cin>>divisor; cout<< Quotient is << dividend / divisor; cout<<, remainder is << dividend % divisor; cout<<\nDo another? (y/n): ; //do it again? cin>>ch; } while( ch != n ); //loop condition return 0; }

Explanation

Initially loop statements are executed and then condition ch != n is checked, now if the user have entered n, then condition will become false, and loop will stop, but if the user continues to enter some other character, the condition will remain true, and loop will execute the statements once again. This will continue, up till the user does not enter n from the keyboard. Output

Syntax

Operation of the do loop

Decision Making Statements


Decision Making is a controlling mechanism. Sometimes, in daily life we make decisions based on specific situations and conditions, Similarly in computer programming decisions are also made on certain conditions. We have many structures for implementing the decision making in C++. If Structure, If- else, switch-case structures are used for decision making problems.

The If and If-Else structure.


Every Decision is based on some condition. If structure is used to take decision based on the condition, if condition is true, decision is taken and statement(s) associated with it are executed. If is simplest decision making structure. Sometimes it is combined with else keyword to provide the facility of alternative decision.

Program
// ifdemo.cpp // demonstrates IF statement #include <iostream> using namespace std; int main() { int x; cout << Enter a number: ; cin >> x; if( x > 100 ) cout << That number is greater than 100\n; return 0; }

Syntax

Operation of the If Loop

If with else: Syntax

If-else operation

#include <iostream> using namespace std; int main() { int x; cout << \nEnter a number: ; cin >> x; if( x > 100 ) cout << That number is greater than 100\n; else cout << That number is not greater than 100\n; return 0; }

prime number program


#include <iostream> using namespace std; #include <process.h> //for exit() int main() { unsigned long n, j; cout <<Enter a number: ; cin >> n; If(n<1){cout<<Invalid Number:;exit(0);}

for(j=2; j <= n/2; j++)


if(n%j == 0) {

//divide by every integer from

cout<<Its not prime; divisible by <<j<<endl; exit(0);

}
cout << Its prime\n; return 0; }

process.h and exit() function & explanation

exit(0), zero inside parenthesis, is used to suddenly stop the execution of the program at any place, since it is contained inside process.h header file, we also need to include it inside our program. In this example the user enters a number that is assigned to n. The program then uses a for loop to divide n by all the numbers from 2 up to n/2. The divisor is j, the loop variable. If any value of j divides evenly into n, then n is not prime. When a number divides evenly into another, the remainder is 0; we use the remainder operator % in the if statement to test for this condition with each value of j. If the number is not prime, we tell the user and we exit from the program. Heres output of the program: Enter a number: 13 Its prime

The getch() and getche() Functions

To use getch() or getche() we must include conio.h header file as #include<conio.h> The getch() and getche() ask the user to press some key from the keyboard or they simply for a character input. They provide means for holding the screen, in case user is directly executing the program without entering the DOS. The difference b/w getch() and getche() is that getche() asks the user to enter a character and also allows echoes (displays on the screen) entered character as soon as it in typed, while getch() only asks the character to be inputted. both can save a character in a variable.

Program
#include<iostream> #include<conio.h> using namespace std; int main(){ char z1 = 'H'; cout<<z1<<'\n'; getche(); getch(); return 0; }

The Switch-Case Statement

Provides alternative way in case we have a large if-else decision tree. If you have a large decision tree based on single variable as if-else conditions, you can use the switch-case clause more conveniently. Switch-Case structure works in cases of single variables possible varying value.

Syntax

Operation

So, where ever switchs case is matched, that particular block is executed and break keyword forces the control to move outside the block of the code. If no any case is matched, then the code inside default: keyword is executed and switch-case is finished. According to standard convention, default must be placed at last of the switch case block.

Example
#include<iostream> using namespace std; int main(){ char englishLetterA; cout<<Enter A:;cin>>englishLetterA; switch(englishLetterA){ case A:

cout<<Capital A;break;
case a: cout<<small a;break; default:

cout<<Invalid Input not A or a; break;


} return 0; }

Task

Write a program, which asks the user to input an english alphabet letter, and determines whether it is consonant or a vowel (using switch-case operators).

Logical Operators

These operators allow you to combine the Boolean values (which could be result of a relational operation or a Boolean data types value), and they also produce Boolean (true / false) value as a result. Three operators;

AND (&&) OR (||) NOT (!)

Logical operators
#include<iostream> using namespace std; int main(){ int num1, num2, num3; cout<<"enter three decimal numbers\n"; cin>>num1>>num2>>num3; if(num1>num2 && num1>num3)cout<<num1<<" is largest\n"; if(num2>num1 && num2>num3)cout<<num2<<" is largest\n"; if(num3>num1 && num3>num2)cout<<num3<<" is largest\n"; if (num1==num2 || num1==num3 || num2==num3) cout<<"All "<<num1<<"'s are equal"; return 0; }

The End of Session - II

Вам также может понравиться