Docsity

Computer Basics: Operators, Loops, If-else Statements, Slides of Computer Fundamentals

Partial preview of the text

Download Computer Basics: Operators, Loops, If-else Statements and more Slides Computer Fundamentals in PDF only on Docsity!

ME-

Computer Fundamentals

TODAY’S LECTURE

Relational Operator (Re-visited) Logical Operator (Re-visited) While Loop Do While Loop Nested If-else 2

LOGICAL OPERATORS

Two logical operators

  • AND &&
  • OR II
  • Not! Connects two sentence or conditions, the result of both conditions is added according to the operator used Example int k = 5; Int m = 12; Operation Meaning Result 3>k && k <10 k greater than 3 and k <10 1 3>k II k <10 k greater than 3 or k <10 1 3>k && m <10 k greater than 3 and m <10 0 3>k II m <10 k greater than 3 or m <10 1

EXAMPLE-

Situation : Check whether an integer K is even and divisible by 5 --------Header Files---------- main(){ int K =20; if(K%2==0&&K%5==0) cout<<“K is divisible by 5 and is also even”; else cout<<“Condition Failed”; }

EXAMPLE-

Situation: Check that two integers A and B both are even Sol: main(){ int A=10,B=25; if((A%2==0)B && (B%2==0) ) cout<<“Both are even “; else cout<<“Condition Failed”; }

EXAMPLE-03 (CONTINUED)

Situation: Check that two integers A and B both are even Sol: main(){ int A=10,B=25; if((A%2!=0)B || (B%2!=0) ) cout<<“Condition Failed”; else cout<<“Both are even “; }

WHILE LOOP EXAMPLE

Consider: count = 0; // Initialization while (count < 3) // Loop Condition { cout << "Hi "; // Loop Body count++; // Update expression } Loop body executes how many times?

DO-WHILE LOOP SYNTAX:

2-

WHILE VS. DO-WHILE

  • Very similar, but…
    • One important difference Issue is "WHEN" boolean expression is checked while: checks BEFORE body is executed do-while: checked AFTER body is executed
  • After this difference, they’re essentially identical!
  • while is more common, due to it’s "flexibility"

IF-ELSE STATEMENT SYNTAX

Formal syntax: if (<boolean_expression>) <yes_statement> else <no_statement> Note each alternative is only ONE statement! To have multiple statements execute in either branch we use { }

MULTIWAY IF-ELSE:

Not new, just different indenting Syntax:

MULTIWAY IF-ELSE EXAMPLE:

PROGRAM LOGIC

If slaray is between 30000 and 50000 tax = 5 % otherwise if marks is between 50,000 and 100,000 tax =10% otherwise if marks is between 100,000 and 200, tax=15%

PROGRAM

int marks; int tax; If(marks>=30,000 && marks<50,000) else If(marks>=50,000 && marks<100,000) else If(marks>=100,000 && marks<200,000)