Lecture 3 Strings More control statements C functions.

Slides:



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

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Functions.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Lecture 5: Modular Programming (functions – part 1 BJ Furman 27FEB2012.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Fundamentals of C and C++ Programming Control Structures and Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Lecture 8: Choosing the Correct Loop. do … while Repetition Statement Similar to the while statement Condition for repetition only tested after the body.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
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.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions Outline 5.1Introduction 5.2Program Modules.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
KIC/Computer Programming & Problem Solving 1.  Introduction  Program Modules in C  Math Library Functions  Functions  Function Definitions  Function.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
 2000 Prentice Hall, Inc. All rights reserved. 5.2Program Modules in C Functions –Modules in C –Programs combine user-defined functions with library functions.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
1 UMBC CMSC 104, Section Fall 2002 Functions, Part 1 of 3 Topics Top-down Design The Function Concept Using Predefined Functions Programmer-Defined.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Programming Fundamentals Enumerations and Functions.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Dale Roberts CSCI N305 Functions Declarations Department of Computer and Information Science, School of Science, IUPUI.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 4 – C Program Control
Functions Course conducted by: Md.Raihan ul Masood
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Chapter 5 - Functions Outline 5.1 Introduction
Functions Declarations CSCI 230
Chapter 6 Methods: A Deeper Look
Chapter 6 - Functions Outline 5.1 Introduction
Presentation transcript:

Lecture 3 Strings More control statements C functions

Announcements

More control statements K&R: ch. 3

More control statements for loops –Much like while loops but more general and sometimes more convenient switch statements –Nice alternative to messy if-else sequences do-while loops –Slight variant on while loops goto statements –Typically to be avoided break and continue statements

Control statements, cont. These are all explained nicely with examples in ch. 3 of K&R Main points –These additional statements don't allow you to do anything that you couldn't have done with while and if –However, they do make it much cleaner and more concise to express certain logic. Often so much so that without them a solution may be too difficult to come up with.

For loops General syntax 1; expr2; expr3 ){ –for ( expr1; expr2; expr3 ){ statement1;. } This is exactly equivalent to: expr1; while (expr2) { statement1; expr3; }

For loops, cont. Expr1 –Called the initializer; evaluated once and only once before the loop executes for the first time. Expr2 –The termination condition; evaluated at the beginning of each iteration of the loop. If it evaluates to false, loop ends. Expr3 –Evaluted at the end of each iteration of the loop.

For loops, cont. Simple, most obvious, and most typical usage: for ( j = 0; j < n; j++ ) {…} (write out the equivalent while statement!) Infinite loop: for (; ; ) { … } /* any part may be ommited */ May also combine expressions: for (j=0, k=m; j < k; j++, k--){ … }

For loops, cont Arithmetic expressions –Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10 for ( j = x; j <= 4 * x * y; j += y / x ) is equivalent to for ( j = 2; j <= 80; j += 5 ) Notes about the for structure: –"Increment" may be negative (decrement) –If the loop continuation condition is initially false The body of the for structure is not performed Control proceeds with the next statement after the for structure –Control variable Often printed or used inside for body, but not necessary 1.Initialize variables 2.for repetition structure Program Output

Switch statements General syntax switch( expr ){ case const-expr: statements. default: statements }

Switch, cont. Note that cases must be constant expression, not variables! If a case is matched, switch falls through to the next statement. A break must be used to avoid evaluating subsequent cases. Just a cleaner way of to write a bunch of if-else statements.

Switch flow-chart true false case a case a action(s)break case b case b action(s)break false case z case z action(s)break true default action(s)

do / while Repetition Structure The do / while repetition structure –Similar to the while structure –Condition for repetition tested after the body of the loop is performed All actions are performed at least once –Format: do { statement; } while ( condition );

1/* Fig. 4.9: fig04_09.c 2 Using the do/while repetition structure */ 3#include 4 5int main() 6{6{ 7 int counter = 1; 8 9 do { 10 printf( "%d ", counter ); 11 } while ( ++counter <= 10 ); return 0; 14} Do-while example

Do-while and goto No great advantages to using them. If you're curious, very well explained in K&R 3.6 & 3.8.

C functions Breaking a program into smaller, reusable pieces

Functions –Enable you to break a program into smaller pieces (modularization). –Each function performs a specified task. It may receive input data and return output data. –Main program is mainly a wiring together of function calls. –All variables declared inside functions are local variables Known only in function defined –Parameters Communicate information between functions

Functions, cont. 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

Start with an example Imagine that many different times in a C program you have to find the maximum of two numbers: if ( a > b ){ bigger = a; } else{ bigger = b; } While this may not seem like a lot of code, it can get very ugly and make the program difficult to follow. It would be much nicer to say something like: bigger = imax(a,b);

C functions, cont. The purpose of a C function is to allow the programmer to accomplish exactly this; that is, to move snippets of code outside of the main program and call them by an intuitive name. These functions can then be reused in any program where they are needed.

Example: Max function int imax( int, int ) ; /* function "prototype" - listed before main*/ int main(int argc, char* argv[]){ int a, b, c; a = atoi(argv[1]); b = atoi(argv[2]); c = imax(a,b); printf("%s: %d, "The max value is: ", c); } /* our first non-main function */ int imax( int val1, int val2 ){ if (val1 > val2){ return(val1); } else{ return(val2); }

Dissecting the max function Our programming world will extend now, from main() { … } within a single file, to: #include function prototypes … main(…) { … } func1(…) { …} func2(…) { …}. all within a single file!

Components of a function Each function is composed of three parts: –Name Like variables it's up to you. Should choose clear, intuitive name –Return type Data type that the function will return to user. For imax function this is an int. –Parameter list List of datatypes that will be passed to the function. For imax functions there are two: int and int. –Author of function makes all of these decisions!

Components, cont. Each of the three mentioned on the previous slide parts goes in a specific place: return-type function_name( param1, param2, …) { } Where param1, etc. are composed of two parts: param1_type param1_name Example: int imax( int x, int y) Return type: int Name : imax Parameter list: an integer x and an integer y

Body of a function After the function header comes the body, denoted by braces { … } The body is always organized as variable declarations and then executable statements. Finally, the function should always end with a return statement, specifying the variable that is to be passed back to the caller. –Example: return(x); /* end the function and hand back the value of the variable x to the calling function */

Calling a function Function calls –The word"call" refers to the process of invoking functions. When you call a function: 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

Calling a function, cont. The formal process of calling a function is as follows: return_value = func_name( arg1, arg2, …); return_value: optional variable to store output func_name : name of the function you wish to invoke. arg1, … : Data that you are passing to the function. Known as an argument list. Must match function parameter list in number and type.

Example: calling a function Using our previous imax example: int maxval; /* declare an integer to store the result */ int a = 8; b = 10; /* create some data */ maxval = imax(a,b); /* function call */ Example says "call the function imax, passing to it the variables a and b, and store the result in the integer maxval."

More examples Write a function which takes no input and gives no output; it's only effect is to print an error message to the screen and abort. Write a function called power with the following interface: –double power(double x, int n) which evaluates x to the nth power. Write a function which returns the sum of an arbitrary- sized 1d array. Write a function that sorts an array Write a function to find the max value of an array

Writing functions For each problem on the previous slide, we should first set up the function before writing any code: –What is the input type and number? –What is the output (return val)? –What is a good name for the function? Once this is done, we can address go ahead and write the details of the function.

Data visibility Extremely important! –Function can only "see" three types of variables: Those declared locally within the function Those passed into the function through it arg list "Global variables" defined outside of any function –We have not yet used global variables –Any variables defined in other functions (even main) that are not passed into another function are NOT visible to that function, and it can not see or manipulate their values! This behavior is crucial to achieving code modularity.

Function nuances Just a few more things to know about functions: –Prototype –Dummy argument names –Void argument lists and return types –Calling a function without accepting return value –"pass by value" vs. "pass by reference" Each of these is described in the subsequent slides

Prototyping Though not always strictly necessary, I will require that we template all funtions. Templating means the following: –For each non-main function in your source file, you should include function headers just before main(). –A "header" is just the return_type, name, and param list of the function, ie: int imax(int a, int b) Note that "dummy arguments" a and b are optional here Int imax(int, int ) is ok Templating helps the compiler know what to expect when it encouters a function call for the first time.

Dummy arguments When we setup a function the param names are often referred to as "dummy arguments". For example, for imax: –int imax(int a, int b) –The variables a and b are the dummy arguments. –You can choose to name these anything regardless of the specific names passed to the function at calling time. –Whatever you choose to name them, that will be their name inside the function.

Void arguments A function may have zero or one return values, and zero or more paramters. If you create a function with zero return values, you should use void: –void printerr( int errorcode ); Likewise for zero parameters: –void printerr(void) Use void is optional, but it is a good practice since the compiler it will cause the compiler to do some extra checking.

Calling functions For a function that does not return void, you may still choose to discard the return argument by simply calling the function with no " = ": –imax(a,b) is legal, though not obviously useful. –c = imax(a,b) is more typical and useful