Introduction to Functions in C. Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department
|
|
- Suzanna Short
- 6 years ago
- Views:
Transcription
1 Introduction to Functions in C Dr. Ahmed Telba King Saud University College of Engineering Electrical Engineering Department
2 Function definition For example Pythagoras(x,y,z) double x,y,z; { double d; d = sqrt(x*x+y*y+z*z); printf("the distance to your point was %f\n",d); }
3 Outline Introduction to Functions Predefined Functions and Code Reuse User-defined void Functions without Arguments I. Function Prototypes II. Function Definitions III. Placement of Functions in a Program IV. Program Style 3
4
5
6
7
8
9
10
11 Function Declarations
12 Example
13 Example
14
15
16 Introduction to Functions Learning how to use operators, +, -, *, / and % to form simple arithmetic expressions. However, we are not yet able to write many other mathematical expressions we are used to. For example, we cannot yet represent any of the following expressions in C: C does not have operators for square root, absolute value, sine, log, etc. Instead, C provides program units called functions to carry out these and other mathematical operations. 16
17 Introduction to Functions A function can be thought of as a black box that takes one or more input arguments and produces a single output value. For example, the following shows how to use the sqrt function that is available in the standard math library: y = sqrt (x); If x is 16, the function computes the square root of 16. The result, 4, is then assigned to the variable y. The expression part of the assignment statement is called function call. Another example is: z = sqrt (w); If w = 9, z is assigned , which is
18 Example /* Performs three square root computations */ #include <stdio.h> /* definitions of printf, scanf */ #include <math.h> /* definition of sqrt */ int main(void) { double first, second, /* input - two data values */ first_sqrt, /* output - square root of first input */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum */ printf("enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("square root of the number is %.2f\n", first_sqrt); printf("enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("square root of the second number is %.2f\n", second_sqrt); } sum_sqrt = sqrt(first + second); printf("square root of the sum of the 2 numbers is %.2f\n",sum_sqrt); return (0); 18
19 Predefined Functions and Code Reuse The primary goal of software engineering is to write error-free code. Reusing code that has already been written & tested is one way to achieve this. --- Why reinvent the wheel? C promotes reuse by providing many predefined functions. e.g. Mathematical computations. Input/Output: e.g. printf, scanf 19
20 Predefined Functions and Code Reuse The next slide lists some commonly used mathematical functions (Table 3.6 in the book) Appendix B gives a more extensive lists of standard library functions. In order to use a function, you must use #include with the appropriate library. Example, to use function sqrt you must include math.h. If a functions is called with a numeric argument that is not of the argument type listed, the argument value is converted to the required type before it is used. Conversion of type int to type double cause no problems Conversion of type double to type int leads to the loss of any fractional part. Make sure you look at documentation for the function so you use it correctly. 20
21 Some Mathematical Library Functions Function Header File Purpose Arguments Result abs(x) <stdlib.h> Returns the absolute value of its integer argument x. sin(x),cos(x), tan(x) <math.h> Returns the sine, cosine, or tangent of angle x. log(x) <math.h> Returns the natural log of x. Log10(x) <math.h> Returns base 10 log of x int double (in radians) double (must be positive) Double (positive) int double double double pow(x, y) <math.h> Returns x y double, double double sqrt(x) <math.h> double (must be positive) x double 21
22 #include <iostream> using namespace std; int mult ( int x, int y ); int main() { int x; int y; } cout<<"please input two numbers to be multiplied: "; cin>> x >> y; cin.ignore(); cout<<"the product of your two numbers is "<< mult ( x, y ) <<"\n"; cin.get();
23 Example We can use C functions pow and sqrt to compute the roots of a quadratic equation in x of the form: If the discriminant (b 2 4ac) is greater than zero, the two roots are defined as: In C, these two roots are computed as: /* compute two roots, root_1 and root_2, for disc > 0.0 */ disc = pow(b, 2) - 4 * a * c; root_1 = (-b + sqrt(disc)) / (2 * a); root_2 = (-b - sqrt(disc)) / (2 * a); 23
24 Simple User-defined Functions An advantage of using predefined functions is that the programmer needs to be concerned only with what the function does but not how it does it. In complex software systems, this principle of separating what from the how is an important aspect of managing the complexity of programs. C provides a mechanism for the programmer to define his own functions with the same advantages as the C s library functions. We now study the simplest type of user-defined functions those that display one or more lines of output. These are useful for tasks such as displaying instructions to the user on how to use a program. 24
25 Example /* Performs three square root computations */ #include <stdio.h> /* definitions of printf, scanf */ #include <math.h> /* definition of sqrt */ void instruct (void); //displays user instruction int main(void) { /* Display instrctions */ instruct(); double first, second, /* input - two data values */ first_sqrt, /* output - square root of first input */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum */ printf("enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("square root of the number is %.2f\n", first_sqrt); // continue next slide 25
26 // continue from previous slide Example printf("enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("square root of the second number is %.2f\n", second_sqrt); sum_sqrt = sqrt(first + second); printf("square root of the sum of the 2 numbers is %.2f\n",sum_sqrt); return (0); } // end of main function /* displays user instructions */ void instruct(void) { printf("this program demostrates the use of the \n"); printf("math library function sqrt (square root). \n"); printf("you will be asked to enter two numbers -- \n"); printf("the program will display the square root of \n"); printf("each number and the square root of their sum. \n\n"); } 26
27 Function Prototypes Like other identifiers in C, a function must be declared before it can be used in a program. To do this, you can add a function prototype before main to tell the compiler what functions you are planning to use. A function prototype tells the C compiler: 1. The data type the function will return For example, the sqrt function returns a type of double. 2. The function name 3. Information about the arguments that the function expects. The sqrt function expects a double argument. So the function prototype for sqrt would be: double sqrt(double); 27
28 Function Prototypes : void Functions void instruct(void); is a void function Void function - does not return a value The function just does something without communicating anything back to its caller. If the arguments are void as well, it means the function doesn t take any arguments. Now, we can understand what our main function means: int main(void) This means that the function main takes no arguments, and returns an int 28
29 Function Definition The prototype tells the compiler what arguments the function takes and what it returns, but not what it does. We define our own functions just like we do the main function Function Header The same as the prototype, except it is not ended by the symbol ; Function Body A code block enclosed by {}, containing variable declarations and executable statements. In the function body, we define what actually the function does In this case, we call printf 5 times to display user instructions. Because it is a void function, we can omit the return statement. Control returns to main after the instructions are displayed. 29
30 Placement of Functions in a program In general, we will declare all of our function prototypes at the beginning (after #include or #define) This is followed by the main function After that, we define all of our functions. However, this is just a convention. As long as a function s prototype appears before it is used, it doesn t matter where in the file it is defined. The order we define them in does not have any impact on how they are executed 30
31 Execution Order of Functions Execution order of functions is determined by the order of execution of the function call statements. Because the prototypes for the function subprograms appear before the main function, the compiler processes the function prototypes before it translates the main function. The information in each prototype enables the compiler to correctly translate a call to that function. After compiling the main function, the compiler translates each function subprogram. At the end of a function, control always returns to the point where it was called. 31
32 Flow of Control Between the main Function and a Function Subprogram 32
33 Program Style Each function should begin with a comment that describes its purpose. If the function subprograms were more complex, we would include comments on each major algorithm step just as we do in function main. It is recommended that you put prototypes for all functions at the top, and then define them all after main. 33
34 #include <stdio.h> /* Program for Lesson 5_1 */ void function1(void); void function2(int n, double x); void main(void) { int m; double y ; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1( ); function2(m,y); } printf ("The value of m in main is still m=%d\n",m); void function1(void) { printf("function1 is a void function that does not receive\n\ \rvalues from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37; z=4.0*x-58.4; printf("function2 is a void function that does receive\n\ \rvalues from main. The values received from main are:\n\ \r\t n=%d \n\r\t x=%lf\n\n",n,x); printf("function2 creates three new variables, k, m and z\n\ \rthese variables have the values:\n\ \r\t l=%d \n\r\t m=%d \n\r\t z=%lf\n\n",k,m,z);
35 /* Program for Lesson 5_2*/ #include <stdio.h> unsigned long int fact(int m); int main(void) { int n; unsigned long int g; double one_over_nfactorial; printf("this program calculates 1/nfactorial.\n\ \renter a positive integer less than or equal to 12:\n "); scanf ("%d",&n); g=fact(n); one_over_nfactorial=1.0/g; printf("1/%d! = %e",n,one_over_nfactorial); return (0); } unsigned long int fact(int m) { int i; unsigned long int product; } product = 1; for (i=m; i>=1; i--) { product*=i; } return(product);
36 /* Program for Lesson 5_3 */ #include <stdio.h> int m = 12; int function1 (int a, int b, int c, int d); void main(void) { int n = 30; int e,f,g,h,i; e=1; f=2; g=3; h=4; printf ("\n\n In main (before the call to function1): \n\ \r m = %d\n\ \r n = %d\n\ \r e = %d\n\n",m,n,e ); i=function1(e,f,g,h); } printf ("After returning to main: \n"); printf ("n = %d \n\ \r m = %d \n\ \r e = %d \n\ \r i = %d", n, m,e,i); int function1 (int a, int b, int c, int d) { int n = 400;
37 printf ("In function1:\n\ \r n = %d\n\ \r m = %d initially\n\ \r a = %d initially \n",n,m,a); m = 999; } if (a>=1) { a+=b+m+n; printf ("m = %d after being modified\n\ \r a = %d after being modified\n\n",m,a) ; return (a); } else { c+=d+m+n; return (c); }
38 /* Program for Lesson 5_4 */ #include <stdio.h> void function1 (int a, int b, double r,double s, int *c, double *t); void main (void) { int i=5, j=6, k; double x=10.6, y=22.3, z; } printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n", i,j,x,y); function1 (i,j,x,y,&k,&z); printf (" k = %d \n\r z = %lf \n\n", k, z); void function1 (int a,int b,double r,double s,int *c,double *t) { *c = a+b; *t = r+s +(*c); } printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );
39 * Program for Lesson 5_4 */ #include <stdio.h> void function1 (int a, int b, double r,double s, int *c, double *t); void main (void) { int i=5, j=6, k; double x=10.6, y=22.3, z; } printf (" i = %d \n\r j = %d \n\r x = %lf \n\r y = %lf \n\n", i,j,x,y); function1 (i,j,x,y,&k,&z); printf (" k = %d \n\r z = %lf \n\n", k, z); void function1 (int a,int b,double r,double s,int *c,double *t) { *c = a+b; *t = r+s +(*c); } printf (" *c = %d \n\r *t = %lf \n\n", *c, *t );
40 #include<iostream.h> int sum(int, int); int sub(int,int; int mul(int,int); int dev(int,int); int main() { int a,b,result; char op; cout << "pleas enter the first number" << endl; cin >> a; cout << "pleas enter the second number" << endl; cin >> b; cout << "type + for summing and - for subtracting and * for multiplaying>> " << endl; cin >> op; switch(op) { case '+': result = sum(a,b); cout << result; break; case '-': result = sub(a,b); cout << result; break; case '*': result = mul(a,b); cout << result; break; }} int sum(int x,int y) { return x+y; } int sub(int x,int y) { return x-y; } int mul(int x,int y) { return x*y; }
Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer
Introduction to Computers II Lecture 4 Dr Ali Ziya Alkar Dr Mehmet Demirer 1 Contents: Utilizing the existing information Top-down design Start with the broadest statement of the problem Works down to
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Stephen Scott (Adapted from Christopher M. Bourke) 1 / 41 Fall 2009 Chapter 3 3.1 Building Programs from Existing Information
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 03 - Functions Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 cbourke@cse.unl.edu Chapter 3 3.1 Building
More informationChapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.
Chapter 3 Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus Lecture 03 - Introduction To Functions Christopher M. Bourke cbourke@cse.unl.edu 3.1 Building Programs from Existing
More informationC++ Programming Lecture 11 Functions Part I
C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs
More informationFunctions. Systems Programming Concepts
Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value
More informationLesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University
Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only
More informationObject Oriented Programming Using C++ Mathematics & Computing IET, Katunayake
Assigning Values // Example 2.3(Mathematical operations in C++) float a; cout > a; cout
More informationFunctions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction
Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that
More informationWeek 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.
Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific
More informationC Functions. 5.2 Program Modules in C
1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking
More information6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x
(Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)
More informationProgramming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1
300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard
More informationLecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch
Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10
More informationLESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long
LESSON 5 ARITHMETIC DATA PROCESSING The arithmetic data types are the fundamental data types of the C language. They are called "arithmetic" because operations such as addition and multiplication can be
More informationFunctions. A function is a subprogram that performs a specific task. Functions you know: cout << Hi ; cin >> number;
Function Topic 4 A function is a subprogram that performs a specific task. you know: cout > number; Pre-defined and User-defined Pre-defined Function Is a function that is already defined
More informationFunctions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR
1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries
More informationStructured Programming. Dr. Mohamed Khedr Lecture 4
Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Scientific Notation for floats 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10-4 = 0002.7 = 0.00027 2 Output Formatting
More informationFunction. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers
Functions 1 Function n A program segment that carries out some specific, well-defined task n Example A function to add two numbers A function to find the largest of n numbers n A function will carry out
More informationBil 104 Intiroduction To Scientific And Engineering Computing. Lecture 5. Playing with Data Modifiers and Math Functions Getting Controls
Readin from and Writint to Standart I/O BIL104E: Introduction to Scientific and Engineering Computing Lecture 5 Playing with Data Modifiers and Math Functions Getting Controls Pointers What Is a Pointer?
More informationC Program Structures
Review-1 Structure of C program Variable types and Naming Input and output Arithmetic operation 85-132 Introduction to C-Programming 9-1 C Program Structures #include void main (void) { } declaration
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationBSM540 Basics of C Language
BSM540 Basics of C Language Chapter 9: Functions I Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture Introduce the switch and goto statements Introduce the arrays in C
More informationINTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from
INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function
More information3.1. Chapter 3: The cin Object. Expressions and Interactivity
Chapter 3: Expressions and Interactivity 3.1 The cin Object Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3-1 The cin Object Standard input stream object, normally the keyboard,
More informationDr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)
Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly
More informationData Type Fall 2014 Jinkyu Jeong
Data Type Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1 Syntax Rules Recap. keywords break double if sizeof void case else int static... Identifiers not#me scanf 123th printf _id so_am_i gedd007 Constants
More informationC Functions. CS 2060 Week 4. Prof. Jonathan Ventura
CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference
More informationC Programs: Simple Statements and Expressions
.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following
More informationANSI C Programming Simple Programs
ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double
More informationMore Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4
More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4 Ziad Matni Dept. of Computer Science, UCSB Administrative CHANGED T.A. OFFICE/OPEN LAB HOURS! Thursday, 10 AM 12 PM
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationFunctions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single
Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module
More informationCSE202-Lec#4. CSE202 C++ Programming
CSE202-Lec#4 Functions and input/output streams @LPU CSE202 C++ Programming Outline Creating User Defined Functions Functions With Default Arguments Inline Functions @LPU CSE202 C++ Programming What is
More informationComputers in Engineering. Moving From Fortran to C Michael A. Hawker
Computers in Engineering COMP 208 Moving From Fortran to C Michael A. Hawker Remember our first Fortran program? PROGRAM hello IMPLICIT NONE!This is my first program WRITE (*,*) "Hello, World!" END PROGRAM
More informationCalling Prewritten Functions in C
Calling Prewritten Functions in C We've already called two prewritten functions that are found in the C library stdio.h: printf, scanf. The function specifications for these two are complicated (they allow
More informationCSE123. Program Design and Modular Programming Functions 1-1
CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.
More informationOperators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP
Operators and Expression Dr Muhamad Zaini Yunos JKBR, FKMP Arithmetic operators Unary operators Relational operators Logical operators Assignment operators Conditional operators Comma operators Operators
More informationChapter 5 C Functions
Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(
More informationOutline. Functions. Functions. Predefined Functions. Example. Example. Predefined functions User-defined functions Actual parameters Formal parameters
Outline Functions Predefined functions User-defined functions Actual parameters Formal parameters Value parameters Variable parameters Functions 1 Functions 2 Functions Predefined Functions In C++ there
More informationWARM UP LESSONS BARE BASICS
WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions
More informationAN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University
AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:
More informationC++ PROGRAMMING SKILLS Part 3 User-Defined Functions
C++ PROGRAMMING SKILLS Part 3 User-Defined Functions Introduction Function Definition Void function Global Vs Local variables Random Number Generator Recursion Function Overloading Sample Code 1 Functions
More informationProgramming. C++ Basics
Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationCSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU
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
More informationLecture 04 FUNCTIONS AND ARRAYS
Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions
More informationGE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004
GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004 Functions and Program Structure Today we will be learning about functions. You should already have an idea of their uses. Cout
More informationBIL 104E Introduction to Scientific and Engineering Computing. Lecture 4
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More information2. Numbers In, Numbers Out
COMP1917: Computing 1 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. COMP1917 15s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write down a proposed solution Break
More informationProgramming Language A
Programming Language A Takako Nemoto (JAIST) 22 October Takako Nemoto (JAIST) 22 October 1 / 28 From Homework 2 Homework 2 1 Write a program calculate something with at least two integer-valued inputs,
More informationFunctions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa
Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined
More informationECET 264 C Programming Language with Applications
ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10
More informationIntroduction to Programming
Introduction to Programming session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines
More informationComputer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)
CP Lect 5 slide 1 Monday 2 October 2017 Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) Cristina Alexandru Monday 2 October 2017 Last Lecture Arithmetic Quadratic equation
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More information2. Numbers In, Numbers Out
REGZ9280: Global Education Short Course - Engineering 2. Numbers In, Numbers Out Reading: Moffat, Chapter 2. REGZ9280 14s2 2. Numbers In, Numbers Out 1 The Art of Programming Think about the problem Write
More informationCOMP 208 Computers in Engineering
COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,
More informationProgramming and Data Structure
Programming and Data Structure Sujoy Ghose Sudeshna Sarkar Jayanta Mukhopadhyay Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Spring Semester 2012 Programming and Data
More informationIntroduction. What is function? Multiple functions form a larger program Modular programming
FUNCTION CSC128 Introduction What is function? Module/mini program/sub-program Each function/module/sub-program performs specific task May contains its own variables/statements Can be compiled/tested independently
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationOutline. Why do we write functions? Introduction to Functions. How do we write functions? Using Functions. Introduction to Functions March 21, 2006
Introduction to User-defined Functions Larry Caretto Computer Science 106 Computing in Engineering and Science March 21, 2006 Outline Why we use functions Writing and calling a function Header and body
More informationChapter 6 - Notes User-Defined Functions I
Chapter 6 - Notes User-Defined Functions I I. Standard (Predefined) Functions A. A sub-program that performs a special or specific task and is made available by pre-written libraries in header files. B.
More informationUsing Free Functions
Chapter 3 Using Free Functions 3rd Edition Computing Fundamentals with C++ Rick Mercer Franklin, Beedle & Associates Goals Evaluate some mathematical and trigonometric functions Use arguments in function
More informationFunctions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.
Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create
More informationFunction a block of statements grouped together, to perform some specific task
Function a block of statements grouped together, to perform some specific task Each program written in C / C++ includes at least one function with pre-defined name: main( ). In our previous programs, we
More informationStandard Library Functions Outline
Standard Library Functions Outline 1. Standard Library Functions Outline 2. Functions in Mathematics #1 3. Functions in Mathematics #2 4. Functions in Mathematics #3 5. Function Argument 6. Absolute Value
More informationA function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.
Chapter-12 FUNCTIONS Introduction A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called. Types of functions There are two types
More informationFunctions. Lecture 6 COP 3014 Spring February 11, 2018
Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its
More informationC++, How to Program. Spring 2016 CISC1600 Yanjun Li 1
Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide
More informationLearning to Program with Haiku
Learning to Program with Haiku Lesson 3 Written by DarkWyrm All material 2010 DarkWyrm So far we've been learning about programming basics, such as how to write a function and how to start looking for
More informationC++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 6: User-Defined Functions I In this chapter, you will: Objectives Learn about standard (predefined) functions and discover
More informationAssoc. Prof. Dr. Tansu FİLİK
Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming
More informationFunctions. Arash Rafiey. September 26, 2017
September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic
More informationET156 Introduction to C Programming
ET156 Introduction to C Programming g Unit 22 C Language Elements, Input/output functions, ARITHMETIC EXPRESSIONS AND LIBRARY FUNCTIONS Instructor : Stan Kong Email : skong@itt tech.edutech.edu General
More informationChapter 4 Functions By C.K. Liang
1 Chapter 4 Functions By C.K. Liang What you should learn? 2 To construct programs modularly from small pieces called functions Math functions in C standard library Create new functions Pass information
More informationExam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80
Exam 2 CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson Question Points Score 1 18 2 29 3 18 4 15 Total: 80 I understand that this exam is closed book and closed note and
More informationProgramming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.
Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results
More informationPreview from Notesale.co.uk Page 2 of 79
COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the
More informationCS16 Exam #1 7/17/ Minutes 100 Points total
CS16 Exam #1 7/17/2012 75 Minutes 100 Points total Name: 1. (10 pts) Write the definition of a C function that takes two integers `a` and `b` as input parameters. The function returns an integer holding
More informationC Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.
C Tutorial: Part 1 Dr. Charalampos C. Tsimenidis Newcastle University School of Electrical and Electronic Engineering September 2013 Why C? Small (32 keywords) Stable Existing code base Fast Low-level
More information4. C++ functions. 1. Library Function 2. User-defined Function
4. C++ functions In programming, function refers to a segment that group s code to perform a specific task. Depending on whether a function is predefined or created by programmer; there are two types of
More informationDownloaded from
Function: A function is a named unit of a group of statements that can be invoked from other parts of the program. The advantages of using functions are: Functions enable us to break a program down into
More informationFunction Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design
What is a Function? C Programming Lecture 8-1 : Function (Basic) A small program(subroutine) that performs a particular task Input : parameter / argument Perform what? : function body Output t : return
More informationLecture 9 - C Functions
ECET 264 C Programming Language with Applications Lecture 9 C Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 9- Prof. Paul I. Lin
More informationComputer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries
Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,
More informationConditional Expressions
Conditional Expressions Boolean Expressions: An expression that evaluates to either TRUE or FALSE. The most common types of boolean expressions are those that use relational operators. The general syntax
More informationOutput of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8
Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationCopyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Slide 7-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Type Conversation / Casting Name Constant - const, #define X When You Mix Apples and Oranges: Type Conversion Operations
More informationCS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.
REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout
More informationo Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement
Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise
More informationfrom Appendix B: Some C Essentials
from Appendix B: Some C Essentials tw rev. 22.9.16 If you use or reference these slides or the associated textbook, please cite the original authors work as follows: Toulson, R. & Wilmshurst, T. (2016).
More informationSummary of basic C++-commands
Summary of basic C++-commands K. Vollmayr-Lee, O. Ippisch April 13, 2010 1 Compiling To compile a C++-program, you can use either g++ or c++. g++ -o executable_filename.out sourcefilename.cc c++ -o executable_filename.out
More informationEngineering Problem Solving with C++, Etter/Ingber
Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input
More informationComputer Programming for Engineering Applica4ons. Intro to Programming 10/2/13 ECE 175. Limita4ons of Reference by Value. The Concept of Pointers
Computer Programming for Engineering Applica4ons ECE 175 Intro to Programming Limita4ons of Reference by Value Write a C func4on that does the following Argument: the radius of a circle r Output: circumference
More informationIntroduction to Scientific Programming with C++
Introduction to Scientific Programming with C++ Session 1: Control structure Martin Uhrin and Seto Balian UCL December 17-19th 2014 1 / 22 Table of Contents 1 Conditionals 2 Loops while loops do-while
More informationFundamentals of Programming & Procedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Eight: Math Functions, Linked Lists, and Binary Trees Name: First Name: Tutor:
More information