15.1.2001Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 5.

Slides:



Advertisements
Similar presentations
Computer Programming w/ Eng. Applications
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
L5:CSC © Dr. Basheer M. Nasef Lecture #5 By Dr. Basheer M. Nasef.
Lecture 2 Introduction to C Programming
Introduction to C Programming
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
1 Operators And Expressions. 2 Operators Arithmetic Operators Relational and Logical Operators Special Operators.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
ISBN Chapter 7 Expressions and Assignment Statements.
Chapter 2 Data Types, Declarations, and Displays
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
1  Ex: Declare a variable to store user’s age: int age; Prompt the user to enter his/her age: printf (“ How old are you? “); Read / scan the entered value.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Programming in C Spring Semester 2013Programming and Data Structure1.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Conditional Statement
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
1 CSC103: Introduction to Computer and Programming Lecture No 6.
C Programming n General Information on C n Data Types n Arithmetic Operators n Relational Operators n if, if-else, for, while by Kulapan Waranyuwat.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Selection-making Decisions Selection allows you to choose between two or more possible program flow --- it lets you make decisions in your program. Examples.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 4.
1 Expressions. 2 Variables and constants linked with operators  Arithmetic expressions Uses arithmetic operators Can evaluate to any value  Logical.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
CSE 1320 Basics Dr. Sajib Datta
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Control Statements: Part1  if, if…else, switch 1.
 Most C programs perform calculations using the C arithmetic operators (Fig. 2.9).  Note the use of various special symbols not used in algebra.  The.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Chapter 4 – C Program Control
Chapter 7: Expressions and Assignment Statements
Operators And Expressions
Chapter 7: Expressions and Assignment Statements
Arithmetic Operator Operation Example + addition x + y
CS1100 Computational Engineering
Chapter 4 - Program Control
3 Control Statements:.
Relational, Logical, and Equality Operators
Chapter 4 - Program Control
Basic Programming Concepts
Chap 7. Advanced Control Statements in Java
OPERATORS in C Programming
DATA TYPES There are four basic data types associated with variables:
DATA TYPES AND OPERATIONS
OPERATORS in C Programming
Presentation transcript:

Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 5

Sudeshna Sarkar, IIT Kharagpur 2 Variables It is an identifier used to represent a specified type of information within a designated portion of the program The data item must be assigned to the variable at some point of the program It can be accessed later by referring to the variable name A given variable can be assigned different data items at different places within the program.

Sudeshna Sarkar, IIT Kharagpur 3 int a, b, c ; char d; a = 3; b = 5; c = a+b; d = ‘a’ ; a = 4; b = 2; c = a-b; d = ‘D’ ; abcd 3 ? ?? ? ?? ? 3?? 3 5 ?

Sudeshna Sarkar, IIT Kharagpur 4 Declaration of Variables data-type variable-list ; int a, b, c; float root1, root2; char flag, response; Declaration : 1. specifies the name of the variable 2. Specifies what type of data the variable will hold.

Sudeshna Sarkar, IIT Kharagpur 5 A First Look at Pointers A variable is assigned a specific memory location. For example, a variable speed is assigned memory location Also assume that the memory location contains the data value 100. When we use the name speed in an expression, it refers to the value 100 stored in the memory location. distance = speed * time; Thus every variable has an address (in memory), and its contents.

Sudeshna Sarkar, IIT Kharagpur 6 Contd. In C terminology, in an expression speed refers to the contents of the memory location. &speed refers to the address of the memory location. Examples: printf (“%f %f %f”, speed, time, distance); scanf (“%f %f”, &speed, &time);

Sudeshna Sarkar, IIT Kharagpur 7 An Example #include int main() { float speed, time, distance; scanf (“%f %f”, &speed, &time); distance = speed * time; printf (“\n The distance traversed is: \n”,distance); }

Sudeshna Sarkar, IIT Kharagpur 8 Assignment Statement Used to assign values to variables, using the assignment operator (=). General syntax: variable_name = expression; Examples: velocity = 20; b = 15; temp = 12.5; /* Multiple assign on same line */ A = A + 10; v = u + f * t; s = u * t * f * t * t;

Sudeshna Sarkar, IIT Kharagpur 9 Contd. A value can be assigned to a variable at the time the variable is declared. int speed = 30; char flag = ‘y’; Several variables can be assigned the same value using multiple assignment operators. a = b = c = 5; flag1 = flag2 = ‘y’; speed = flow = 0.0;

Sudeshna Sarkar, IIT Kharagpur 10 Operators in Expressions Operators Arithmetic Operators Relational Operators Logical Operators

Sudeshna Sarkar, IIT Kharagpur 11 Operator Precedence In decreasing order of priority 1. Parentheses :: ( ) 2. Unary minus :: Multiplication, Division, and Modulus 4. Addition and Subtraction For operators of the same priority, evaluation is from left to right as they appear. Parenthesis may be used to change the precedence of operator evaluation.

Sudeshna Sarkar, IIT Kharagpur 12 Examples: Arithmetic expressions a + b * c – d / e  a + (b * c) – (d / e) a * -b + d % e – f  a * (-b) + (d % e) – f a – b + c + d  (((a – b) + c) + d) x * y * z  ((x * y) * z) a + b + c * d * e  (a + b) + ((c * d) * e)

Sudeshna Sarkar, IIT Kharagpur 13 Integer Arithmetic When the operands in an arithmetic expression are integers, the expression is called integer expression, and the operation is called integer arithmetic. Integer arithmetic always yields integer values.

Sudeshna Sarkar, IIT Kharagpur 14 Real Arithmetic Arithmetic operations involving only real or floating-point operands. Since floating-point values are rounded to the number of significant digits permissible, the final value is an approximation of the final result. 1.0 / 3.0 * 3.0 will have the value and not 1.0 The modulus operator cannot be used with real operands.

Sudeshna Sarkar, IIT Kharagpur 15 Mixed-mode Arithmetic When one of the operands is integer and the other is real, the expression is called a mixed- mode arithmetic expression. If either operand is of the real type, then only real arithmetic is performed, and the result is a real number. 25 / 10  2 25 / 10.0  2.5 Some more issues will be considered later.

Sudeshna Sarkar, IIT Kharagpur 16 Relational Operators Used to compare two quantities. <is less than > is greater than <=is less than or equal to >=is greater than or equal to ==is equal to !=is not equal to

Sudeshna Sarkar, IIT Kharagpur 17 Examples 10 > 20 is false 25 < 35.5is true 12 > (7 + 5)is false When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will be evaluated first and then the results compared. a + b > c – d is the same as (a+b) > (c+d)

Sudeshna Sarkar, IIT Kharagpur 18 Logical Operators Logical operators act upon logical expressions && : and (true if both operands are true) || : or (true if either or both operands true ! : negates the value of the logical expression Example (n >= lo_bound) && (n <= upper_bound) ! (num > 100)

Sudeshna Sarkar, IIT Kharagpur 19 Example: Logical Operators int main () { int i, j; for (i=0; i<2; i++) { for (j=0; j<2; j++) printf (“%d AND %d = %d, %d OR %d=%d\n”, i,j,i&&j, i,j, i||j) ; }

Sudeshna Sarkar, IIT Kharagpur 20 [himalay] $./a.out 0 AND 0 = 00 OR 0 = 0 0 AND 1 = 00 OR 1 = 1 1 AND 0 = 01 OR 0 = 1 1 AND 1 = 11 OR 1 = 1 [himalay] $

Sudeshna Sarkar, IIT Kharagpur 21 int main () { int amount ; /* The no of bytes to be transferred */ int rate ; /* The average network transfer rate */ int time; /* The time, in seconds, for the transfer */ int hours, minutes, seconds; /* The no of hrs,mins,secs for the transfer*/ printf (“How many bytes of data to be transferred ?\n”) ; scanf (“%d”, &amount) ; printf (“What is the average transfer rate in bytes/sec ?\n”) ; scanf (“%d”, &rate) ; time = amount / rate ; hours = time / 3600 ; minutes = (time % 3600) / 60 ; seconds = ((time % 3600) % 60) /60 ; printf (“The expected time is %dh %dm %ds\n”, hours,minutes,seconds); }

Sudeshna Sarkar, IIT Kharagpur 22 C’s special operators ++ and -- : a trademark of C programming ++ : increments a variable ; -- : decrements a variable x++ In an expression, value of this expression is the value of x prior to increment ++x In an expression, value of this expression is the value of x after the increment.

Sudeshna Sarkar, IIT Kharagpur 23 x = 4; y = x++; x = 4; y = ++x ; y=4, x=5 after evaluation y=5, x=5 after avaluation x += 5 equivalent to x = x + 5 h %= f equivalent to h = h%f product *= num equivalent to product = product * num

Sudeshna Sarkar, IIT Kharagpur 24 int main () { int x = 10; printf (“ x = %d\n”, ++x) ; primtf (“x = %d\n”, x++) ; } Question : What will get printed ?

Sudeshna Sarkar, IIT Kharagpur 25 Exercise Suppose your program contains two integer variables, x and y which have values 3 and 4 respectively, Write C statements that will exchange the values in x and y such that after the statements are executed, x is equal to 4 and y is equal to 3. First, write this routine using a temporary variable for storage. Now re-write this routine without using a temporary variable for storage.

Sudeshna Sarkar, IIT Kharagpur 26 Control Structures: conditional constructs if (x <= 10) y = x * x + 5; if (x <= 10) { y = x * x + 5; z = (2 * y)/4 ; } if (x <= 10) y = x * x + 5; z = (2 * y)/4 ; if (condition) action ; condition action

Sudeshna Sarkar, IIT Kharagpur 27 if statement if (expression) statement1 if (expression) statement1 else statement2 expression must have an integral type. Zero is false, nonzero is true. Notes: expression must be parenthesized

Sudeshna Sarkar, IIT Kharagpur 28 Examples if (0 <= age && age <= 11) kids = kids + 1 ; if ( month == 4 || month == 6 || month == 9 || month == 11 printf ( “ The month has 31 days\n ” ); if (x=2) y = 5; if (x== 2) y = 5; What is the difference ?

Sudeshna Sarkar, IIT Kharagpur 29 if-else statement if (condition) action-if ; else action-else ; condition action-if action-else TF

Sudeshna Sarkar, IIT Kharagpur 30 int main () { int month ; printf (“Pls enter the no of the month”) ; scanf (“%d”, &month) ; if (month==4 || month==6 || month==9 || month==11) printf (“The month has 30 days\n) ; else if (month ==1 || month==3 || month==5 || month==7 || month==8 || month ==10 || month==12) printf (“The month has 31 days\n); else if (month == 2) printf (“The month has 28 or 29 days\n”) ; else printf (“Don’t know that month\n”) ; } Example 1 : if

Sudeshna Sarkar, IIT Kharagpur 31 main () { int dividend, divisor, result ; printf (“Enter the dividend: ”) ; scanf (“%d”, &dividend) ; printf (“Enter the divisor: “) ; scanf (“%d”, &divisor) ; if (divisor != 0) { result = dividend/divisor; printf (“Result of division is %d\n”, result); } else printf (“A divisor of 0 is not allowed\n”); } Example 2 : if

Sudeshna Sarkar, IIT Kharagpur 32 Dangling else problem if (exp1) if (exp2) stmta else stmtb if (exp1) if (exp2) stmta else stmtb OR if (exp1) if (exp2) stmta else stmtb ?

Sudeshna Sarkar, IIT Kharagpur 33 Avoiding the dangling else problem Null statement if (exp1) if (exp2) stmta else ; else stmtb Compound statement if (exp1) { if (exp2) stmta } else stmtb

Sudeshna Sarkar, IIT Kharagpur 34 else if statements if (expression) statement else if (expression) statement else if (expression) statement else statement if (x%4 == 0) sum += 2; else if (x%4 == 1) sum *= 2; else if (x%4 == 2) sum--; else if (x%4 == 3) sum++; else sum += 4;

Sudeshna Sarkar, IIT Kharagpur 35 switch switch (expression){ case const-expr/: statements default : statements } switch (choice = getchar()) { case ‘r’ : case ‘R’: printf(“Red”); break; case ‘b’ : case ‘B’ : printf(“Blue”); break; case ‘g’ : case ‘G’: printf(“Green”); break; default: printf(“Black”); }

Sudeshna Sarkar, IIT Kharagpur 36 switch (digit) { case 0: case 1: case 2: case 3: case 4: printf (“Round down\n”); break; case 5: case 6: case 7: case 8: case 9:printf(“Round up\n”); }

Sudeshna Sarkar, IIT Kharagpur 37 int main () { int operand1, operand2; int result = 0; char operation ; /* Get the input values */ printf (“Enter operand1 :”); scanf(“%d”,&operand1) ; printf (“Enter operation :”); scanf (“\n%c”,&operation); printf (“Enter operand 2 :”); scanf (“%d”, &operand2); switch (operation) { case ‘+’ : result=operand1+operand2; break;

Sudeshna Sarkar, IIT Kharagpur 38 case ‘-’ : result=operand1-operand2; break; case ‘*’ : result=operand1*operand2; break; case ‘/’ : if (operand2 !=0) result=operand1/operand2; else printf(“Divide by 0 error”); break; default: printf(“Invalid operation\n”); } printf (“The answer is %d\n”,result); }

Sudeshna Sarkar, IIT Kharagpur 39 Iteration Constructs Iteration constructs repeat a sequence of code in a controlled manner. while for do-while

Sudeshna Sarkar, IIT Kharagpur 40 while loop while (expression) statement while (i < n) { printf (“Line no : %d.\n”,i); i++; } expression statement (loop body) F T