Introduction to Programming. Lecture 6: Functions & Program Structure

Similar documents
Introduction to Programming. Lecture 2: Introduction to C

CSI33 Data Structures

Introduction to Computing Lecture 09: Functions (Part II)

CSI33 Data Structures

Chapter 7 Functions. Now consider a more advanced example:

BITG 1113: Function (Part 2) LECTURE 5

Technical Questions. Q 1) What are the key features in C programming language?

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Introduction to Computer Science Midterm 3 Fall, Points

CSE 230 Intermediate Programming in C and C++ Functions

Scope and Parameter Passing

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

M.CS201 Programming language

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

A Fast Review of C Essentials Part II

WARM UP LESSONS BARE BASICS

Lecture 12 Modular Programming with Functions

User Defined Functions

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Lecture 23: Pointer Arithmetic

Scope and Parameter Passing

Chapter 4 Computer Science with C++ Name: Review Worksheet A Mr. Ferwerda

Fundamentals of Programming Session 12

CS2255 HOMEWORK #1 Fall 2012

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

DELHI PUBLIC SCHOOL TAPI

C and C++ I. Spring 2014 Carola Wenk

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Visual Programming. Lecture 3: Loops, Arrays. Mahmoud El-Gayyar

ENERGY 211 / CME 211. Functions

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

1 Unit 8 'for' Loops

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

CS240: Programming in C

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Principles of Computer Science

AN OVERVIEW OF C++ 1

CS110: PROGRAMMING LANGUAGE I

Lecture 3: C Programm

Introduction to Programming. Structures

C++ Support Classes (Data and Variables)

CS111: PROGRAMMING LANGUAGE II

C Functions. Object created and destroyed within its block auto: default for local variables

CS349/SE382 A1 C Programming Tutorial

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Visual Programming. Lecture 2: More types, Methods, Conditionals

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

This is CS50. Harvard University Fall Quiz 0 Answer Key

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

M.EC201 Programming language

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

LECTURE 5 Control Structures Part 2

Scope: Global and Local. Concept of Scope of Variable

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

UEE1302 (1102) F10: Introduction to Computers and Programming

cast.c /* Program illustrates the use of a cast to coerce a function argument to be of the correct form. */

AMCAT Automata Coding Sample Questions And Answers

ARRAYS(II Unit Part II)

Assignment #3 Answers

CS113: Lecture 4. Topics: Functions. Function Activation Records

For example, let s say we define an array of char of size six:

LECTURE 06 FUNCTIONS

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Fundamentals of Programming

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Understanding main() function Input/Output Streams

Add Subtract Multiply Divide

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

Name SECTION: 12:45 2:20. True or False (12 Points)

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING


C Programming Language

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Exam 3 Chapters 7 & 9

Functions. (transfer of parameters, returned values, recursion, function pointers).

Programming in C++: Assignment Week 6

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Informatica e Sistemi in Tempo Reale

Homework #3 CS2255 Fall 2012

CS240: Programming in C

Lecture 15a Persistent Memory & Shared Pointers

Introduction to C Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Short Notes of CS201

Variables and Operators 2/20/01 Lecture #

Object Oriented Software Design II

Q1 (15) Q2 (15) Q3 (15) Q4 (15) Total (60)

Chapter 6: Functions

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Transcription:

Introduction to Programming Lecture 6: Functions & Program Structure Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg

Arrays Review of Chapter 5 Initialization Multi-dimensional arrays More Operators Assignment operators Increment and decrement operators Order of evaluation Mahmoud El-Gayyar / Advanced Programming 2

Functions Basics Outline Function Prototypes Void (Non Value-Returning) Functions Variables Visibility and Lifetime Default Initialization Examples Mahmoud El-Gayyar / Advanced Programming 3

Functions Basics Outline Function Prototypes Void (Non Value-Returning) Functions Variables Visibility and Lifetime Default Initialization Examples Mahmoud El-Gayyar / Advanced Programming 4

What is a Function? Inputs Function Outputs Mahmoud El-Gayyar / Advanced Programming 5

What is a Function? Code within a function should has these properties: It performs some well-defined task (Useful to the program) It might be useful to other programs as well The rest of the program doesn't have to know the details of how the function is implemented Avoid to repeat code in the program (simpler code) Can be re-written (improved) while the rest of the program is not modified. Mahmoud El-Gayyar / Advanced Programming 6

A function consists of: Function Basics Name Parameters (inputs) Body (set of instructions: sequential, loop, conditional) Return type (the type of its output) Example: Multiply an int by two function, int multbytwo(int x){ int retval; retval = x * 2; return retval; Mahmoud El-Gayyar / Advanced Programming 7

Function Basics The previous function can be written in a simplified format: (return can be used to return an expression) int multbytwo(int x){ return x * 2; But how can we call our defined function?! For this we will see a full program using the mltbytwo function. Mahmoud El-Gayyar / Advanced Programming 8

#include <stdio.h> Functions: Full Example int multbytwo(int); void main(){ int i, j; i = 3; j = multbytwo(i); printf("%d\n", j); //function prototype //function call /*----------Function multbytwo------------*/ int multbytwo(int x){ return x * 2; Mahmoud El-Gayyar / Advanced Programming 9

prototypes help to Function Prototypes ensure that the compiler can generate correct code for calling the functions allowing the compiler to catch certain mistakes you might make however, prototypes are optional. (Define functions before main) Actually header (.h) files contains only functions prototypes while code is available in dynamic libraries (.dll files) Mahmoud El-Gayyar / Advanced Programming 10

Functions Basics Outline Function Prototypes Void (Non Value-Returning) Functions Variables Visibility and Lifetime Default Initialization Examples Mahmoud El-Gayyar / Advanced Programming 11

Void functions are created and used just like value- Example: Write a function to print Hello for n times How to call?! Void Functions returning functions except they do not return a value after the function executes. on the screen. void printhello(int num){ for(int i=0;i<num;i++) printf( Hello\n ); Mahmoud El-Gayyar / Advanced Programming 12

Parameters Passing: arrays When passing an array to a function, we only need to specify the array name The following example is invalid void f(int x[20]){ void main(){ int y[20]; f(y[0]); //invalid, type mismatch

Parameters Passing: arrays The size of array is optional. void f(int a[]) if the content of a[i] is modified in the function, the modification will persist even after the function returns (Call by reference) void f(int a[3]){ cout << a[0] <<endl; //1 is printed a[0]=10; void main (void) { int a[3]={1,2,5; //an array with 3 elements f(a); //calling f() with array a cout << a[0] <<endl; //10 is printed Only need to input the array name!

Parameters Passing: arrays Write a C function to count n numbers from an array?

Functions Basics Outline Function Prototypes Void (Non Value-Returning) Functions Variables Visibility and Lifetime Default Initialization Examples Mahmoud El-Gayyar / Advanced Programming 13

The visibility of a variable determines how much of the A variable declared within a block ( braces { ) are called local variables Variable Visibility rest of the program can access that variable. Visible only within the block Function blocks for/if/switch blocks a variable declared outside of any function is a global variable, and it is potentially visible anywhere within the program. Mahmoud El-Gayyar / Advanced Programming 14

Variable Life Time Automatic duration: start at the beginning of the block and they (and their values) disappear at the end of the block (e.g. local variables). Static duration: they last, and the values stored in them persist (for sure can be changed), for as long as the program does. (e.g. global variables) static keyword can be used to switch the local variable duration into a static one. Mahmoud El-Gayyar / Advanced Programming 15

Example: Variable Life Time void staticexample( ); int z=2; void main(){ cout<<z++<<endl; staticexample(); staticexample(); staticexample(); 2 0 0 3 0 1 4 0 2 5 void staticexample( ){ int x=0; static int y=0; cout<< x++ << y++<<endl; cout<<z++<<endl; Mahmoud El-Gayyar / Advanced Programming 16

Variable Initialization If you do not explicitly initialize them, automatic- duration variables (that is, local, non-static ones) are not guaranteed to have any particular initial value (garbage) Static-duration variables (global and static local), on the other hand, are guaranteed to be initialized to 0 (zero) if you do not use an explicit initializer in the definition. Mahmoud El-Gayyar / Advanced Programming 17

int globalvar = 1; Example 1 int anotherglobalvar; f(){ int localvar; int localvar2 = 2; static int persistentvar; Mahmoud El-Gayyar / Advanced Programming 18

Example 2 Write a function to compute the factorial of a number, and use it to print the factorials of the numbers 1-7. int fact (int n ); int main(){ for(int i=1; i<=7 ; i++) printf("factorial of %d equals %d \n", i, fact(i)); return 0; int fact (int n ){ int factorial=1; for(int i=n; i>1 ; i--) factorial=factorial*i; return factorial; Mahmoud El-Gayyar / Advanced Programming 19

How to write functions Don t forget your prototype Summary Difference between local and global variables Mahmoud El-Gayyar / Advanced Programming 20