Chapter 9. Variable Scope and Functions

Size: px
Start display at page:

Download "Chapter 9. Variable Scope and Functions"

Transcription

1 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 how to divide your code into functions. 9.1 Scope and Class All variables have two attributes: scope and class. The scope of a variable is the area of the program in which the variable is valid. A global variable is valid everywhere (hence the name global), so its scope is the whole program. A local variable has a scope that is limited to the block in which it is declared and cannot be accessed outside that block. A block is a section of code enclosed in curly braces (). Figure 9-1 shows the difference between local and global variables. Figure 9-1. Local and global variables You can declare a local variable with the same name as a global variable. Normally, the scope of the variable count (first declaration) would be the whole program. The declaration of a second local count takes precedence over the global declaration inside the small block in which the local count is declared. In this block, the global count is hidden. You can also nest local declarations and hide local variables. Figure 9-2 illustrates a hidden variable.

2 Figure 9-2. Hidden variables The variable count is declared as both a local variable and a global variable. Normally, the scope of count (global) is the entire program; however, when a variable is declared inside a block, that instance of the variable becomes the active one for the length of the block. The global count has been hidden by the local count for the scope of this block. The shaded block in the figure shows where the scope of count (global) is hidden. A problem exists in that when you have the statement: count = 1; you cannot tell easily to which count you are referring. Is it the global count, the one declared at the top of main, or the one in the middle of the while loop? You should give these variables different names, like total_count, current_count, and item_count. The class of a variable may be either permanent or temporary. Global variables are always permanent. They are created and initialized before the program starts and rema in until it terminates. Temporary variables are allocated from a section of memory called the stack at the beginning of the block. If you try to allocate too many temporary variables, you will get a "Stack overflow" error. The space used by the temporary variables is returned to the stack at the end of the block. Each time the block is entered, the temporary variables are initialized.

3 The size of the stack depends on the system and compiler you are using. On many UNIX systems, the program is automatically allocated the largest possible stack. On other systems, a default stack size is allocated that can be changed by a compiler switch. On MS-DOS/Windows systems, the stack space must be less than 65,536 bytes. This may seem like a lot of space; however, several large arrays can eat it up quickly. You should consider making all large arrays permanent. Local variables are temporary unless they are declared static. static has an entirely different meaning when used with global variables. It indicates that a variable is local to the current file. See Chapter 18. Example 9-1 illustrates the difference between permanent and temporary variables. We have chosen obvious names: temporary is a temporary variable, while permanent is permanent. The variable temporary is initialized each time it is created (at the beginning of the for statement block). The variable permanent is initialized only once, at startup time. In the loop, both variables are incremented. However, at the top of the loop, temporary is initialized to one, as shown in Example 9-1. Example 9-1. vars/vars.c #include <stdio.h> int main() int counter; /* loop counter */ for (counter = 0; counter < 3; ++counter) int temporary = 1; /* A temporary variable */ static int permanent = 1; /* A permanent variable */ printf("temporary %d Permanent %d\n", temporary, permanent); ++temporary; ++permanent; return (0); The output of this program is:

4 Temporary 1 Permanent 1 Temporary 1 Permanent 2 Temporary 1 Permanent 3 Temporary variables are sometimes referred to as automatic variables because the space for them is allocated automatically. The qualifier auto can be used to denote a temporary variable; however, in practice it is almost never used. Table 9-1 describes the different ways in which a variable can be declared. Table 9-1. Declaration Modifiers Outside all blocks Global Permanent Once static outside all blocks Global [1] Permanent Once Inside a block Local Temporary Each time block is entered static inside a block Local Permanent Once [1] A static declaration made outside blocks indicates the variable is local to the file in which it is declared. (See Chapter 18 for more information on programming with multiple files.) 9.2 Functions Functions allow us to group commonly used code into a compact unit that can be used repeatedly. We have already encountered one function, main. It is a special function called at the beginning of the program. All other functions are directly or indirectly called from main. Suppose we want to write a program to compute the area of three triangles. We could write out the formula three times, or we could create a function to do the work. Each function should begin with a comment block containing the following: Name Name of the function Description Description of what the function does

5 Parameters Description of each of the parameters to the function Returns Description of the return value of the function Additional sections may be added such as file formats, references, or notes. Refer to Chapter 3, for other suggestions. Our function to compute the area of a triangle begins with: /********************************************* * triangle -- Computes area of a triangle. * * Parameters * * width -- Width of the triangle. * * height -- Height of the triangle. * * Returns * * area of the triangle. * *********************************************/ The function proper begins with the line: float triangle(float width, float height) float is the function type. The two parameters are width and height. They are of type float also. C uses a form of parameter passing called "Call by value". When our procedure triangle is called, with code such as: triangle(1.3, 8.3); C copies the value of the parameters (in this case 1.3 and 8.3) into the function's parameters (width and height) and then starts executing the function's code. With this form of parameter passing, a function cannot pass data back to the caller using parameters. [2] [2] This statement is not strictly true. We can trick C into passing information back through the use of pointers, as we'll see in Chapter 13.

6 The function type is not required by C. If no function type is declared, the type defaults to int. However, if no type is provided, the maintainer cannot determine if you wanted to use the default (int) or if you simply forgot to declare a type. To avoid this confusion, always declare the function type and do not use the default. The function computes the area with the statement: area = width * height / 2.0; What's left is to give the result to the caller. This step is done with the return statement: return (area); Example 9-2 shows our full triangle function. Example 9-2. tri-sub/tri-sub.c #include <stdio.h> /******************************************** * triangle -- Computes area of a triangle. * * Parameters * * width -- Width of the triangle. * * height -- Height of the triangle. * * Returns * * area of the triangle. * ********************************************/ float triangle(float width, float height) float area; /* Area of the triangle */ area = width * height / 2.0; return (area); The line: size = triangle(1.3, 8.3);

7 is a call to the function triangle. C assigns 1.3 to the parameter width and 8.3 to height. If functions are the rooms of our building, then parameters are the doors between the rooms. In this case, the value 1.3 is going through the door marked width. Parameters' doors are one way. Things can go in, but they can't go out. The return statement is how we get data out of the function. In our triangle example, the function assigns the local variable area the value 5.4, then executes the statement return (area);. The return value of this function is 5.4, so our statement: size = triangle (1.3, 8.3) assigns size the value 5.4. Example 9-3 computes the area of three triangles. Example 9-3. tri-prog/tri-prog.c [File: tri-sub/tri-prog.c] #include <stdio.h> /******************************************** * triangle -- Computes area of a triangle. * * Parameters * * width -- Width of the triangle. * * height -- Height of the triangle. * * Returns * * area of the triangle. * ********************************************/ float triangle(float width, float height) float area; /* Area of the triangle */ area = width * height / 2.0; return (area); int main()

8 printf("triangle #1 %f\n", triangle(1.3, 8.3)); printf("triangle #2 %f\n", triangle(4.8, 9.8)); printf("triangle #3 %f\n", triangle(1.2, 2.0)); return (0); If we want to use a function before we define it, we must declare it just like a variable to inform the compiler about the function. We use the declaration: /* Compute a triangle */ float triangle (float width, float height); for the triangle function. This declaration is called the function prototype. The variable names are not required when declaring a function prototype. Our prototype could have just as easily been written as: float triangle(float, float); However, we use the longer version because it gives the programmer additional information, and it's easy to create prototypes using the editor's cut and paste functions. Strictly speaking, the prototypes are optional for some functions. If no prototype is specifie d, the C compiler assumes the function returns an int and takes any number of parameters. Omitting a prototype robs the C compiler of valuable information that it can use to check function calls. Most compilers have a compile -time switch that warns the programmer about function calls without prototypes. 9.3 Functions with No Parameters A function can have any number of parameters, including none. But even when using a function with no parameters, you still need the parentheses: value = next_index(); Declaring a prototype for a function without parameters is a little tricky. You can't use the statement: int next_index(); because the C compiler will see the empty parentheses and assume that this is a K&R-style function declaration. See Chapter 19, for details on this older style. The keyword void is used to indicate an empty parameter list. So the prototype for our next_index function is:

9 int next_index(void); void is also used to indicate that a function does not return a value. (Void is similar to the FORTRAN subroutine or PASCAL procedure.) For example, this function just prints a result; it does not return a value: void print_answer(int answer) if (answer < 0) printf("answer corrupt\n"); return; printf("the answer is %d\n", answer); Question 9-1: Example 9-4 should compute the length of a string. [3] Instead, it insists that all strings are of length 0. Why? (Click here for the answer Section 9.6 ) [3] This function performs the same function as the library function strlen. Example 9-4. len/len.c /******************************************************** * Question: * * Why does this program always report the length * * of any string as 0? * * A sample "main" has been provided. It will ask * * for a string and then print the length. * ********************************************************/ #include <stdio.h> /******************************************************** * length -- Computes the length of a string. * * Parameters * * string -- The string whose length we want. * * Returns * * the length of the string. * ********************************************************/ int length(char string[]) int index; /* index into the string */

10 /* * Loop until we reach the end of string character */ for (index = 0; string[index]!= '\0'; ++index) /* do nothing */ return (index); int main() char line[100]; /* Input line from user */ while (1) printf("enter line:"); fgets(line, sizeof(line), stdin); printf("length (including newline) is: %d\n", length(line)); 9.4 Structured Programming Computer scientists spend a great deal of time and effort studying how to program. The result is that they come up with absolutely, positively, the best programming methodology a new one each month. Some of these systems include flow charts, top-down programming, bottom-up programming, structured programming, and object-oriented design (OOD). Now that we have learned about functions, we can talk about using structured programming techniques to design programs. These techniques are ways of dividing up or structuring a program into small, well-defined functions. They make the program easy to write and easy to understand. I don't claim that this method is the absolute best way to program. It happens to be the method that works best for me. If another system works better for you, use it. The first step in programming is to decide what you are going to do. This has already been described in Chapter 7. Next, decide how you are going to structure your data. Finally, the coding phase begins. When writing a paper, you start with an outline of each section in the paper described by a single s entence. The details will be filled in later. Writing a program is a similar process. You start with an outline, and this becomes your main function. The details can be hidden within other functions. For example, Example 9-5 solves all the world's problems.

11 Example 9-5. Solve the World's Problems int main() init(); solve_problems(); finish_up(); return (0); Of course, some of the details will have to be filled in later. Start by writing the main function. It should be less than three pages long. If it grows longer, consider splitting it up into two smaller, simpler functions. After the main function is complete, you can start on the others. This type of structured programming is called top-down programming. You start at the top (main) and work your way down. Another type of coding is called bottom -up programming. This method involves writing the lowest-level function first, testing it, and then building on that working set. I tend to use some bottom-up techniques when I'm working with a new standard function that I haven't used before. I write a small function to make sure that I really know how the function works, and then continue from there. This approach is used in Chapter 7 to construct the calculator program. So, in actual practice, both techniques are useful. A mostly top-down, partially bottom-up technique results. Computer scientists have a term for this methodology: chaos. The one rule you should follow in programming is "Use what works best." 9.5 Recursion Recursion occurs when a function calls itself directly or indirectly. Some programming functions, such as the factorial, lend themselves naturally to recursive algorithms. A recursive function must follow two basic rules: It must have an ending point. It must make the problem simpler. A definition of factorial is: fact(0) = 1

12 fact(n) = n * fact(n-1) In C, this definition is: int fact(int number) if (number == 0) return (1); /* else */ return (number * fact(number-1)); This definition satisfies our two rules. First, it has a definite ending point (when number == 0). Second, it simplifies the problem because the calculation of fact(number-1) is simpler than fact(number). Factorial is legal only for number >= 0. But what happens if we try to compute fact(-3)? The program will abort with a stack overflow or similar message. fact(-3) calls fact(-4), which calls fact(-5), etc. No ending point exists. This error is referred to as an infinite recursion error. Many things that we do iteratively can be done recursively for example, summing up the elements of an array. We define a function to add elements m-n of an array as follows: If we have only one element, then the sum is simple. Otherwise, we use the sum of the first element and the sum of the rest. In C, this function is: int sum(int first, int last, int array[]) if (first == last) return (array[first]); /* else */ return (array[first] + sum(first+1, last, array)); For example: Sum( ) = 1 + Sum(8 3 2) = 8 + Sum(3 2) = 3 + Sum (2) =

13 = = = 14 Answer = Answers Answer 9-1: The programmer went to a lot of trouble to explain that the for loop did nothing (except increment the index). However, there is no semicolon (;) at the end of the for. C keeps on reading until it sees a statement (in this case return(index)), and then puts that statement in the for loop. Properly done, this program should look like Example 9-6. Example 9-6. len2/len2.c #include <stdio.h> int length(char string[]) int index; /* index into the string */ /* * Loop until we reach the end-of-string character */ for (index = 0; string[index]!= '\0'; ++index) continue; /* do nothing */ return (index); int main() char line[100]; /* Input line from user */ while (1) printf("enter line:"); fgets(line, sizeof(line), stdin); printf("length (including newline) is: %d\n", length(line));

14 9.7 Programming Exercises Exercise 9-1: Write a procedure that counts the number of words in a string. (Your documentation should describe exactly how you define a word.) Write a program to test your new procedure. Exercise 9-2: Write a function begins(string1,string2) that returns true if string1 begins string2. Write a program to test the function. Exercise 9-3: Write a function count(number, array, length) that counts the number of times number appears in array. The array has length e lements. The function should be recursive. Write a test program to go with the function. Exercise 9-4: Write a function that takes a character array and returns a primitive hash code by adding up the value of each character in the array. Exercise 9-5: Write a function that returns the maximum value of an array of numbers. Exercise 9-6: Write a function that scans a character array for the character - and replaces it with _.

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 9 Variable Scope and Functions Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Variable Scope and Class Variables are defined by two attributes: Scope The area where a

More information

Chapter 8. More Control Statements

Chapter 8. More Control Statements Chapter 8. More Control Statements 8.1 for Statement The for statement allows the programmer to execute a block of code for a specified number of times. The general form of the for statement is: for (initial-statement;

More information

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

15 FUNCTIONS IN C 15.1 INTRODUCTION

15 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 information

EC 413 Computer Organization

EC 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 information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Lecture 6. Statements

Lecture 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 information

Chapter 5. Arrays, Qualifiers, and Reading Numbers

Chapter 5. Arrays, Qualifiers, and Reading Numbers Chapter 5. Arrays, Qualifiers, and Reading Numbers 5.1 Arrays In constructing our building, we have identified each brick (variable) by name. That process is fine for a small number of bricks, but what

More information

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

C 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 information

University of Kelaniya Sri Lanka

University of Kelaniya Sri Lanka University of Kelaniya Sri Lanka Scope, Lifetime and Storage Class of a Variable COSC 12533/ COST 12533 SACHINTHA PITIGALA 2017 - Sachintha Pitigala < 1 What is Scope? Scope of Identifier: The scope of

More information

C Language, Token, Keywords, Constant, variable

C Language, Token, Keywords, Constant, variable C Language, Token, Keywords, Constant, variable A language written by Brian Kernighan and Dennis Ritchie. This was to be the language that UNIX was written in to become the first "portable" language. C

More information

Some Computer Preliminaries

Some Computer Preliminaries Some Computer Preliminaries Before we get started, let's look at some basic components that play a major role in a computer's ability to run programs: 1) Central Processing Unit: The "brains" of the computer

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

142

142 Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned

More information

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

CS113: 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 information

Preview from Notesale.co.uk Page 6 of 52

Preview from Notesale.co.uk Page 6 of 52 Binary System: The information, which it is stored or manipulated by the computer memory it will be done in binary mode. RAM: This is also called as real memory, physical memory or simply memory. In order

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

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

Functions. (transfer of parameters, returned values, recursion, function pointers). 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

More information

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. 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 information

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

Intro to Computer Programming (ICP) Rab Nawaz Jadoon Intro to Computer Programming (ICP) Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS IIT, Abbottabad Pakistan Introduction to Computer Programming (ICP) What

More information

AN 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 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 information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Chapter 12 Variables and Operators Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2 Highlights (2) r. height

More information

Unit 7. Functions. Need of User Defined Functions

Unit 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 information

Technical 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? 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 information

Functions and Recursion

Functions 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 information

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

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values

More information

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

C 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 information

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

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. If a function has default arguments, they can be located anywhere

More information

Programming for Electrical and Computer Engineers. Loops

Programming 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 information

Fundamental of Programming (C)

Fundamental 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 information

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Bil 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 information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

Function. 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

Function. 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 information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

Functions. Systems Programming Concepts

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

Flow Control. CSC215 Lecture

Flow 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 information

Chapter 7 Functions. Now consider a more advanced example:

Chapter 7 Functions. Now consider a more advanced example: Chapter 7 Functions 7.1 Chapter Overview Functions are logical groupings of code, a series of steps, that are given a name. Functions are especially useful when these series of steps will need to be done

More information

In further discussion, the books make other kinds of distinction between high level languages:

In further discussion, the books make other kinds of distinction between high level languages: Max and Programming This essay looks at Max from the point of view of someone with a bit of experience in traditional computer programming. There are several questions that come up from time to time on

More information

Functions. 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 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 information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Chapter 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 information

War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control.

War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control. War Industries Presents: An Introduction to Programming for Hackers Part III - Advanced Variables & Flow Control By Lovepump, 2004 Visit: www.warindustries.com Part II Programs 101 Goals: At the end of

More information

Programming 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 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 information

Chapter 3 - Functions

Chapter 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 information

What Is a Function? Illustration of Program Flow

What 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 information

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto CS 170 Java Programming 1 The Switch Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Menu-Style Code With ladder-style if-else else-if, you might sometimes find yourself writing menu-style

More information

Function Call Stack and Activation Records

Function 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 information

PROGRAMMAZIONE I A.A. 2017/2018

PROGRAMMAZIONE 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 information

Scopes Global and Block

Scopes Global and Block Scopes Global and Block Lecture 9 Go to poll.unc.edu Sign-in via this website then go to pollev.com/compunc VSCode: Open Project -> View Terminal -> npm run pull -> npm start Videos for Thursday V15 -

More information

Data Types and Variables in C language

Data 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 information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

EL6483: Brief Overview of C Programming Language

EL6483: 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 information

User Defined Functions

User Defined Functions User Defined Functions CS 141 Lecture 4 Chapter 5 By Ziad Kobti 27/01/2003 (c) 2003 by Ziad Kobti 1 Outline Functions in C: Definition Function Prototype (signature) Function Definition (body/implementation)

More information

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

A 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 information

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

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y ); - 50 - Control Structures: 8. Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

CSE 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. 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 information

Introduction to C/C++ Programming

Introduction to C/C++ Programming Chapter 1 Introduction to C/C++ Programming This book is about learning numerical programming skill and the software development process. Therefore, it requires a lot of hands-on programming exercises.

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. 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 information

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475 C/C++ Notes C/C++ Coding Style Guidelines -0 Ray Mitchell C/C++ Notes 0 0 0 0 NOTE G. C/C++ Coding Style Guidelines. Introduction The C and C++ languages are free form, placing no significance on the column

More information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead. Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public

More information

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals VENTURE COMS 4115 - Language Reference Manual Zach Adler (zpa2001), Ben Carlin (bc2620), Naina Sahrawat (ns3001), James Sands (js4597) Section 1. Lexical Elements 1.1 Identifiers An identifier in VENTURE

More information

CSE101-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 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 information

Provided by - Microsoft Placement Paper Technical 2012

Provided by   - Microsoft Placement Paper Technical 2012 Provided by www.yuvajobs.com - Microsoft Placement Paper Technical 2012 1. Analytical 25 questions ( 30 minutes) 2. Reasoning 25 questions (25 minutes) 3. Verbal 20 questions (20 minutes) Analytical (some

More information

1 Overview. 2 Basic Program Structure. 2.1 Required and Optional Parts of Sketch

1 Overview. 2 Basic Program Structure. 2.1 Required and Optional Parts of Sketch Living with the Lab Winter 2015 What s this void loop thing? Gerald Recktenwald v: February 7, 2015 gerry@me.pdx.edu 1 Overview This document aims to explain two kinds of loops: the loop function that

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 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 information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

Learning to Program with Haiku

Learning to Program with Haiku Learning to Program with Haiku Lesson 4 Written by DarkWyrm All material 2010 DarkWyrm It would be incredibly hard to write anything useful if there weren't ways for our programs to make decisions or to

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Pointers Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) Pointers February 29, 2012 1

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

A Fast Review of C Essentials Part II

A 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 information

OBJECTIVE QUESTIONS: Choose the correct alternative:

OBJECTIVE QUESTIONS: Choose the correct alternative: OBJECTIVE QUESTIONS: Choose the correct alternative: 1. Function is data type a) Primary b) user defined c) derived d) none 2. The declaration of function is called a) function prototype b) function call

More information

Chapter 2: Functions and Control Structures

Chapter 2: Functions and Control Structures Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random

More information

Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Four: Functions: Built-in, Parameters and Arguments, Fruitful and Void Functions

More information

CpSc 1111 Lab 5 Formatting and Flow Control

CpSc 1111 Lab 5 Formatting and Flow Control CpSc 1111 Lab 5 Formatting and Flow Control Overview By the end of the lab, you will be able to: use fscanf() to accept a character input from the user execute a basic block iteratively using loops to

More information

The New C Standard (Excerpted material)

The New C Standard (Excerpted material) The New C Standard (Excerpted material) An Economic and Cultural Derek M. Jones derek@knosof.co.uk Copyright 2002-2008 Derek M. Jones. All rights reserved. 165 5.1.2.2.1 Program startup 5.1.2.2.1 Program

More information

CSE 230 Intermediate Programming in C and C++ Functions

CSE 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 information

Sums. Here's a (poor) program to add three numbers

Sums. Here's a (poor) program to add three numbers Arrays 1 2 Sums 3 Here's a (poor) program to add three numbers /* Add three numbers */ #include add.c int main() { int numbers[3]; numbers[0] = 16; numbers[1] = 12; numbers[2] = 14; int sum =

More information

Chapter 2: Programming Concepts

Chapter 2: Programming Concepts Chapter 2: Programming Concepts Objectives Students should Know the steps required to create programs using a programming language and related terminology. Be familiar with the basic structure of a Java

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Review of the C Programming Language

Review 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 information

Applied 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 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 information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

M.CS201 Programming language

M.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 information

C++ Reference NYU Digital Electronics Lab Fall 2016

C++ Reference NYU Digital Electronics Lab Fall 2016 C++ Reference NYU Digital Electronics Lab Fall 2016 Updated on August 24, 2016 This document outlines important information about the C++ programming language as it relates to NYU s Digital Electronics

More information

Functions and Recursion

Functions 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 information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

More information

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 12 Pointers and Arrays 1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements. This leads to an alternative way of processing arrays in which pointers

More information

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators Basic C Elements Chapter 12 Variables and Operators Original slides from Gregory Byrd, North Carolina State University! Variables named, typed data items! Operators predefined actions performed on data

More information

Chapter 6. Decision and Control Statements

Chapter 6. Decision and Control Statements Chapter 6. Decision and Control Statements Once a decision was made, I did not worry about it afterward. Harry Truman Calculations and expressions are only a small part of computer programming. Decision

More information