CECS 121 Final Test.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
Strings.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointers in C Rohit Khokher
CSCI 171 Presentation 11 Pointers. Pointer Basics.
 #include  Using a directive to include a header file  Stdio.h = standard input output header file.
Kernighan/Ritchie: Kelley/Pohl:
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
Chapter 10.
 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.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen() 
CECS 121 EXAM 1. /* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
 data_type array_name [number-of-elements];  Two Dimensional Array array_type array_name [number_of_ROWS][number_of_COLUMNS];
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CECS 121 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Pointers OVERVIEW.
C Programming – Part 6 File Input and Output
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CECS 130 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 Pointers and Strings Chapter 5 2 What You Will Learn...  How to use pointers Passing arguments to functions with pointers See relationship of pointers.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen() 
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CECS 130 Final EXAM.  #include  Using a directive to include a header file  Stdio.h = standard input output header file.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Old Material escape sequences operator precedence printf() scanf() if() switch case &&,|| while, do-while, ++, -- functions New Material 1-D arrays string.
CECS 130 EXAM 1.  int main() { printf (“%c %c \n", 'a', 65); printf ("%d %ld\n", 1977, L); printf (" %10d \n", 1977); printf ("%010d \n", 1977);
Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CECS 130 Mid-term Test Review Provided by REACH – Resources for Academic Achievement Presenter: [REACH Tutor]
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
CECS 121 Midterm Review Presented by REACH (If you have not signed the attendance sheet, please do so now!)
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
User-Written Functions
CECS 130 Mid-term Test Review
Quiz 11/15/16 – C functions, arrays and strings
Arrays in C.
Outline Defining and using Pointers Operations on pointers
Engineering Problem Solving with C++, Etter
Arrays Arrays A few types Structures of related data items
CECS 130 Midterm Exam Review Spring 2019
Presentation transcript:

CECS 121 Final Test

 Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type returned by the function, the data type of parameters, how many parameters, and the order of parameters  Function definitions implement the function prototype  Where are function prototypes located in the program?  Where do you find function definitions?

 Function Prototypes are placed after preprocessor directives and before the main(){} function.  Function Definitions are self contained outside of the main(){} function

#include int mult ( int, int ); main() { int x,y; printf( "Please input two numbers to be multiplied: " ); scanf( "%d", &x ); scanf( "%d", &y ); printf( "The product of your two numbers is %d\n", mult( x, y ) ); getchar(); // To pause the screen, same like system(“pause”) } int mult (int x, int y) // Make sure not to end this with a semicolon { return(x * y); }

#include void print_char( char *, int); main() { char name[20]=“REACH CRC”; print_char(name, 3); // The name of the array is a pointer to that array getchar(); } void print_char (char *nameStringArray, int x) { printf(“The character specified is: %c”, nameStringArray[x-1]); }

#include void printReportHeader(); main() { printReportHeader; } void printReportHeader() { printf(“\n Column1\tColumn2\tColumn3\tColumn4 \n”); }

#include void printReportHeader(); main() { printReportHeader; // Should be corrected to printReportHeader() } void printReportHeader() { printf(“\n Column1\tColumn2\tColumn3\tColumn4 \n”); }

 Variable scope defines the life time of a variable  Local Scope: defined within functions and loses scope after function is finished. Can reuse in other functions (ex. p.123)  Global Scope: defined outside of functions and can be accessed by multiple functions

#include void printNumbers(); int iNumber; // This is a global variable reachable from any place in code main() { int x; for(x=0, x<10,x++){ printf(“\n Enter a number:”); scanf(“%d”, &iNumber); printNumbers(); } void printNumbers() { printf(“\n Your number is: %d \n”, iNumber); }

 Can you declare a one-dimensional array made up of 10 integers?  data_type name[size_of_array]  Answer: int iArray[10];  How to declare an Array  int iArray[10]; // Array of 10 integers  float fAverages[30]; // Array of 10 floats  char cName[19];// 18 characters and 1 null character

 Why do we initialize? Because memory spaces may not be cleared from previous values when arrays are created  Can initialize an array directly  Example int iArray[5]={0,1,2,3,4};  Can initialize an array with a loop such as for()

#include main() { int x; int iArray[5]; for( x=0; x < 5 ; x++) { iArray[x] = 0; }

 Can you add code that will print out the value of each element of iArray? #include main() { int x; int iArray[5]; for( x=0; x < 5 ; x++) { iArray[x] = 0; }

#include main() { int x; int iArray[5]; for( x=0; x < 5 ; x++) { iArray[x] = 0; } for(x=0 ; x<5; x++) { printf(“\n The value of iArray index %d is %d \n”, x, iArray[x]); }

 How do you search through an array?

#include main() { int x; int iValue; int iFound = -1; int iArray[5]; for( x=0; x < 5 ; x++) iArray[x] = (x+x); printf(“\n Enter value to search for:”); scanf(“%d”, &iValue); for(x=0 ; x<5; x++) { if( iArray[x] ==iValue){ iFound =x; break; ) } if(iFound >-1) printf(“\n I found your search value in element %d \n”, iFound); else printf(“\n Sorry, your search value was not found \n”); }

 Declaring:  data_type name[size_dim_1][size_dim_2] ▪size_dim_1 is known as “ROW” count. ▪size_dim_2 is known as “COLUMN” count.  int double_array[20][10]  Accessing:  printf(“Element 2,5 is: %d”, double_array[2][5]);

 Initializing: Use a second, nested FOR() loop #include main() { int x, y, double_array[10][20]; for( x=0; x < 10 ; x++) // Outer loop goes with ROW count { for(y=0 ; y<20; y++) // Inner loop goes with Column count { double_array[x][y] = 0; }

 Passing to a function: #include void custom_func(int [ ][2]); // Multi dimensional arrays must have a bound main() { int double_array[2][2]={{1,2},{3,4}}; custom_func (double_array); system(“pause”); } void custom_func (int temp[ ][2]) { printf(“Test: %d, %d, %d”, temp[0][0],temp[0][1],temp[1][1]); } OUTPUT: Test: 1, 2, 4

Lect 14P. 20  Pointers are variables that contain memory addresses as their values.  A variable name directly references a value.  A pointer indirectly references a value. Referencing a value through a pointer is called indirection.  A pointer variable must be declared before it can be used.  ALL Arrays are Pointers!

Lect 14P. 21  Examples of pointer declarations: FILE *fptr; //fptr is a pointer to a file int *a; //a is a pointer to a file float *b; //b is a pointer to a file char *c; //c is a pointer to a file  The asterisk, when used as above in the declaration, tells the compiler that the variable is to be a pointer, and the type of data that the pointer points to, but NOT the name of the variable pointed to.

Lect 14P. 22Winter Quarter  Consider the statements: #include int main ( ) { FILE *fptr1, *fptr2 ; /* Declare two file pointers */ int *aptr ; /* Declare a pointer to an int */ float *bptr ; /* Declare a pointer to a float */ int a ; /* Declare an int variable */ float b ; /* Declare a float variable */ return 0; }

Lect 14P. 23Winter Quarter  When is & used?  When is * used?  & -- "address operator" which gives or produces the memory address of a data variable  * -- "dereferencing operator" which provides the contents in the memory location specified by a pointer

Lect 14P. 24Winter Quarter  If instead of passing the values of the variables to the called function, we pass their addresses, so that the called function can change the values stored in the calling routine. This is known as "call by reference" since we are referencing the variables.  The following shows a swap function modified from a "call by value" to a "call by reference". Note that the values are now actually swapped when the control is returned to main function.

 Unary operator (&) – “Address of” int x=10; int *xptr; xptr = &x; //xptr now points to x  Indirection operator (*) int x, y = 10; int *xptr; xptr = &y; x = *xptr //copies contents of y into x

Lect 14P. 26 #include void swap ( int *, int *) ; int main ( ) { int a = 5, b = 6; printf("a=%d b=%d\n",a,b) ; swap (&a, &b) ; printf("a=%d b=%d\n",a,b) ; return 0 ; } void swap( int *a, int *b ) { int temp; temp= *a; *a= *b; *b = temp ; printf ("a=%d b=%d\n", *a, *b); } Output: a=5 b=6 //printed from main a=6 b=5 //printed from inside swap a=6 b=5 // printed from main after calling swap function

 To avoid accidently changing the value the pointer points to: Use const void custom(const int *); main(){} void custom(const int *) { }

 Strings are character arrays that have a special set of functions for handling their data as complete sentences or “strings” of characters.  Since a string is an array it is also a pointer.  Character literals are expressed with a single quote: char example=‘a’;  String literals are expressed with double quote: char example[10]=“REACH”;

 When determining the maximum length your string variable needs to be it is important to consider a NULL Character: “\0” char example[10]=“REACH”; example[0] -> R example[1] -> E example[2] -> A example[3] -> C example[4] -> H example[5] -> \0

#include int main () { char szInput[256]; printf ("Enter a sentence: "); gets (szInput); printf ("The sentence entered is %u characters long.\n",(unsigned)strlen(szInput)); System(“pause”); return 0; } Output: Enter sentence: just testing The sentence entered is 12 characters long.

#include int main () { int i=0; char str[]="Test String.\n"; char c; while (str[i]) { c=str[i]; putchar (tolower(c)); i++; } return 0; } Output: test string. For toupper() will be same case, just replace tolower() by toupper()

#include int main () { char str1[]="Sample string"; char str2[40]; char str3[40]; strcpy (str2,str1); strcpy (str3,"copy successful"); printf ("str1: %s\nstr2: %s\nstr3: %s\n",str1,str2,str3); return 0; } Output: str1: Sample string str2: Sample string str3: copy successful

#include int main () { char str[80]; strcpy (str,"these "); strcat (str,"strings "); strcat (str,"are "); strcat (str,"concatenated."); puts (str); return 0; } Output: these strings are concatenated.

#include int main () { char szKey[] = "apple"; char szInput[80]; do { printf ("Guess my favourite fruit? "); gets (szInput); } while (strcmp (szKey,szInput) != 0); puts ("Correct answer!"); return 0; } Output: Guess my favourite fruit? orange Guess my favourite fruit? Apple Correct answer!

/*This example searches for the "simple" substring in str and replaces that word for "sample".*/ #include int main () { char str[] ="This is a simple string"; char * pch; pch = strstr (str,"simple") ; /* returns a pointer to first occurrence of “simple” in str*/ strncpy (pch,"sample",6); // copies 6 characters from source->pch puts (str); return 0; } Output: This is a sample string

Can you make a program to sort an array of 10 integers either ascending or descending order? Consider you have the array[10]={7,8,5,3,0,3,2,1,4,10} Write a code to do the sorting.

#include int main(){ int array[10]={7,8,5,3,0,3,2,1,4,10}; int temp=0,i,j; for(i=0;i<10;i++) // print the array before sorting printf(“%d\n”,array[i]); for(i=0;i<10;i++) for(j=0;j<10;j++) { if(array[i] */ { temp=array[i]; // This will do the swapping array[i]=array[j]; array[j]=temp; } for(i=0;i<10;i++) // print the array after sorting printf(“%5d “,array[i]); getchar(); return 0; }

 Can you modify the previous code to pass the array to a function that will sort the array and print the sorted array in main.

#include void sortArray(int [ ],int size); int array[10]={7,8,5,3,0,3,2,1,4,10}; int temp=0,i,j; int main(){ for(i=0;i<10;i++) printf(“%d\n”,array[i]); sortArray(array,10); for(i=0;i<10;i++) printf(“%5d”,array[i]); getchar(); return 0; } void sortArray(int passedArray[ ],int arraySize) { for(i=0;i<arraySize;i++) for(j=0;j<arraySize;j++) { if(passedArray[i]<passedArray[j]) { temp=passedArray[i]; passedArray[i]=passedArray[j]; passedArray[j]=temp; } Calling the function sortArray(array,10) is equivalent to sortArray(&array[0],10)

 Classes are general models from which you can create objects  Classes have data members either data types or methods  Classes should contain a constructor method and a destructor method  See handout for example of a program that utilizes a class

class ClassName { memberList }; memberList can be either data member declarations or method declarations

Class Bow { //data member declarations string color; bool drawn; int numOfArrows; Bow(string aColor); //constructor ~Bow(); //destructor //methods void draw(); int fire(); };

Return_type ClassName::methodName(argumentList) { methodImplementation }

//draws the bow Void Bow::draw() { drawn = true; cout<< “The “<<color<<“bow has been drawn.”<<endl; }

Please enter how long your name is: 21 Please enter your name: Nawaf Hello Nawaf Please enter how long your name is: -7 Failed allocation memory

int *n; int * n1; n=( int * ) calloc(5, sizeof(int)); // Reserves a block of memory for 5 integers //Decide you need to reallocate more memory later in the program n1= (int *) realloc(n, 10 * sizeof(int));//allocate 10 integers instead of 5 if (n1!=NULL) { n=n1; } else printf("Out of memory!"); realloc() returns null if unable to complete or a pointer to the newly reallocated memory.

 Function declaration  Function definition  Function call

#include using namespace std; int add(int, int); int main(void) { int number1, number2; cout << “Enter the first value to be summed:”; cin >> number1; cout << “\nEnter the second:”; cin >> number2; cout << “\n The sum is: “ << add (number1, number2) <<endl; } int add(int a, int b){return a+b;}

 Write a function, called multiply that multiplies two numbers and returns the result

Do you know the syntax for each of these, used to read and write to data files?  Pointers: think of it as the memory address of the file  fopen()  fclose()  fscanf()  fprintf()

 fopen() returns a FILE pointer back to the pRead variable #include Main() {FILE *pRead; pRead = fopen(“c:\\folder1\\folder2\\file1.dat”, “r”); if(pRead == NULL) printf(“\nFile cannot be opened\n”); else printf(“\nFile opened for reading\n”); fclose(pRead); }

int main () { FILE * pFile; char c; pFile=fopen("alphabet.txt","wt"); for (c = 'A' ; c <= 'Z' ; c++) { putc (c, pFile);//works like fprintf } fclose (pFile); return 0; }

 Pretty basic.  Always close files when you use fopen.

 Reads a single field from a data file  “%s” will read a series of characters until a white space is found  can do fscanf(pRead, “%s%s”, name, hobby);

#include Main() { FILE *pRead; char name[10]; pRead = fopen(“names.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else printf(“\nContents of names.dat\n”); fscanf( pRead, “%s”, name ); while( !feof(pRead) ) { // While end of file not reached printf( “%s\n”, name ); // output content of name fscanf( pRead, “%s”, name ); // scan from file next string } fclose(pRead); }

Kelly11/12/866Louisville Allen04/05/7749Atlanta Chelsea03/30/9012 Charleston Can you write a program that prints out the contents of this information.dat file?

#include Main() { FILE *pRead; char name[10]; char birthdate[9]; float number; char hometown[20]; pRead = fopen(“information.dat”, “r”); if( pRead == NULL ) printf( “\nFile cannot be opened\n”); else fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); while( !feof(pRead) ) { printf( “%s \t %s \t %f \t %s\n”, name, birthdate, number, hometown ); fscanf( pRead, “%s%s%f%s”, name, birthdate, &number, hometown ); } fclose(pRead); }

 The fprintf() function sends information (the arguments) according to the specified format to the file indicated by stream. fprintf() works just like printf() as far as the format goes.printf()

#include Main() { FILE *pWrite; char fName[20]; char lName [20]; float gpa; pWrite = fopen(“students.dat”,”w”); if( pWrite == NULL ) printf(“\nFile not opened\n”); else printf(“\nEnter first name, last name, and GPA ”); printf(“separated by spaces:”); scanf(“%s%s%f”, fName, lName, &gpa); fprintf(pWrite, “%s \t %s \t %.2f \n”, fName, lName, gpa); fclose(pWrite); }

 Can you write a program that asks the user for their  Name  Phone Number  Bank account balance And then prints this information to a data file called accounts.dat ?

 Good Luck from REACH in your Test.

 TEXTBOOK RESOURCE: C Programming for the Absolute Beginner 2 nd Edition by Michael Vine 