CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Similar documents
CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

Chapter 3 Structured Program Development in C Part II

Chapter 3 Structured Program Development

Structured Program Development in C

Structured Program Development

Functions. Systems Programming Concepts

Fundamentals of Programming Session 7

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

C Functions. 5.2 Program Modules in C

C Programming for Engineers Functions

Lecture 04 FUNCTIONS AND ARRAYS

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Lecture 04 FUNCTIONS AND ARRAYS

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

CSE123. Program Design and Modular Programming Functions 1-1

Programming for Engineers Iteration

CS110D: PROGRAMMING LANGUAGE I

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 3. Section 3.10 Type of Expressions and Automatic Conversion. CS 50 Hathairat Rattanasook

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

1.3b Type Conversion

Programming for Engineers Functions

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

A Look Back at Arithmetic Operators: the Increment and Decrement

C: How to Program. Week /Mar/05

Operators and Expressions:

Lecture 9 - C Functions

C Programming for Engineers Structured Program

Chapter 2 - Introduction to C Programming

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Fundamentals of Programming. Lecture 6: Structured Development (part one)

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Introduction to Programming

Fundamental of Programming (C)

Chapter 3 - Functions

Control Statements. Musa M. Ameen Computer Engineering Dept.

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

3. Types of Algorithmic and Program Instructions

Functions and Recursion

BRANCHING if-else statements

Functions. Arash Rafiey. September 26, 2017

Decision Making -Branching. Class Incharge: S. Sasirekha

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Data Types and Variables in C language

Computers Programming Course 6. Iulian Năstac

Chapter 2 - Control Structures

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Introduction to C Programming

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

Visual C# Instructor s Manual Table of Contents

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Variables and Operators 2/20/01 Lecture #

Data Types. Data Types. Integer Types. Signed Integers

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Chapter 7 Functions. Now consider a more advanced example:

Introduction to C. Systems Programming Concepts

Chapter 3 Structure of a C Program

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Unit 7. Functions. Need of User Defined Functions

Computer System and programming in C

C++ Programming Lecture 11 Functions Part I

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Introduction to C Final Review Chapters 1-6 & 13

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

1 EEE1008 C Programming

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Programming in C++ 6. Floating point data types

ANSI C Programming Simple Programs

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Fundamentals of Programming

Structured Programming. Dr. Mohamed Khedr Lecture 9

Full file at

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

C Functions Pearson Education, Inc. All rights reserved.

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Lab 2: Structured Program Development in C

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

CMSC 104 -Lecture 9 John Y. Park, adapted by C Grasso

Transcription:

CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Outline Designing structured programs in C: Counter-controlled repetition Sentinel-controlled repetition Top down design and stepwise refinement Type conversion Functions(prototype and definition)

Example Counter Controlled Sentinel Controlled Do TEN push ups imposes a count condition

Repetitions The while loop repeats untill the condition is true. The condition to stop the repeated loop depends upon the output required. Condition True Repeated_Actions False

Formulating Algorithms (Counter-Controlled Repetition) Counter-controlled repetition Loop repeated until counter reaches a certain value. Counter is a variable used to specify the number of times a set of statements should execute. Definite repetition: number of repetitions is known Example (class-averaging problem) A class of ten students took a quiz. The marks (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz

Class-averaging Problem Pseudocode: 1. Set total to zero 2. Set grade counter to one 3.while grade counter is less than or equal to ten a. Input the next grade b. Add the grade into the total c. Add one to the grade counter 4. Set the class average to the total divided by ten 5. Print the class average

#include <stdio.h> int main() { int counter; //number of grade to be entered next int grade, total, average; total = 0; // initialize total counter = 1; // initialize loop counter while ( counter <= 10 ) { // loop 10 times printf( "%s", "Enter grade: "); scanf( "%d", &grade ); total = total + grade; counter = counter + 1; // increment counter } // end while average = total / 10; printf( "Class average is %d\n", average ); }

Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81

Formulating Algorithms with Top- Down, Stepwise Refinement Reconsider class-averaging problem: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. Unknown number of students. How will the program know when to end? Use sentinel value Also called signal value, dummy value, or flag value Indicates end of data entry. Loop ends when user inputs the sentinel value Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case)

Formulating Algorithms with Top- Down, Stepwise Refinement Top-down, stepwise refinement Begin with a pseudocode representation of the top: Determine the class average for the quiz Divide top into smaller tasks and list them in order: Initialize variables Input, sum and count the quiz grades Calculate and print the class average Many programs have three phases: Initialization: initializes the program variables Processing: inputs data values and adjusts program variables accordingly Termination: calculates and prints the final results

Formulating Algorithms with Top- Down, Stepwise Refinement Refine the initialization phase from Initialize variables to: Initialize total to zero Initialize counter to zero Refine Input, sum and count the quiz grades to Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel)

Formulating Algorithms with Top- Down, Stepwise Refinement Refine Calculate and print the class average to If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print No grades were entered

Refined Pseudocode for Classaveraging Problem Pseudocode: 1. Initialize total to zero 2. Initialize counter to zero 3. Input the first grade 4. While the user has not as yet entered the sentinel a. Add this grade into the running total b. Add one to the grade counter c. Input the next grade(possibly the sentinel) 5. If the counter is not equal to zero a. Set the average to the total divided by the counter b. Print the average Else a. Print No grades were entered

#include <stdio.h> int main() { int counter, grade, total; float average; total = 0; counter = 0; printf("%s", "Enter grade, -1 to end:"); scanf("%d", &grade); while ( grade!= -1 ) { //Sentinel value = -1 total = total + grade; counter = counter + 1; printf( "%s", "Enter grade, -1 to end: " ); scanf("%d", &grade); } //end while if (counter!= 0) { average = (float) total/counter; //type conversion printf("class average is %.2f\n", average); } //end if else { puts("no grades were entered"); } //end else }

Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50 OR Enter grade, -1 to end: -1 No grades were entered

Type Conversion C evaluates arithmetic expressions only in which the data types of the operands are identical. To ensure that operands are of same type the compiler performs type conversion. Converting between types can be : Implicitly (automatically) Explicitly (forced)

Implicit Conversion If two operands are of different data types the compiler performs an operation called implicit conversion on selected operands. Example: in an expression containing the data types int and float, int operand is converted to float. float average, total; int counter; average = total/counter; The copy of counter is made and converted to float, the calculation is performed and the result of floating-point division is assigned to average.

Order of converting type implicitly long double double float unsigned long int long int signed int int char

Explicit Conversion Type is converted using unary type cast operator. Which temporary converts the operands. Example: in an expression containing the data types int and float, int operand is converted to float. float average, total; int counter; average = total/(float)counter; The temporary floating-point copy of counter is created. The value stored in counter is still integer. calculation is performed and the result of floating-point division is assigned to average.

Cast operator is unary operator i.e. it takes only one operand. It is formed by placing parentheses around the type name with operand. Syntax (type) operand;

Divide and Conquer Best way to solve a problem is by dividing the problem and solving it. Divide and conquer Construct a program from smaller pieces or components These smaller pieces are called modules Each module more manageable than the original program

Program Modules in C Functions Modules in C are called functions. Programs combine user-defined functions with library functions C standard library has a wide variety of functions for performing common mathematical calculations, string manipulations, character manipulations, input/output and many more. C standard library makes your job easier. Functions like printf(), scanf(), pow() are standard library functions. We can also write functions to define some specific task in a program and these functions are called user-defined functions.

Functions Functions Modularize a program All variables defined inside functions are local variables Known only in function defined. Parameters Functions have list of parameters. Communicate information between functions. Are also Local variables to that function.

Benefits of functions Divide and conquer Manageable program development Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions) Avoid code repetition

Function Call Function calls Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results Function call analogy: Boss asks worker to complete task Worker gets information, does task, returns result Information hiding: boss does not know details

Program Modules in C Hierarchical boss function/worker function relationship. main worker1 worker2 worker3 worker4 worker5

Function Definitions Function definition format return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result (default int) void indicates that the function returns nothing Parameter-list: comma separated list, declares parameters A type must be listed explicitly for each parameter unless, the parameter is of type int

Function Definitions Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } Definitions and statements: function body (block) Variables can be defined inside blocks (can be nested) Functions can not be defined inside other functions Returning control If nothing returned return; or, until reaches right brace at the end of function. If something returned return expression;

#include <stdio.h> int square(int y); // function prototype int main() { int x; //counter for ( x = 1; x <= 10; ++x) { printf( "%d ", square(x)); //function call } //end for puts( ); } //end main int square( int y ) // function definition { return y * y; //returns the square of y as an int } 1 4 9 16 25 36 49 64 81 100

Function Prototypes Function prototype Function name Parameters what the function takes in Return type data type function returns (default int) Used to validate functions Prototype only needed if function definition comes after use in program The function with the prototype int square( int y); Takes in 1 int data. Returns an int Promotion rules and conversions Converting to lower types can lead to errors

Function Prototypes The argument values that do not correspond to the parameter types in the function prototype are converted to the proper type before function is called. This is done according to promotion hierarchy of data types in type conversion. The types lower in the table is converted to types higher in the table. Data types printf conversion specifications long double %Lf %Lf double %f %lf float %f %f unsigned long int %lu %lu long int %ld %ld unsigned int %u %u int %d %d short %hd %hd char %c %c Promotion hierarchy for data types. scanf conversion specifications

Next Class: Math Library Function cse101@lpu.co.in