FUNCTIONS.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

C Language.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Multi-Dimensional Arrays Arrays that have more than one index: Example of differences between basic data types and arrays using integers: Basic integer:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Pointers and Arrays Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Computer Science 210 Computer Organization
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Computer Programming BCT 1113
C Programming Tutorial – Part I
Will these print the same thing?
Functions, locals, parameters, and separate compilation
Review of C… The basics of C scanf/printf if/elseif statements
ICS103 Programming in C Lecture 3: Introduction to C (2)
Module 4 Functions – function definition and function prototype.
Pointers.
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
INC 161 , CPE 100 Computer Programming
Module 2 Arrays and strings – example programs.
Programmazione I a.a. 2017/2018.
Arrays in C.
Lecture 6 C++ Programming
Formatted and Unformatted Input/Output Functions
C-Programming, continued
Computer Science 210 Computer Organization
Chapter 5 - Functions Outline 5.1 Introduction
Arrays, For loop While loop Do while loop
Object Oriented Programming COP3330 / CGS5409
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
7 Arrays.
Chapter 14 - Advanced C Topics
Arrays Kingdom of Saudi Arabia
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
EKT150 : Computer Programming
Lecture 18 Arrays and Pointer Arithmetic
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Functions with arrays.
Outline Defining and using Pointers Operations on pointers
Pointers.
MSIS 655 Advanced Business Applications Programming
Building Java Programs
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
7 Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Suggested self-checks: Section 7.11 #1-11
Arrays Arrays A few types Structures of related data items
Exercise Arrays.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Arrays.
Pointers Chapter 11 Copyright © 2008 W. W. Norton & Company.
Lecture 14: Problems with Lots of Similar Data
Programming Languages and Paradigms
C++ Array 1.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Introduction to C Programming
ICS103: Programming in C 6: Pointers and Modular Programming
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

FUNCTIONS

What is a function? 1. A piece of code that performs an operation that can be used by the main program or by other functions 2. A sophisticated if –else statement that always goes into the else part and never into the if part Just some stuff the compiler uses and the user never has to use or see 4. An out of this world thrill ride at the Walt Disney World Resort in Orlando, FL!!!

Purpose of functions Avoid re-inventing the wheel Using existing functions as building-blocks to create new programs Make programs easier to understand and to write Sometimes a program uses a section of code over and over again, using a function will avoid having to rewrite code segments

Function Definitions return-value-type function-name( parameter-list ) { definitions statements } function-name: any valid identifier - using a meaningful name. return-value-type: data type of the result. void - indicates that the function returns nothing parameter-list: comma-separated list Specifies the parameters received by the function when it is called. Function header

Function Prototypes Format return-value-type function-name( parameter-list ); Parameter names are not necessarily included in the function prototype. A function prototype is used to validate functions The type of data returned by the function The number of parameters the function expected to receive The types of the parameters The order in which these parameters are expected.

Function Calls Invoking functions (by a function call) Provide function name and arguments (data) Function returns results #include<stdio.h> #define SIZE 5 int sumValue( int x[ ], int size ); int main( void ) { int a[SIZE] = {1, 2, 3, 4, 5}; int total = 0; total = printf(“%d\n”, total); return 0; } int k, sum = 0; for (k = 0; k < size; k++) { sum += x[k]; return sum; sumValue( a, SIZE ); /* call sumValue( ); passing array a and SIZE */ What is the total? Passing an int to a floating point number, the value is not changed. Passing a floating point number to an int, the fractional part of the value is truncated. Should not pass an int to a pointer to int. The function prototype, function header and function calls should all agree in the number, type, and order of arguments and parameters, and in the type of return value. int sumValue( int x[ ], int size )

Functions Some notes: The function myFunction that returns an integer and takes in a double array called square and an integer called arraylength has the following prototype: int myFunction (double square[], int arraylength); 2. When this function is called from main() (or from another function), the call statement does not include the ‘[]’ for the array nor does it include the data types (i.e. double and int), i.e.: returnvalue = myFunction(square, arraylength); 3. The function definition has the following syntax, in this case returns as int: int myFunction (double square[], int arraylength) { perform actions; return somevalue; }

ARRAYS

Arrays An array is a data structure consisting of related data items of the same type. Stored in a group of memory locations Defining arrays int arrayName[ 100 ]; Examples int a[5]; float b[120], x[24]; … a[0] 5 memory 10 15 3 23 a[1] a[2] a[3] a[4] Name of the array Specifying the type of each element The number of the elements

Referring to Array Elements Formally called a subscript or an index Format arrayName[ position number ] First element at position 0 Last element at position size – 1 The i-th element of array a is referred to as a[i-1] A subscript must be an integer or an integer expression. Avoid to referring to an element outside the array bounds. Array elements are like normal variables. Passing an array element to a function by value. Passing a whole array to a function passes by reference.

1. num=2.00 num=2.00 num=2.50 num=2.25 num=4.00 2. num=2.00 num=1.00 #include <stdio.h> int main() { float num[5]; int i; for (i=0;i<5;i++) num[i] = 0.; } num[0] = 2.; num[4] = 4.; for(i=1;i<4;i++) num[i] = (num[i+1]+num[i-1])/2.; for(i=0;i<5;i++) printf("num=%.2f\n", num[i]); 1. num=2.00 num=2.00 num=2.50 num=2.25 num=4.00 2. num=2.00 num=1.00 num=0.50 num=2.25 num=4.00 3. num=2.00 num=1.00 num=1.50 num=2.25 num=0.00 4. num=0.00 num=1.00 num=0.50 num=2.25 num=4.00

Passing arrays to functions Some notes: Whole arrays are passed by reference – which means that when they are changed in the function, that change is also seen in main() – or in the function from which it was called Related to #1 above, the address of the first element of an array is passed to a function 3. Array elements are passed by value 4. Typically the size of the array (unless it is a character array with a terminating character, i.e. string) is passed to the function because functions do not know what the size of an array is

What will this print out? #include <stdio.h> void change(int array[], int val); int main(void) { int val = 3; int array[1] = {3}; change(array, val); printf(“array=%d, val=%d”,array[0],val); } void change(int array[], int val) int i; array[0] = array[0]*2; val = val * 2; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6

In the previous example, array was passed by ____1______, while val was are passed by ___2_____? 1. reference, value 2. value, reference 4. Oh shoot, don’t know, I’d better ask Garvin’s other half as she is the one who knows everything! 3. Yo mamma, yo daddy

What will this print out? #include <stdio.h> void change(int array, int val); int main(void) { int val = 3; int array[1] = {3}; change(array[0], val); printf(“array=%d, val=%d”,array[0],val); } void change(int not_an_array, int val) not_an_array = not_an_array*2; val = val * 2; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6 Notice that the function no longer takes in a whole array, but an array element – which is passed by value

What will this print out? #include <stdio.h> int change(int array[], int val); int main(void) { int val = 3; int array[1] = {3}; val = change(array, val); printf("array=%d, val=%d",array[0],val); } int change(int array2[], int val) array2[0] = array2[0]*2; val = val * 2; return val; 1. array=6, val=6 2. array=6, val=3 3. array=3, val=3 4. array=3, val=6

Multi-Dimensional Arrays Arrays that have more than one index(subscript): Basic integer: int a; -- Only has one value associated with it at one time -- Unless specified otherwise, a basic variable is passed to a function by value 1D array: int a[SIZE] -- Has a series of values associated with it: a[0], a[1], a[2], ….a[SIZE-1] 2D array: int a[ROWSIZE][COLSIZE] a[0][0], a[0][1], a[0][2], …a[0][COLSIZE-1], a[1][0],… Multi-D array: int a[SIZE][SIZE][SIZE]… Arrays are passed by reference, array elements are passed by value

Referring to Two-Dimensional Array Elements Format arrayName[ rowIndex ][ colIndex ] Both row and column indices start from 0, and must be an integer or an integer expression. The accessed element of the array is on Row rowIndex and Column colIndex The names of the elements in the i-th row all have a first suscript/index of i. The names of the elements in the j-th column all have a second suscript/index of j.

Passing Two-Dimensional Arrays to Functions Defining the function: The function’s parameter list must specify that a two-dimensional array will be received. #define ROWSIZE 10 #define COLSIZE 10 void oneFunc( int ary[ ] [ COLSIZE ] , int rowSize, int colSize ) Calling the function To pass an array argument to a function, specify the name of the array without any brackets int anArray[ ROWSIZE ][ COLSIZE ] = {{0}}; oneFunc( anArray, ROWSIZE, COLSIZE ); Array size usually passed to function Specifies the number of columns of the array parameter, which is required. The number of rows of the array parameter is NOT required. The header of the function Normally, also pass the numbers of rows and columns of the array argument.

STRINGS: A character array with a terminating null character ‘\0’ Various ways of defining a character array: char chararray[]=“biscuits”; char chararray[] = {‘b’,’i’,’s’,’c’,’u’,’i’,’t’,’s’,’\0’}; char chararray[80];

Some more string stuff: Strings are character arrays (example): #include <stdio.h> #include <string.h> int main() { char sentence[80]; /* large array length */ int i; sentence[0] = 'B'; sentence[1] = 'y'; sentence[2] = 'e'; sentence[3] = '\0'; printf("%s", sentence); /* prints Bye */ for (i = 0; i < strlen(sentence); i++) printf("%c", sentence[i]); /* prints Bye */ } Caution when using scanf with strings: scanf(“%s”, string) /* no & is needed w/ %s*/ scanf(“%c”, &char) /* & is needed with %c */

POINTERS, PASS BY REFERENCE and PASS BY VALUE

Pointer Variables Contain memory addresses as their values Normal variables contain a specific value (directly reference a value) Pointers contain address of a variable that has a specific value (indirectly reference a value) Referencing a value through a pointer is called indirection (or dereferencing)

Call(Pass)-by-Value Copy of argument passed to function Changes in function do not effect original Use when function does not need to modify argument To avoid accidental changes Variables of type int, float, double, char are passed to a function by value. Elements of arrays are passed to a function by value.

Let’s review pass by value: #include <stdio.h> void doSomething(int a, int b); int main() { int a = 1, b =0; doSomething(a,b); printf(“a=%d, b=%d ", a, b); } void doSomething(int a, int b) a = 7; b = 8; Is this going to print: 1. a=7, b=8 2. a=1, b=0

Illustrate what is going on with a “memory model”: #include <stdio.h> void doSomething(int a, int b); int main() { int a = 1, b =0; doSomething(a,b); printf(“a=%d, b=%d ", a, b); } void doSomething(int a, int b) a = 7; b = 8; Variable Address Value in memory a b 500 501 1 When passed to function doSomething, the values are passed, not memory address: Variable Address Value in memory a b 550 551 1 7 8 Different address The modification was only for memory addresses 550 and 551, but when main prints a and b, it prints values at 500 and 501

What if we wanted main to print out the modified values of a and b? Need to know each memory address! Need to use pointers!

What is the output now?: #include <stdio.h> void doSomething(int *a, int *b); int main() { int a = 1, b =0; doSomething(&a,&b); printf(“a=%d, b=%d ", a, b); } void doSomething(int *a, int *b) *a = 7; *b = 8; Is this going to print: 1. a=7, b=8 2. a=1, b=0

Illustrate what is going on with a “memory model”: #include <stdio.h> void doSomething(int *a, int *b); int main() { int a = 1, b =0; doSomething(&a,&b); printf(“a=%d, b=%d ", a, b); } void doSomething(int *a, int *b) *a = 7; *b = 8; Variable Address Value in memory a b 500 501 1 When passed to function doSomething, the ‘&’ means addresses are passed as values: Variable Address Value in memory a b 550 551 500 501 Original address stored as a value Different address a and b are the values of the addresses that were passed into the function, Using *a and *b allows you to modify the original values of a and b at location 500 and 501 (this process is called dereferencing).

Call(pass)-by-Reference Passes original argument Changes made to parameter in function effect original argument Only used with trusted functions Arrays, strings, and pointers are passed to a function by reference.

A little more on pointers Declaring a pointer needs a *: int * xPtr; This means xPtr should store an address If xPtr gets changed the address gets changed However, if *xPtr gets changed, that means xPtr is now “pointing” to that value Passing the address (i.e. pass by reference) of a regular variable needs an & in front of it (like scanf). int variable = 7; /* stores a value */ printf(“%p”,&variable); /* prints out address */

Quick example that may clear up some confusion: int variable = 10; int *varPtr; varPtr = &variable; /* varPtr pointed to the variable address */ variable =100; printf(“%d, %d”, *varPtr, variable); variable = 200; *varPtr = 150; Answer: 100, 100 150, 150

(FILE I/O or FILE INPUT/OUTPUT) C File Processing (FILE I/O or FILE INPUT/OUTPUT)

Why Using Files? Storage of data in variables and arrays is temporary (memory) Data lost when a program terminates. Files are used for permanent retention of data Stored on secondary storage devices Disks Optical disks (CDs, DVDs) USB memory key

Opening a File Define a FILE pointer called rfPtr; FILE *rfPtr; The fopen function links a FILE pointer to the file to read: rfPtr = fopen(“sData.txt”, “r”); Or write: rfPtr = fopen(“sData.txt”, “w”); fopen Takes two arguments Filename -- file to open (“sData.txt”) File open mode -- “r” or “w” – there are others as well If open fails, NULL returned (i.e. there is nothing there)

Reading a file and writing to a file Once a file is open, you can read or write to that file: To read a file: fscanf(rfPtr, “%f”, &variable); Like scanf, except reads from file instead of screen To write to a file fprintf(rfPtr, “%f”, variable); Like printf except prints to file instead of screen Check to see if end of file is reached: feof(rfPtr) Closing the file fclose(rfPtr);

What does this code do? #include <stdio.h> int main(void) { FILE *fp; int i, n=10; fp = fopen("data1", "w"); for (i=0;i<n;i++) fprintf(fp,“%d\n”, i+1); } fclose(fp); return 0; 1. This prints to file data1 2. This prints to the screen 3. This prints to file fp 4. This reads from file data1

What does this code print out to output.dat when the contents of data1 is: 0 1 2 3 4 5 #include <stdio.h> int main(void) { FILE *fr, *fp; int i=0; fr = fopen("data1", “r"); fp = fopen(“output.dat”, “w”); fscanf(fr, “%d”, &i); while (!feof(fr)) fprintf(fp,“%d\n”, i+1); fscanf(fr,“%d”, &i); } fclose(fr); fclose(fp); return 0; 1. 1 2 3 4 5 6 2. 1 2 3 4 5 6 3. 0 1 2 3 4 5 4. 0 1 2 3 4 5