Functions. (transfer of parameters, returned values, recursion, function pointers).
|
|
- Daniela Cannon
- 5 years ago
- Views:
Transcription
1 Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value to the calling program. Every C/C++ program has at least one function, main(). When your program starts, main() is called automatically. main() might call other functions, some of which might call still others. A function definition consists of two aspects: prototype and proper definition. The prototype specifies how it may be used. The function prototype is a statement, which means it ends with a semicolon. It consists of the function's return-type, name, and parameter list. Function prototype syntax is: return_type function_name ( [type [parametername]]...); Entities of prototype: - function_name - this is simply a unique identifier. - parameter list - this is a set of zero or more typed identifiers used for passing values to and from the function. The parameter list is a list of all parameters and their types, separated by commas. - return_type - this specifies the type of value the function returns. A function which returns nothing should have the return type void. For example, Figure. illustrates the parts of the function prototype. This prototype declares a function named area()which returns a long and that has two parameters, both integers. The prototype long area(int, int); Figure. Function prototype. is perfectly legal, but adding parameter names makes your prototype clearer. The same function with named parameters might be long area(int length, int width); The proper definition of a function consists of the function header and its body. The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. The body of the function contains the computational steps (statements) that comprise the function. The statements are enclosed in braces. Function definition syntax is: return_type function_name ( [type parametername]...) statements; If the function returns a value, it should end with a return statement, although return
2 statements can legally appear anywhere in the body of the function. Every function has a return-type. If one is not explicitly designated, the return type will be int. Be sure to give every function an explicit return-type. If a function does not return a value, its type will be void. Function definition is illustrated In Figure. Figure. Function definition. Using a function involves calling it. A function call consists of the function name followed by the call operator parentheses (), inside which zero or more comma-separated arguments appear. The number of arguments should match the number of function parameters. Each argument is an expression whose type should match the type of the corresponding parameter in the function prototype. An example for the function area call is: area (, 0); When a function call is executed, the arguments are first evaluated and their resulting values are assigned to the corresponding parameters. The function body is then executed. Execution begins with the first statement after the opening brace (). Finally, the function returned value (if any) is passed to the caller. Listing. shows the definition of a simple function which calculates the area of a rectangle. Listing. A simple function. 0 long area( int length, int width); // function prototype int main(void) int len, wid; long Area; printf("input the rectangle length: "); scanf("%d", &len); printf( "Input the rectangle width: "); scanf("%d", &wid); Area = area(len, wid); printf("area = %ld", Area); return 0; // function area definition long area( int length, int width) long Area; Area = length * width; return (Area); // call of function area // header of function area
3 Note: Note that the syntax for parameters is similar to the syntax for defining variables: type identifier followed by the parameter name. However, it is not possible to follow a type identifier with multiple comma-separated parameters: long area (int length, width) // Wrong!. Parameters and Arguments There are three ways to pass data from one function to another: - by value - by address - by reference Passing by value is sometimes called passing by copy. When you pass an argument from one function to another, the argument's value is passed to the receiving function, but the variable itself isn't passed. The value parameter receives a copy of the value of the argument passed to it. As a result, if the function makes any changes to the parameter, this will not affect the argument. For example, inlisting the two parameters are value (copy) parameters. When the function is called and lenis passed to length, lengthis a new variable, local to the function, which copies the value of len. In the same way, width receives a copy of the value of wid. The second way of passing data to a function is passing by address. Parameters used in this case are pointers that hold addresses of arguments. When C++ passes a variable by address, in effect it passes the variable itself, which means that the receiving function can change the calling function's variable. When the calling function regains control, any variable just passed by address might be changed if the called function changed the argument. The third way to pass data to a function is passing by reference. When you pass data by reference, if the called function changes the data, C++ applies those same changes to the calling function's data. In function we use the calling function's variable under a new name (an alias).the end result of passing by reference is identical to that of passing by address. There is one exception, the syntax when you passing variables (non arrays) by reference: if you pass nonarrays by address you must precede the passed arguments with ampersands and also precede all parameters in the called function with asterisks. When passing variables by reference, you only have to precede the receiving parameters with ampersands. Here are three examples of functions using different options to pass values: - Passing by value: void func( int x ) // function passing by value printf("%d", x ); // parameter value is printed The call of function func is like: int a=; func(a); - Passing by address: // x copies the value of variable a void func( int * x ) // function passing by address printf("%d", *x ); // parameter value is obtained by // indirection The call of function func is like: int a=;
4 func( &a); - Passing by reference: void func( int &x ) // you pass the address of variable a // function passing by reference printf("%d", x ); // the value of parameter is obtained // directly, without indirection The call of function func is like: int a=; func( a); // you pass the variable a To observe the differences, consider Listing. It defines three functions which try to reverse values of two variables. Listing. Passing values to a function 0 0 void swap (int x, int y) // pass-by-value printf("\n == Function swap ==\n" ); printf("initial values: x=%d, y=%d \n ", x, y ); int temp = x; x = y; y = temp; printf("final values: x=%d y= %d \n ", x, y); void swap (int *x, int *y) // pass-by-address (pointers) printf("\n == Function swap ==\n" ); printf("initial values: *x=%d, *y=%d\n", *x, *y ); int temp = *x; *x = *y; *y = temp; printf("final values: *x=%d, *y=%d\n",*x, *y ); void swap (int &x, int &y) // pass-by-reference printf("\n == Function swap ==\n"); printf("initial values: x=%d, y=%d \n", x, y ); int temp = x; x = y; y = temp; printf("final values: x=%d, y=%d \n", x, y ); void main(void) int a, b; printf("a= "); scanf("%d", &a); printf("b= "); scanf(" %d ", &b); swap( a, b); printf( a= %d, b=%d\n, a, b); swap( &a, &b); printf( a= %d, b=%d, a, b ); swap( a, b); printf( a= %d, b=%d, a, b );
5 Remarks: swap swaps x and y, that has no effect on the arguments passed to the function, because swap receives a copy of the arguments. The change of copy does not affect the original. swap uses pointer parameters. By dereferencing the pointers, swap gets to the original values and swaps them. The call syntax of swap demands passing the addresses of variables a and b (see line ). swap uses reference parameters. The parameters become aliases of the arguments passed to the function and swap them. swap has the added advantage that its call syntax is the same as swap and involves no addressing or dereferencing.. Passing Arrays to Functions There is a significant difference between an array variable and a normal variable: an array variable is really a pointer in disguise. So when you pass an array as a parameter, you are really passing its address. This means that when you pass an array, you are effectively passing the contents of the array by address. Therefore, when you pass an array, the contents of the array can also be changed. See for example the Listing. Listing. Passing arrays to functions 0 void reading_array(int Array[]) for (int i=0; i<; i++) printf("array[ %d] =", i ); scanf("%d", &Array[i]); void printing_array(int Array[]) for (int i=0; i<; i++) printf("array[ %d] = %d\n", i, Array[i]); void main(void) int myarray[]; printf("reading values for myarray:\n"); reading_array(myarray); printf("printing myarray values:\n"); printing_array(myarray);. Symbolic Constants A function parameter may also be declared to be constant. This may be used to indicate that the function does not change the value of a parameter: int func (const int par, const int par) //...
6 A function may also return a constant result. For example, const char* func (void) return "const string"; The usual place for constant definition is within header files so that they can be shared by source files.. Global and Local Scope Variables have either local or global scope. Their scope determines whether or not another function can use them. Everything defined outside functions and classes is said to have a global scope. The functions swap, swap, swap(listing ) all have a global scope. Variables may also be defined at the global scope. Uninitialized global variables are automatically initialized to zero. Global entities are generally accessible everywhere in the program. Each block in a program defines a local scope. Thus the body of a function represents a local scope. The parameters of a function have the same scope as the function body. Variables defined within a local scope are visible to that scope only. A variable need only be unique within its own scope. Local scopes may be nested, in which case the inner scopes override the outer scopes. For example, in int x; // x is global void function (int x) // x is local to the body of function if (x > 0) double x; // x is local to this block //... there are three distinct scopes, each containing a distinct x. Generally, the lifetime of a variable is limited to its scope. So, for example, global variables last for the duration of program execution, while local variables are created when their scope is entered and destroyed when their scope is exited. The memory space for global variables is reserved prior to program execution commencing, whereas the memory space for local variables is allocated on the stack during program execution. In C++, global variables are legal, but they are almost never used. They are necessary when the programmer needs to make data available to many functions and he does not want to pass that data as a parameter from function to function. Note: Global variables are dangerous because they are shared data, and one function can change a global variable in a way that is invisible to another function. This can and does create bugs that are very difficult to find.. Static Variables and Functions It is often useful to confine the accessibility of a global variable or function to a single function. This is facilitated by the storage class specifier static. The static storage class specifier with a local variable preserves the last value between
7 successive calls to that function. A static variable acts like a local variable but has the lifetime of an external variable. Syntax of declaration is: static <data definition> ; static <function definition> ; The same argument may be applied to the global variables in this file that are for the private use of the functions in the file. For example, static int var; // static global variable A local variable in a function may also be defined as static. The variable will remain only accessible within its local scope; however, its lifetime will no longer be confined to this scope, but will instead be global. In other words, a static local variable is a global variable which is only accessible within its local scope. Like global variables, static local variables are automatically initialized to 0. Static local variables are useful when we want the value of a local variable to persist across the calls to the function in which it appears. An example of using static variable: Listing. Using static variable void func(void) static int m=; printf("initial value: m = %d\n", m); m++; printf("final value: m = %d\n", m); void main() printf( "First call of function :\n"); func(); printf("\nsecond call of function :\n" ); func(); static declaration forces the static life of variable without changing its domain. These variables are allocated in the data segment, so the allocation is throughout the execution of the program, but can be referred only in the block in which it was declared. Listing. Using static variable #include <conio.h> void func(void) int a=; static int b=; a=a+; b=b+; printf("\na=%d, b=%d", a, b); void main() func(); func(); func(); getch();
8 . Extern Variables and Functions Because a global variable may be defined in one file and referred to in other files, some means of telling the compiler that the variable is defined elsewhere may be needed. Otherwise, the compiler may object to the variable as undefined. This is facilitated by an extern declaration. For example, the declaration extern int size; // variable declaration informs the compiler that size is actually defined somewhere (may be later in this file or in another file). This is called a variable declaration (not definition) because it does not lead to any storage being allocated for size. It is not recommended to include an initializer for an extern variable, since this causes it to become a variable definition and have storage allocated for it: extern int size = ; // no longer a declaration! If there is another definition for size elsewhere in the program, it will eventually produce an error. Function prototypes may also be declared as extern, but this has no effect when a prototype appears at the global scope. It is more useful for declaring function prototypes inside a function. For example: double Tangent (double angle) extern double sin(double); // defined elsewhere extern double cos(double); // defined elsewhere return sin(angle) / cos(angle); Listing. Using extern variables and functions // File FILE_A.cpp #include <conio.h> extern int a; extern void func(); void main() printf("a=%d\n", a); func(); getch(); // File FILE_B.cpp int a = 0; void func() printf("\nis executed func"); printf ("\na=%d", a); Remarks: The both files, FILE_A.cpp and FILE_B.cpp, are included in the same project. Variable a is declared in file FILE_B.cpp in line ; this produce the allocation of variable on stack and its initialization. This variable can be used in FILE_A.cpp because of declaration extern from line. Both files use the same variable. Function func() is defined in FILE_B.cpp (lines -) and it can be used in FILE_A.cpp because of the declaration extern from line. The two files can be compiled separately. The links between declaration and usage of variable a and function func() are made in the linkage stage.
9 . Recursion A function can call itself. A function which calls itself is said to be recursive. Recursion can be direct or indirect. It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function. Recursion is a general programming technique applicable to problems which can be defined in terms of them selves. Take the factorial problem which is defined as: - factorial of 0 is. - factorial of a positive number n is n times the factorial of n-. The second line clearly indicates that factorial is defined in terms of itself and hence can be expressed as a recursive function: long factorial (unsigned int n) if (n<=) return ; else return n*fact(n-); Figure. Factorial() execution trace. For n set to, Figure. provides a trace of the calls to factorial. The stack frames for these calls appear sequentially on the runtime stack, one after the other. A recursive function must have at least one termination condition which can be satisfied. Otherwise, the function will call itself indefinitely until the runtime stack overflows. The factorial function, for example, has the termination condition n<= which, when satisfied, causes the recursive calls to fold back. (Note that for a negative n this condition will never be satisfied and factorial will fail). As a general rule, all recursive functions can be rewritten using iteration. An iterative version is therefore preferred in this case: long fact (unsigned int n) long res = ; for(int i=; i<=n; i++) // or: while (n> 0) res=res * n--; res = res*i; return res; Example. General Program Structure Generally, a program consists of three parts: the preprocessing directives, the global statements, the definitions of functions. In C/C++ programming, it is considered good practice to use prototype declarations for all functions that you call. These prototypes help to ensure that the compiler can generate correct code for calling the functions, as well as allowing the compiler to catch certain mistakes you might make. Strictly speaking, however, prototypes are optional but using prototypes of functions offers the following advantages:
10 -it gives clear program, the programmer can easily see what names are used and how to use (how many parameters and the data types); - if function prototypes are specified, the order of defining functions is not important. Listing. I. The preprocessing directives II. Global declarations #include <conio.h> #define PI. float area(float); float length(float); int r = ; void main(void) float radius, a, l; Local declaration III. Function definitions printf("enter the radius value:"); scanf("%f", &radius); a = area(radius); l = length(radius); printf("\ncirclehas:"); printf("\nradius = %f ", radius); printf("\narea = %f ", a); printf("\nlength = %f", l); Statements printf("\ncircle has:"); printf("\nradius = %d ", r); printf("\narea = %f ", area(r)); printf("\nlength = %f", length(r)); getch(); float area(float r) float a; a = PI * r * r; return a; float length(float r) float l; l = * PI * r; return l; Remarks: The call of functions length() and area() is available in main() because of their prototypes. If prototypes are missing, functions must be defined before the main(). The header of a function must have the same signature with its prototype (the same returned type and same number and type of parameters).
Lecture 3. Variables. Variables
Lecture 3 Variables Variables Data processed by programs are input from keyboard by user, are read from the storage medium or are obtained by evaluating expressions. For this purpose it is necessary to
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 informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationUnit 7. Functions. Need of User Defined Functions
Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have
More informationCSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:
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 informationCSE 230 Intermediate Programming in C and C++ Functions
CSE 230 Intermediate Programming in C and C++ Functions Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse230/ Concept of Functions
More informationFunctions and Recursion
Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead
More informationWhy Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...
Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such
More informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationComputer Programming Unit 3
POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very
More informationComputer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary
GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis
More informationUnit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.
1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific task. The functions which are created by programmer are
More informationPointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables
Chapter 11 Pointers The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into bytes, with each byte capable
More informationStructured Programming. Functions and Structured Programming. Functions. Variables
Structured Programming Functions and Structured Programming Structured programming is a problem-solving strategy and a programming methodology. The construction of a program should embody topdown design
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationEL6483: Brief Overview of C Programming Language
EL6483: Brief Overview of C Programming Language EL6483 Spring 2016 EL6483 EL6483: Brief Overview of C Programming Language Spring 2016 1 / 30 Preprocessor macros, Syntax for comments Macro definitions
More informationb. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.
UNIT IV 1. Appropriately comment on the following declaration int a[20]; a. Array declaration b. array initialization c. pointer array declaration d. integer array of size 20 2. Appropriately comment on
More informationEC 413 Computer Organization
EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages
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 informationWhat Is a Function? Illustration of Program Flow
What Is a Function? A function is, a subprogram that can act on data and return a value Each function has its own name, and when that name is encountered, the execution of the program branches to the body
More informationBil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7
Strings and Clases BIL104E: Introduction to Scientific and Engineering Computing Lecture 7 Manipulating Strings Scope and Storage Classes in C Strings Declaring a string The length of a string Copying
More informationC Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function
More informationLecture 6. Statements
Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions
More informationDay08 A. Young W. Lim Mon. Young W. Lim Day08 A Mon 1 / 27
Day08 A Young W. Lim 2017-10-16 Mon Young W. Lim Day08 A 2017-10-16 Mon 1 / 27 Outline 1 Based on 2 C Functions (2) Storage Class and Scope Storage Class Specifiers A. Storage Duration B. Scope C. Linkage
More informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More information& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.
Computer Programming and Utilization (CPU) 110003 G) Functions 1 What is user defined function? Explain with example. Define the syntax of function in C. A function is a block of code that performs a specific
More informationProgramming for Electrical and Computer Engineers. Loops
Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly
More informationC Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationUNIT 3 FUNCTIONS AND ARRAYS
UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing
More informationDeclaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:
Declarations Based on slides from K. N. King Declaration Syntax General form of a declaration: declaration-specifiers declarators ; Declaration specifiers describe the properties of the variables or functions
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 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 informationBinding and Variables
Binding and Variables 1. DEFINITIONS... 2 2. VARIABLES... 3 3. TYPE... 4 4. SCOPE... 4 5. REFERENCES... 7 6. ROUTINES... 9 7. ALIASING AND OVERLOADING... 10 8. GENERICS AND TEMPLATES... 12 A. Bellaachia
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
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 informationChapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.
Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop
More informationLecture 2: C Programming Basic
ECE342 Introduction to Embedded Systems Lecture 2: C Programming Basic Ying Tang Electrical and Computer Engineering Rowan University 1 Facts about C C was developed in 1972 in order to write the UNIX
More informationFundamental Concepts and Definitions
Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most
More informationIt is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.
Functions A number of statements grouped into a single logical unit are called a function. The use of function makes programming easier since repeated statements can be grouped into functions. Splitting
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 information[0569] p 0318 garbage
A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the
More informationCS113: Lecture 4. Topics: Functions. Function Activation Records
CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make
More informationComputer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore
Sir Syed University of Engineering and Technology. Computer ming & Problem Solving ( CPPS ) Functions Chapter No 1 Compiled By: Sir Syed University of Engineering & Technology Computer Engineering Department
More informationReview of the C Programming Language
Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the
More informationCSCI 2132 Software Development. Lecture 17: Functions and Recursion
CSCI 2132 Software Development Lecture 17: Functions and Recursion Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 15-Oct-2018 (17) CSCI 2132 1 Previous Lecture Example: binary
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationGovernment Polytechnic Muzaffarpur.
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking
More informationTechnical Questions. Q 1) What are the key features in C programming language?
Technical Questions Q 1) What are the key features in C programming language? Portability Platform independent language. Modularity Possibility to break down large programs into small modules. Flexibility
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationC Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach
C Fundamentals & Formatted Input/Output adopted from KNK C Programming : A Modern Approach C Fundamentals 2 Program: Printing a Pun The file name doesn t matter, but the.c extension is often required.
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 FUNCTIONS INTRODUCTION AND MAIN All the instructions of a C program are contained in functions. üc is a procedural language üeach function performs a certain task A special
More informationReview of the C Programming Language for Principles of Operating Systems
Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights
More informationProgramming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014
Programming & Data Structure Laboratory rrays, pointers and recursion Day 5, ugust 5, 2014 Pointers and Multidimensional rray Function and Recursion Counting function calls in Fibonacci #include
More informationC Programming Lecture V
C Programming Lecture V Instructor Özgür ZEYDAN http://cevre.beun.edu.tr/ Modular Programming A function in C is a small sub-program that performs a particular task, and supports the concept of modular
More informationFunctions. Chapter 5
Functions Chapter 5 Function Definition type function_name ( parameter list ) declarations statements For example int factorial(int n) int i, product = 1; for (i = 2; I
More informationQUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:
QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the
More informationM.CS201 Programming language
Power Engineering School M.CS201 Programming language Lecture 4 Lecturer: Prof. Dr. T.Uranchimeg Agenda How a Function Works Function Prototype Structured Programming Local Variables Return value 2 Function
More informationC Functions. Object created and destroyed within its block auto: default for local variables
1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program
More informationblock structure, scope and macros
static variables static variables week 6, and macros Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 20 review of static variables static variables // declaration
More informationFlow Control. CSC215 Lecture
Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements
More informationProgramming for Engineers Iteration
Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers
More informationProgramming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3
Programming in C main Level 2 Level 2 Level 2 Level 3 Level 3 1 Programmer-Defined Functions Modularize with building blocks of programs Divide and Conquer Construct a program from smaller pieces or components
More informationVariation of Pointers
Variation of Pointers A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before
More informationA Fast Review of C Essentials Part II
A Fast Review of C Essentials Part II Structural Programming by Z. Cihan TAYSI Outline Fixed vs. Automatic duration Scope Global variables The register specifier Storage classes Dynamic memory allocation
More informationLecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?
Lecture 16 Functions II they re back and they re not happy Daily Puzzle If it is raining at midnight - will we have sunny weather in 72 hours? function prototypes For the sake of logical clarity, the main()
More informationTo declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows
Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful
More informationA brief introduction to C programming for Java programmers
A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically
More informationGoals of this Lecture
C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationM1-R4: Programing and Problem Solving using C (JAN 2019)
M1-R4: Programing and Problem Solving using C (JAN 2019) Max Marks: 100 M1-R4-07-18 DURATION: 03 Hrs 1. Each question below gives a multiple choice of answers. Choose the most appropriate one and enter
More informationUNIT III (PART-II) & UNIT IV(PART-I)
UNIT III (PART-II) & UNIT IV(PART-I) Function: it is defined as self contained block of code to perform a task. Functions can be categorized to system-defined functions and user-defined functions. System
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 informationApplied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011
Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and
More informationMA 511: Computer Programming Lecture 2: Partha Sarathi Mandal
MA 511: Computer Programming Lecture 2: http://www.iitg.ernet.in/psm/indexing_ma511/y10/index.html Partha Sarathi Mandal psm@iitg.ernet.ac.in Dept. of Mathematics, IIT Guwahati Semester 1, 2010-11 Largest
More informationLab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering
2013/2014 Programming Fundamentals for Engineers Lab Lab Session # 1 Introduction to C Language ALQUDS University Department of Computer Engineering Objective: Our objective for today s lab session is
More information15 FUNCTIONS IN C 15.1 INTRODUCTION
15 FUNCTIONS IN C 15.1 INTRODUCTION In the earlier lessons we have already seen that C supports the use of library functions, which are used to carry out a number of commonly used operations or calculations.
More informationCHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++
CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,
More informationCS 161 Exam II Winter 2018 FORM 1
CS 161 Exam II Winter 2018 FORM 1 Please put your name and form number on the scantron. True (A)/False (B) (28 pts, 2 pts each) 1. The following array declaration is legal double scores[]={0.1,0.2,0.3;
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 informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationA function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).
CIT Intro to Computer Systems Lecture # (//) Functions As you probably know from your other programming courses, a key part of any modern programming language is the ability to create separate functions
More informationInformatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
More informationFunction Call Stack and Activation Records
71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students
More informationChapter 8: Function. In this chapter, you will learn about
Principles of Programming Chapter 8: Function In this chapter, you will learn about Introduction to function User-defined function Formal and Actual Parameters Parameter passing by value Parameter passing
More information3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type
Pointer Basics What is a pointer? pointer = memory address + type C Language III CMSC 313 Sections 01, 02 A pointer can contain the memory address of any variable type A primitive (int, char, float) An
More informationFundamentals of Programming
Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions
More informationChapter 9. Variable Scope and Functions
Chapter 9. Variable Scope and Functions So far, we have been using only global variables. In this chapter, we will learn about other kinds of variables and how to use them. This chapter also tells you
More informationData Types and Variables in C language
Data Types and Variables in C language Basic structure of C programming To write a C program, we first create functions and then put them together. A C program may contain one or more sections. They are
More informationM.EC201 Programming language
Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2 The union Keyword The
More informationThis is CS50. Harvard University Fall Quiz 0 Answer Key
Quiz 0 Answer Key Answers other than the below may be possible. Binary Bulbs. 0. Bit- Sized Questions. 1. Because 0 is non- negative, we need to set aside one pattern of bits (000) for it, which leaves
More information10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013
Midterm Topic Review Pointer Basics C Language III CMSC 313 Sections 01, 02 1 What is a pointer? Why Pointers? Pointer Caution pointer = memory address + type A pointer can contain the memory address of
More informationChapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016
Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use
More informationC: How to Program. Week /Apr/16
C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies
More informationFunctions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.
Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements
More information1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?
1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity
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 informationCSCI 2132 Software Development. Lecture 18: Functions
CSCI 2132 Software Development Lecture 18: Functions Instructor: Vlado Keselj Faculty of Computer Science Dalhousie University 18-Oct-2017 (18) CSCI 2132 1 Previous Lecture Example: binary search Multidimensional
More information