Top Banner
Some More C++ Explicit Casting, some more operators, Conditions, Loops Engineer Jokhio Sultan Salahuddin Kohistani Lecturer, CSE, MUET Jamshoro Session - II
64

Some More C++

Apr 05, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 1/64

Some More C++

Explicit Casting, some more

operators, Conditions, Loops

Engineer Jokhio Sultan Salahuddin Kohistani

Lecturer, CSE, MUET Jamshoro

Session - II

Page 2: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 2/64

Explicit Casting

Conversion with force or forceful conversion orconversation 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 forconversion to take place.

Page 3: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 3/64

Explicit Casting 1

#include<iostream>using namespace std;

int main(){

float z = static_cast<float>(1)/2;

cout<<z;return 0;

}

Page 4: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 4/64

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.

Page 5: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 5/64

 Task

Write the program which can input roots for a quadraticequation (a,b,c) and solve the equation for that roots andfind out the solution.

= − ±

− 42

 

Page 6: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 6/64

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 negativeroots are "<<ngX;

return 0;

}

Page 7: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 7/64

Operators

These entities perform some kind of operations over theoperands.

Three Categories

Arithmetic (+, -, *, /, %, op operators, unary increment

decrement) Logical (&&, ||, !)

Relational (>, <, >=, <=, ==, !=)

Page 8: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 8/64

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 toetc. etc.

These are :

They return some Boolean value (1, 0 or true, false) as resultof comparison

Operator Purpose

== 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

!= Checks for inequality

Page 9: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 9/64

Relational Operators

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

int z = 2;

cout<<a<z; //returns 0

Results

on nextslide

Page 10: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 10/64

Relational Operators

Page 11: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 11/64

A common mistake!

People get confused in Assignment Operator (=) &

Equality Relational Operator (==)

Assignment is only used to assign values to the variable atleft hand side.

While, Equality Relational Operator is used to comparetwo values for equality.

1==2; //return what??

int a;

a = 2; //is

a==2; // different from above a=2.

Page 12: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 12/64

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;

}

Page 13: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 13/64

Loops

Loops are used to repeat/iterate statements.

Page 14: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 14/64

Loops

Loops are one of basic features of programming, whichallows an statement or a group of statements to beexecuted 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, Doloop or Do-While Loop.

All are used with different situations.

Page 15: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 15/64

 The for Loop

Used when the exact number of iterations/repetitions areknown.

Used in case, we know in advance that how much numberof 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 arecontained in place, in one peace.

Syntax on the next slide.

Page 16: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 16/64

for loop syntax

for (initialization expression; testexpression; increment expression)

single statement;

for (initialization expression; testexpression; increment expression){

statement;

statement;

statement;} 

If Single Statement is needs to looped.

In case of Multiple Statements, enclosethem into pair of curly braces to form acode block.

Page 17: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 17/64

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 thesquare of j

cout << endl;

return 0;

}

Page 18: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 18/64

for Loop syntax

Page 19: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 19/64

for Loop Operation

Have a look at the fordemo.cpp once again.

Page 20: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 20/64

Some for loops variations

for (int z = 100;z>=1;z--); //loop from100 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++); //loopfrom -100 to 100 with step +1

Page 21: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 21/64

 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;

}

Page 22: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 22/64

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;

}

Page 23: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 23/64

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 willcomplete its all iterations.

Nested for loops have a lot of applications, they aremostly used to access elements in multidimensional

arrays.*

Page 24: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 24/64

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;

Page 25: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 25/64

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 2ndcolumn

}return 0;

}

Page 26: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 26/64

Variable Scope

Variable Scope is the capability of a variable to beaddressed/called.

Sometimes called variable’s 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.

Page 27: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 27/64

 The While Loop

Used when we don’t know the exact number of repetitions to be performed in our program.

It uses “while” (without quotes) as a c++ keyword forlooping.

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 thosestatements, which are just below, outside the loop body. 

Page 28: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 28/64

While Syntax

for single statementwhile (condition or test expression)

Statement;

for multiple statementswhile (condition or test expression)

{

statement(s);

Page 29: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 29/64

Syntax

Page 30: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 30/64

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;

}

Page 31: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 31/64

Explanation

Now the loop continues to ask to the user to input anumber (n) until 100 is not inputted. As this conditionwill become true, loop will stop and will execute rest of the statements.

So, As long as the test expression is true, the loopcontinues to be executed. In above, the text expression

n != 100 (n not equal to 100) is true until the user enters100.

Since there is not any pair of braces, the single cinstatement is inside the loop, while the cout statement is

 just outside the loop.

Page 32: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 32/64

Operation of the While loop

Page 33: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 33/64

#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 numbercout << 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;

}

Page 34: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 34/64

 The Fibonacci Series

Write a Program which can print the Fibonacci series.

In the next program we are using unsigned keyword infront data types, which will enforce the compiler toconsider only the positive values, while the negative willbe omitted.

 Also depicts the precedence between Relational and Arithmetic 

operators.

Page 35: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 35/64

#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;

}

Page 36: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 36/64

Precedence between relational and

arithmetic operators

You might be thinking of placing the arithmetic operationinside the pair of Parenthesis i.e. next<(limit / 2) 

to enforce the arithmetic operation to take place priorthan the relational one, but that is not the story at all,because compiler automatically thinks of the precedence,since according to language specifications, arithmeticoperators have the higher precedence than relationaloperators, so they would be evaluated first and thenresult is operated with relational operator.

Page 37: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 37/64

 The Output

Page 38: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 38/64

 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, doloop places condition at last, at also checks conditionafter executing the statements.

The do loop, despite of having true or false condition,executes the loop statements at least once, and thenchecks the condition, if then condition is false, it will exitthe 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

Page 39: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 39/64

 The do loop Syntax

In case of single statement.

dostatement;

while (condition);

In case of multiple statements.

do {statement;

statement;}

while (condition); 

#include <iostream> 

Page 40: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 40/64

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;

}

Page 41: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 41/64

Explanation

Initially loop statements are executed and then conditionch != ‘n’ is checked, now if the user have entered n, then

condition will become false, and loop will stop, but if theuser continues to enter some other character, thecondition will remain true, and loop will execute thestatements once again. This will continue, up till the userdoes not enter n from the keyboard.

Output

Page 42: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 42/64

Syntax

Page 43: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 43/64

Operation of the do loop

Page 44: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 44/64

Decision Making Statements

Decision Making is a controlling mechanism.

Sometimes, in daily life we make decisions based onspecific situations and conditions, Similarly in computerprogramming 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.

Page 45: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 45/64

 The If and If-Else structure.

Every Decision is based on some condition.

If structure is used to take decision based on thecondition, if condition is true, decision is taken andstatement(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.

Page 46: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 46/64

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;

}

Page 47: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 47/64

Syntax

Page 48: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 48/64

Operation of the If Loop

Page 49: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 49/64

If with else: Syntax

Page 50: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 50/64

If-else operation

Page 51: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 51/64

#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;

}

Page 52: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 52/64

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++) //divide by every integer from

if(n%j == 0) {

cout<<“It’s not prime; divisible by “<<j<<endl;

exit(0);}

cout << “It’s prime\n”; 

return 0;

}

Page 53: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 53/64

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 insideprocess.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 numbersfrom 2 up to n/2. The divisor is j, the loop variable. If any value of jdivides evenly into n, then n is not prime. When a number dividesevenly into another, the remainder is 0; we use the remainderoperator % in the if statement to test for this condition with

each value of j. If the number is not prime, we tell the user andwe exit from the program. Here’s output of the program:

Enter a number: 13

It’s prime

Page 54: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 54/64

 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 keyfrom the keyboard or they simply for a character input.

They provide means for holding the screen, in case user isdirectly executing the program without entering the DOS.

The difference b/w getch() and getche() is that getche() asksthe 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.

Page 55: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 55/64

Program

#include<iostream>

#include<conio.h>

using namespace std;

int main(){

char z1 = 'H';cout<<z1<<'\n';

getche();

getch();return 0;

}

Page 56: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 56/64

 The Switch-Case Statement

Provides alternative way in case we have a large if-elsedecision tree.

If you have a large decision tree based on single variableas if-else conditions, you can use the switch-case clause

more conveniently. Switch-Case structure works in cases of single variable’s

possible varying value.

Page 57: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 57/64

Syntax

Page 58: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 58/64

Operation

Page 59: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 59/64

So, where ever switch’s case is matched, that particular

block is executed and break keyword forces the controlto 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 placedat last of the switch case block.

Page 60: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 60/64

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;

}

Page 61: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 61/64

 Task

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

Page 62: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 62/64

Logical Operators

These operators allow you to combine the Booleanvalues (which could be result of a relational operation ora Boolean data type’s value), and they also produce

Boolean (true / false) value as a result.

Three operators;

AND (&&)

OR (||)

NOT (!)

Page 63: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 63/64

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;

}

Page 64: Some More C++

8/2/2019 Some More C++

http://slidepdf.com/reader/full/some-more-c 64/64

The End of Session - II