 #include  Using a directive to include a header file  Stdio.h = standard input output header file.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Dynamic memory allocation
C Language.
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Programming Languages and Paradigms The C Programming Language.
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
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.
Pointers in C Rohit Khokher
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
CSCI 171 Presentation 11 Pointers. Pointer Basics.
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
POINTER Prepared by MMD, Edited by MSY1.  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference.
Arrays. INTRODUCTION TO ARRAYS Just as with loops and conditions, arrays are a common programming construct and an important concept Arrays can be found.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Guide To UNIX Using Linux Third Edition
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Pointers Applications
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
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”); }
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 14P. 1Winter Quarter Pointers Lecture 14.
CECS 121 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
C Programming – Part 6 File Input and Output
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
CECS 130 EXAM 2.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data type.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
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;
/* 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.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
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);
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers *, &, array similarities, functions, sizeof.
C LANGUAGE Characteristics of C · Small size
CECS 121 Final Test.  Function Prototype Syntax return-type function_name ( arg_type arg1,..., arg_type argN);  Function Prototypes tell you the data.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
CECS 130 Mid-term Test Review Provided by REACH – Resources for Academic Achievement Presenter: [REACH Tutor]
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
CECS 121 Midterm Review Presented by REACH (If you have not signed the attendance sheet, please do so now!)
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Computer Science 210 Computer Organization
Quiz 11/15/16 – C functions, arrays and strings
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
Module 2 Arrays and strings – example programs.
Computer Science 210 Computer Organization
Chapter 14 - Advanced C Topics
EECE.2160 ECE Application Programming
Outline Defining and using Pointers Operations on pointers
CECS 130 Midterm Exam Review Spring 2019
Programming Languages and Paradigms
Presentation transcript:

 #include  Using a directive to include a header file  Stdio.h = standard input output header file

 Definition: Escape sequences are specially sequenced characters used to format output  \” Ex: printf(“ \ “This is quoted text \ “ “)  \’ Ex: printf(“ \n A single quote looks like \’ \n”);  \* *\ Comment Block

To declare a constant (read only) value: const int x = 20 const float PI = 3.14

TYPESIZEVALUES bool1 bytetrue (1) or false (0) char1 byte‘a’ to‘z’, ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, and so on int4 bytes-2,147,483,648 to 2,147,483,647 short2 bytes-32,768 to 32,767 long4 bytes-2,147,483,648 to 2,147,483,647 float4 bytes+ - (1.2 x 10^-38 to 3.4 x 10^38) double8 bytes+- (2.3 x 10^-308 to -1.7 x 10^308)

Variables and Constants To declare a constant (read only) value: const int x = 20 const float PI = 3.14 What is wrong with this code?

Variables and Constants Are the following valid names for a variables in C: 1) _name 1) $student_number 1) #salary 1) 9pins+1 and 1) First-name 1) TheIncrediblyEdiblySpiderManWithTheVeryLongNameOfMoreTha n50Characters

 Can you explain what the code is doing?

 Syntax: scanf(“conversion specifier”, variable);

Do you know the answers to these?  A. !( 1 || 0 )  B. !( 1 || 1 && 0 )  C. !( ( 1 || 0 ) && 0 )

 A. !( 1 || 0 ) ANSWER: 0  B. !( 1 || 1 && 0 ) ANSWER: 0 (AND is evaluated before OR)  C. !( ( 1 || 0 ) && 0 ) ANSWER: 1 (Parenthesis are useful)

Logical operators: Syntax:

Else if:

 Can you write code that will ask a user to enter a number 1, 2, or 3 and print out the following:

 while ( condition ) { Code to execute while the condition is true }  Quiz: Can you write a program that prints x while x increments from 0 to 10?

 do { } while ( condition );  What is the main difference between “Do while” and “while”?

 while ( condition ) { Code to execute while the condition is true }  do { } while ( condition );  Do{} while() executes code at least once!

 Use when the number of iterations is already known  Syntax: for ( variable initialization; condition; variable increment/decrement) { Code to execute while the condition is true }

#include int main() { int x; for ( x = 0; x < 10; x++ ){ printf( "%d\n", x ); } getchar(); }

 Write a program using a FOR Loop to display all of the multiples of 5 from 0 to 100.

#include int main() { int x; for ( x = 0; x < =20; x++ ) { printf( "%d\n", x*5 ); } getchar(); }

x++; x--; Postfix ++x; --x; Prefix main() {int x = 0; int y = 0; printf(“\n The value of y is %d \n”, y++); printf(“\n The value of x is %d \n”, ++x); } Answer: 0 1

 Use to manipulate flow in loops  What does a Break statement do when executed within a loop?  What does a Continue statement do when executed within a loop?

#include main() { int x; for ( x = 10; x >5; x-- ) { if (x==7) break; } printf( “\n %d \n ”, x ); } #include main() { int x; for ( x = 10; x >5; x-- ) { if (x==7) continue; printf( “\n %d \n ”, x ); }

 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?

 Where are function prototypes located in the program?  Answer: before the main(){} Function!  Function Definitions are self contained outside of the main(){} function

#include int mult ( int, int); int main() { int x; int 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(); } int mult (int a, int b) { return a * b; }

#include printNumber(); main() { int x; printNumber(x); } void printNumber() { printf(“\n The number is %d \n”, x) }

#include void printNumber( int x); main() { int x; printNumber(x); } void printNumber(int y) { printf(“\n The number is %d \n”, y); }

Functions - Example

#include void printNumbers(); int iNumber; 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); }

 Variable scope defines the life time of a variable  Local Scope: defined within functions and loses scope after function is finished.  Global Scope: defined outside of functions and can be accessed by multiple functions

Can you write code that asks a user to: 1. Input 4 integers. 1. Adds the numbers together in one function. 1. Multiplies them in another. 1. Prints out the absolute difference between the sum and product? 1. The user should have to do this 5 times.

 Syntax (One-dimensional Array): array_type array_name [number-of-elements];  Two Dimensional Array array_type array_name [#ROWS] [#COLUMNS];

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

Array index

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

 Can you add code to print out the values of the program below? #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]); }

Arrays - Example

Multidimensional Arrays

Multidimensional Arrays - Example

 How do you search through an array?

Array Search - Answer

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.

Array Sort - Answer

Strings Since no strings inc C, strings are represented as arrays of chars. Strings are always terminated with a null character, literally a '\0' character. Syntax: char my_name[my_name_length+1];

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

Data Structures A group of data elements goruped together under one name. Syntax: To create a single structure use this syntax: To Access a struct member use the dot (.) operator. struct type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; }; struct_name name_of_single_strcuture; name_of_single_structure.name_of_variable ;

Data Structures typedef can also be used to define struct as follows: Example: Typedef struct { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; } struct_name; typedef struct { char name[64]; char course[128]; int age; int year; } student;

Data Structures Example:

Data Structures If you wish to have a pointer to structure to access its information, use -> operator:

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!

Examples of pointer declarations: FILE *fptr; //fptr is a pointer to a file int *a; //a is a pointer to a int float *b; //b is a pointer to a float char *c; //c is a pointer to a char 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.

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

Reference operator (&) Dereference operator (*)

Example:

Dynamic memory allocation in C: The process of allocating memory during program execution is called dynamic memory allocation. Dynamic memory allocation functions in C: C language offers 4 dynamic memory allocation functions. They are, 1.malloc() 1.calloc() 1.realloc() 1.free()

malloc(): Used to allocate space in memory during the execution of the program. Does not initialize the memory allocated during execution. It carries garbage value. Returns null pointer if it couldn’t able to allocate requested amount of memory.

realloc (): Modifies the allocated memory size by malloc() and calloc() functions to new size. If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block. calloc (): Similar to malloc () except that calloc() initializes the allocated memory to zero but malloc() doesn’t.

free (): Frees the allocated memory by malloc(), calloc(), realloc () functions and returns the memory to the system. sizeof (): Gives the amount of storage, in bytes, required to store an object of the type of the operand.

Please enter how long your name is: 21 Please enter your name: David OUTPUT: Hello David Please enter how long your name is: -7 OTPUT: 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.

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

 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);

Using fscanf()

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

Answer

 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 in your final Exam from REACH

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

Kelly11/12/866Louisville Allen04/05/7749Atlanta Chelsea03/30/9012Charleston How many fields are there? How many records are there? How many bytes are there in the first record? How many bits are there in “Kelly”? How many fields are there? How many records are there? How many bytes are there in the first record? How many bits are there in “Kelly”?