Unit 3 Control Structure

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

Chapter 7: User-Defined Functions II
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Fundamentals of C and C++ Programming Control Structures and Functions.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 8: Arrays and Functions Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Module 6 – Decision Control Statements Objectives  Understands Increment/Decrement operators, Conditional and special operators in C  Understands significance.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Core Java Statements in Java.
Control Structures (Repetition structure) Jump Statements
‘C’ Programming Khalid Jamal.
User-Written Functions
Chapter 7: User-Defined Functions II
EKT120 COMPUTER PROGRAMMING
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
C Program Controls + Flow Structure
Functions and Structured Programming
Week 4 – Repetition Structures / Loops
Module 4 Functions – function definition and function prototype.
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Hector Cen Fall 2017
C Short Overview Lembit Jürimägi.
Introduction to C Programming Language
Programmazione I a.a. 2017/2018.
User-Defined Functions
11/10/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Looping.
Arrays, For loop While loop Do while loop
CS1100 Computational Engineering
Chapter 7 Additional Control Structures
6 Chapter Functions.
Loops in C.
Govt. Polytechnic,Dhangar
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
A function with one argument
Introduction C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell.
CPS120: Introduction to Computer Science
C Programming Getting started Variables Basic C operators Conditionals
CprE 185: Intro to Problem Solving (using C)
2. Second Step for Learning C++ Programming • Data Type • Char • Float
In C Programming Language
1-6 Midterm Review.
Programming Languages and Paradigms
CprE 185: Intro to Problem Solving (using C)
DATA TYPES There are four basic data types associated with variables:
C Language B. DHIVYA 17PCA140 II MCA.
CSC215 Lecture Control Flow.
CprE 185: Intro to Problem Solving (using C)
INTRODUCTION TO C.
Scope Rules.
Presentation transcript:

Unit 3 Control Structure

Flow of Control Unless specified otherwise, the order of statement execution through a function is linear: one statement after another in sequence Some programming statements allow us to: decide whether or not to execute a particular statement execute a statement over and over, repetitively These decisions are based on Boolean expressions (or conditions) that evaluate to true or false The order of statement execution is called the flow of control

C Keywords auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while The words in bold print are used in control statements. They change the otherwise sequential execution of the assignment statements in a function block

Conditional Statements A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements The C conditional statements are the: if statement : Specifies which block of code is execute if-else statement: Check condition true or false if-else if statement : multiple condition at one time Nested if statement : if statement contain another if statement in either its block or else block or both block Switch statement

Logic of an if statement condition evaluated false statement true

The if Statement The if statement has the following syntax: The condition must be a boolean expression. It must evaluate to either true or false. if is a C reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.

To Print largest of two number using if Statement #include<Stdio.h> Main() { int a=10, b=15, max; max=b; if(a>b) { max=a; } printf(“ The largest between two number is =%d”, max); Output: The largest two number is= 15

The if-else Statement An else section can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

Logic of an if-else statement condition evaluated false statement2 statement1 true

To check number is even or odd. #include<stdio.h> main() { int num; if (num%2=0) printf(“Number %d is even”, num); } else printf(“Number %d is odd”, num);

The if-else if Statement To perform various actions based on multiple conditions at one time we can use if-else if statement. If neither of the condition evaluates to true, default statement will be executed. if ( condition ) { statement1; } else if ( condition ) statement2; }

Nested if Statements If statement contain another if statement in either its block or else block or both block. These are called nested if statements. if ( condition ) { statement1; else statement2; } else else statement2; }

To check greatest of three number. #include<stdio.h> main() { Float A,B,C; Printf(“Enter the three number”); Scanf(“%f%f%f”, &A,&B,&C); Printf(“Largest number is”); if (A>B) if (A>C) printf(“%f”, A); else printf(“%f”, C); } if (C>B) printf(“%F”, C); printf(“%f”, B);

The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches

The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

The switch Statement The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int,) or a char It cannot be a floating point value (float or double) You cannot perform relational checks with a switch statement

Flow of switch statement

The switch Statement The general syntax of a switch statement is: and case are reserved words switch ( expression ) { case value1 : statement-list1; break; case value2 : statement-list2; case value3 : statement-list3; case ... default: default-block; } If expression matches value2, control jumps to here

Switch Statement Example case values must be constants int month, daysInMonth, leapYear; … switch (month) { case 0: printf("January\n"); daysInMonth = 31; break; case 1: printf("February\n"); daysInMonth = leapYear ? 29 : 28; break; case 2: printf("March\n"); daysInMonth = 31; break; case 3: printf("April\n"); daysInMonth = 30; break; … } // switch break statement needed to jump over subsequent cases default case is optional (not shown)

Repetition in Programs In most software, the statements in the program may need to repeat for many times. e.g., calculate the value of n!. If n = 10000, it’s not well-designed to write the code as 1*2*3*…*10000. Loop is a control structure that repeats a group of steps in a program. Loop body stands for the repeated statements. There are three C loop control statements: while, for, and do-while.

The while Statement in C The syntax of while statement in C: initialization; while (loop repetition condition) { statement; } Loop repetition condition is the condition which controls the loop. The loop repetition condition is tested before loop body executed. The statement is repeated as long as the loop repetition condition is true. A loop is called an infinite loop if the loop repetition condition is always true.

An Example of a while Loop #include<stdio.h> Main() { int n=1,fact=1; while (n<=5) { fact=fact*n; n++; } printf(“Factorial of Number is :%d”, fact);

The for Statement in C The syntax of for statement in C: for (initialization expression; loop repetition condition; update expression) { statement; } The initialization expression set the initial value of the loop control variable. The loop repetition condition test the value of the loop control variable i.e. Boolean Expression. The update expression update increment/ decrement value. Body of loop is executed, till the repeat condition becomes false. e.g., for (int i = 0; i < 100; i++)

#include<stdio.h> Main() { int n=1,fact=1; for(n=1;n<=5;n++) { fact=fact*n; } printf(“Factorial of Number is :%d”, fact);

Nested For Loops Outer loop Inner loop Nested loops consist of an outer loop with one or more inner loops. Syntax for (initialization expression; loop repetition condition; update expression) { { (Statement); } } e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ … } The above loop will run for 100*50 iterations. Outer loop Inner loop

The do-while Statement in C The syntax of do-while statement in C: initialization; Do { statement } while (loop repetition condition); The statement is first executed. If the loop repetition condition is true, the statement is repeated. Otherwise, the loop is exited.

An Example of the do-while Loop #include<stdio.h> Main() { int n=1,fact=1; do { fact=fact*n; n++; } while (n<=5); printf(“Factorial of Number is :%d”, fact); }

Jump statement allow program to execute in a nonlinear fashion. Jump statements Jump statement allow program to execute in a nonlinear fashion. break statement continue statement goto Return

break statement Terminates innermost loop/switch From this statement, control is transferred to outside the loop/switch. Usage ■ Within loops : Generally used in conjunction with conditional statements ■ Within Switch Case statements : useful to break the switch statement

break Example #include<stdio.h> Main() { int a; for(a=0;a<100;a++) { printf(“\t %d”, a); if(a==10) { break; } }

continue statement The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place,. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control passes to the conditional tests. Syntax: continue;

continue Example void main( ) { for( int i=0; i<10; i++) { printf(“%d”, i); if(i%2==0) continue; } /*end of if*/ printf(“\n"); } /*end of for*/ }

goto statement A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same function. It is used to transferring the control to some other part of the program. Syntax : goto label; .. . label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.

The goto statement is of two types : Conditional goto Statement Unconditional goto Statement Conditional goto Statement : The Conditional goto is used to transfer control of the execution from one part of program to the other part in some conditional Statement. e.g. Main() { Int a,b; printf(“Enter the values of a and b”); Scanf(“%d %d”, &a, &b); if (a>b) { goto 1; } else { goto 2; } 1: printf((“Largest is %d”, a); 2: Printf(“Largest is %d”,b); }

Unconditional goto : it is used to transfer the control of the execution from one part of the program to the other part without checking any condition . e.g. #include<stdio.h> Main() { Start: Printf(“Hello”); goto Start; }

Return Statement The return statement is use to return from a function. It is categorized as a jump statement because it causes execution to return (jump back) to the point at which call to the function was made. A return may or may not have a value associated with it. A return with a value can be used only in a function with a non-void return type. So value associated with return becomes the return value of the function. A return without a value is used to return from a void function. Syntax: return expression;

Where expression is the value to return Where expression is the value to return. we can use as many return statements as we want within a function. but the function will stop executing as soon as it encounters the first return. A function declared as a void can not contain a return statement that specifies a values. E.g. #include<stdio.h> main() { int t=1; printf(“Before the return”); if(t==1) { return 0; } printf(“This will not execute”); Output : Before the return

C Functions Function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions. A function is known with various names like a method or a sub-routine or a procedure, etc.

Defining a Function The general form of a function definition in C programming language is as follows: return type function name( parameter list ) { body of the function } A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value of the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters: A parameter is like a placeholder Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; i.e. a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.

/* function returning the max between two numbers */ Example: Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two: /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }

Function Declarations A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list ); For the above defined function max(), following is the function declaration: int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so following is also valid declaration: int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file i.e. calling the function.

Calling a Function While creating a C function, you give a definition of what the function has to do. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name.

For example: #include <stdio.h> /* function declaration */ int max(int num1, int num2); int main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; }

/. function returning the max between two numbers /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } It kepts max() function along with main() function and compiled the source code. While running final executable, it would produce the following result: Max value is : 200

Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function: Function call by value Function call by reference

Function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming language uses call by value method to pass arguments.

Consider the function swap() definition as follows: /* function definition to swap the values */ void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put x into y */ return; } Now, let us call the function swap() by passing actual values as in the following example:

#include <stdio. h> /. function declaration #include <stdio.h> /* function declaration */ void swap(int x, int y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values */ swap(a, b);

printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; } Let us put above code in a single C file, compile and execute it, it will produce the following result: Before swap, value of a :100 Before swap, value of b :200

Function call by reference The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

/. function definition to swap the values. / void swap(int. x, int /* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put x into y */ return; } Let us call the function swap() by passing values by reference as in the following example which is in subsequent slide:

#include <stdio. h> /. function declaration. / void swap(int #include <stdio.h> /* function declaration */ void swap(int *x, int *y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values. * &a indicates pointer to a i.e. address of variable a and * &b indicates pointer to b i.e. address of variable b. */

swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; } Let us put above code in a single C file, compile and execute it, it will produce the following result: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100 Which shows that there is no change in the values though they had been changed inside the function.

C Scope Rules A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places where variables can be declared in C programming language: Inside a function or a block which is called local variables, Outside of all functions which is called global variables. In the definition of function parameters which is called formal parameters. Let us explain what are local and global variables and formal parameters.

Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Following is the example using local variables. Here all the variables a, b and c are local to main() function which is explain in subsequent slide .

#include <stdio. h> int main () { /. local variable declaration #include <stdio.h> int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; }

Global Variables Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables.

#include <stdio. h> /. global variable declaration #include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; }

A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example: #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces the following result: value of g = 10

Formal Parameters Function parameters, so called formal parameters, are treated as local variables within that function and they will take preference over the global variables. Following is an example: #include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0;

printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0; } /* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; When the above code is compiled and executed, it produces the following result: value of a in main() = 10 value of c in main() = 30 value of a in sum() = 10 value of b in sum() = 20

Initializing Local and Global Variables When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows: It is a good programming practice to initialize variables properly otherwise, your program may produce unexpected results because uninitialized variables will take some garbage value already available at its memory location Data Type Initial Default Value int Char ‘\0’ Float Double Pointer NULL

WAP to print sum of squares of first 20 even number by using (i) while (ii) do while (iii) for loop By using while loop: #include<stdio.h> Main() { int sum=0,i; while(i<=40) { if(i%2==0) { sum=sum+i*i; i++; } printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

By using for loop: #include<stdio By using for loop: #include<stdio.h> Main() { int sum=0,i; for(i=1;i<=40;i++) { if(i%2==0) { sum=sum+i*i; } printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

By using Do while loop: #include<stdio By using Do while loop: #include<stdio.h> Main() { int sum=0,i=1; Do { if(i%2==0) { sum=sum+i*i; i++; } while(i<=40); printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

Read an integer through the keyboard Read an integer through the keyboard. Sort odd and even numbers by using while loop. Write a program to add sum of odd and even number separately and display the results. #include<stdio.h> Main() { int odd=0,even=0,i=1,n; printf(“How Many Numbers are there :”); scanf(“%d”, &n); while(i<=n) { printf(“Enter the Number”); scanf(“%d”, &i); if(i%2==0) { even= even+i; } else odd= odd+i; }

printf(“The sum of Even Number is =%d”, even); printf(“The sum of odd Number is =%d”, odd); } Output : How many Numbers are there : 7 Enter the Number 1 Enter the Number 2 Enter the Number 3 Enter the Number 4 Enter the Number 5 Enter the Number 6 Enter the Number 7 The Sum of Even Numbers is =12 The Sum of Odd Numbers is =16

Q. Write a program to print the following series along with sum of first 20 terms of the series 12 -22+32-42+52-62+72- ………….. Using i) while ii) do while iii) for loop By Using For Loop #include>stdio.h> #include<math.h> Main() { int n, i, sum=0, sign=1; n=20; For(i=1;i<=20;i++) sum=sum+(sign)* pow(I,2); sign*=-1; /* Sign switches between +1` and -1 */ } printf(“Sum is =%d”, sum); Output: Sum is = -210

By Using While Loop #include<stdio. h> #include<math By Using While Loop #include<stdio.h> #include<math.h> Main() { int n, i=1, sum=0, sign=1; n=20; while (i<=20) sum=sum(sign)* pow(I,2); sign*=-1; i++; } printf(“Sum is =%d”, sum); Output: Sum is = -210

By Using Do While Loop #include>stdio. h> #include<math By Using Do While Loop #include>stdio.h> #include<math.h> Main() { int n, i=1, sum=0, sign=1; n=20; do sum=sum(sign)* pow(I,2); sign*=-1; i++; } while (i<=20); printf(“Sum is =%d”, sum); Output: Sum is = -210

WAP by do while loop to calculate the sum of odd no start from 1and less than 99. #include<stdio.h> Main() { int sum=0,i=1; do { if(i%2!=o) { sum=sum+i; i=i+2; } while(i<99); printf(“The sum of odd number is : %d”, sum); Output: The sum of odd Number is: 2401

Q. Find the output of following program: #include<stdio Q. Find the output of following program: #include<stdio.h> Main() { int c=1,s=0,n; n=6; For(;c<=n;c++) s+=c; } printf(“\n sum is %d”, s); Output: sum is 21