Computer Programming: 8th Week Pointers

Similar documents
Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

BİL200 TUTORIAL-EXERCISES Objective:

Assoc. Prof. Dr. Tansu FİLİK

Computer Programming 3 th Week Variables, constant, and expressions

Fundamentals of Programming Session 12

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Pointers, Arrays, and Strings. CS449 Spring 2016

Computer Programming: Skills & Concepts (CP) Strings

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Intermediate Programming, Spring 2017*

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

CSC 2400: Computer Systems. Arrays and Strings in C

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CSC 2400: Computer Systems. Arrays and Strings in C

Computer Programming 6th Week Functions (Function definition, function calls),

BSM540 Basics of C Language

School of Computer Science Algorithms & Programming. Fall Midterm Examination # 2 Wednesday, November 14, 2007.

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers

Programming Language B

ESC101N: Fundamentals of Computing End-sem st semester

Assoc. Prof. Dr. Tansu FİLİK

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Characters and Strings

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

BLM2031 Structured Programming. Zeyneb KURT

Computer Science & Engineering 150A Problem Solving Using Computers

8. Characters, Strings and Files

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Unit 7. Functions. Need of User Defined Functions

C: How to Program. Week /Mar/05

M1-R4: Programing and Problem Solving using C (JAN 2019)

Array Initialization

Full file at C How to Program, 6/e Multiple Choice Test Bank

ECE551 Midterm Version 1

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

C introduction: part 1

Create a Program in C (Last Class)

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Principles of C and Memory Management

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Chapter 1 & 2 Introduction to C Language

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Functions. Systems Programming Concepts

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C programming basics T3-1 -

CS61, Fall 2012 Section 2 Notes

Chapter 8 C Characters and Strings

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Assoc. Prof. Dr. Tansu FİLİK

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

ALGORITHM 2-1 Solution for Exercise 4

C-LANGUAGE CURRICULAM

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Programming Language B

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

CSE123. Program Design and Modular Programming Functions 1-1

Procedural Programming

Chapter 2 - Introduction to C Programming

Procedural Programming & Fundamentals of Programming

Chapter 2: Overview of C. Problem Solving & Program Design in C

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

Compiling and Running a C Program in Unix

ECE551 Midterm Version 2

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

Pointers and Functions Passing Pointers to Functions CMPE-013/L. Pointers and Functions. Pointers and Functions Passing Pointers to Functions

C Programming Language Review and Dissection III

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

CS1100 Introduction to Programming

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

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

JTSK Programming in C II C-Lab II. Lecture 3 & 4

Introduction to string

Fundamentals of Programming & Procedural Programming

Function Call Stack and Activation Records

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

ECE 551D Spring 2018 Midterm Exam

ECE 551D Spring 2018 Midterm Exam

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Variation of Pointers

Programming and Data Structures

SYSTEM AND LIBRARY CALLS. UNIX Programming 2015 Fall by Euiseong Seo

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Midterm Examination # 2 Wednesday, March 18, Duration of examination: 75 minutes STUDENT NAME: STUDENT ID NUMBER:

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

Fundamental of Programming (C)

Lecture 3. Variables. Variables

Fundamentals of Programming

A Fast Review of C Essentials Part I

Transcription:

Computer Programming: 8th Week Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik

Computer Programming Previously on Bil-200 Recursive functions, two way communications with functions (reference)

Meanings of * Multiplication: Between two numbers, it is the multiplication operator. a * b Pointer: Corresponds to the pointer type variable. char *p; Pointer: Corresponds to the value of the variable pointed to by the pointer. *p = 5;

Computer Programming Pointers int *p1 /*Pointer to an integer variable*/ double *p2 /*Pointer to a variable of data type double*/ char *p3 /*Pointer to a character variable*/ float *p4 /*pointer to a float variable*/ Example-1 int main() { /*Pointer of integer type*/ int *p; int var = 10; /*Assigning the variable address to pointer*/ p= &var; printf("value of var is: %d", var); printf("address of var is: %d", p); return 0; Declerations #include <stdio.h> int main() { int var =10; int *p; p= &var; printf ( "\n Address of var is: %d", &var); printf ( "\n Address of var is: %d", p); printf ( "\n Address of pointer p is: %d", &p); printf( "\n Value of pointer p is: %d", p); printf ( "\n Value of var is: %d", var); printf ( "\n Value of var is: %d", *p); printf ( "\n Value of var is: %d", *( &var)); return 0; Address of var is: 00XBBA77 Address of var is: 00XBBA77 Address of pointer p is: 77221111 Value of pointer p is: 00XBBA77 Value of var is: 10 Value of var is: 10 Value of var is: 10

Example: Date Write a function to enter a date in the "dd/mm/yyyy" form. If the entered date s invalid, the function must warn by writing invalid and requesting a proper date. void input_date(int *gun, int *ay, int *yil);

Example: Date void input_dat(int *gun, int *ay, int *yil) { int gecerli; char ayrac1, ayrac2; do { gecerli = 1; printf("tarih girin(gg aa yyyy): "); scanf("%d %d %d", gun, ay, yil); if ( *gun < 0 *gun > 31 *ay< 1 *ay > 12 *yil < 0 *yil > 9999) { gecerli = 0; printf("tarih yanlis\n"); while (!gecerli);

Example: Date void input_date(int *gun, int *ay, int *yil) { gun is a pointer variable. It contains the the address of the variable.... scanf("%d %d %d", gun, ay, yil);... Why didn t we use &? The & sign is used for accessing the address of the variable. The gun variable is already an address.

Example: Polynomial roots Write a function which takes three float type variables a, b, c from the main program, and returns the real roots of the second order polynomail identified by these coefficients. The function will have three input and two output parameters. input parameters void kok_bul(float a, float b, float c, float &x1, float &x2); output parameters

Example: Polynomial roots #include <stdio.h> void kok_bul(float a,float b,float c, float *x1, float *x2); void main() { float x, y, z, k1, k2; printf("a b c girin: "); scanf("%f %f %f", &x, &y, &z); kok_bul(x, y, z, &k1, &k2); prototype values addresses printf("kokler: %f %f\n", k1, k2);

Example: Polynomial roots void kok_bul(float a, float b, float c, float *x1, float *x2) { float delta; delta = b * b 4 * a * c; if(delta < 0) { *x1 = 0; *x2 = 0; return; *x1 = (-b + sqrt(delta)) / ( 2 * a ); *x2 = (-b - sqrt(delta)) / ( 2 * a );

Introduction to Programming Languages #include <stdio.h> #include <math.h> void kok_bul(double a, double b, double c, double *x1, double *x2); void main(void) { double x, y, z, k1, k2; printf("a - b - c girin: "); scanf_s("%lf %lf %lf", &x, &y, &z); kok_bul(x, y, z, &k1, &k2); printf("kokler: %f %f\n", k1, k2); system("pause"); void kok_bul(double a, double b, double c, double *x1, double *x2) { double delta; delta = b * b - 4 * a * c; if (delta < 0) { *x1 = 0; *x2 = 0; return; *x1 = (-b + sqrt(delta)) / (2 * a); *x2 = (-b - sqrt(delta)) / (2 * a);

Class exercise: division Write a function bolum()with the following parameter list of integers: sayi: to be divided bolen: number to divide with sonuc: division result kalan: remainder The function must implement the integer division. It should divide sayi to bolen, and return the division in sonuc, remainder in kalan.

Character arrays We have been using them for a long time, but...

Character arrays character array printf("sayi=%d!\n", i, j); We have not seen character array type (string) variables yet, but we have been using them for some time. They are defined like: char isim[100];

Strings Like other arrays, initial assignments can be made: char isim[20] = mehmet"; In memory null character (terminates array) isim m e h m e t \0????????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 space allocated for the array

Strings In the declaration and initial assignment line, the compiler terminates the string with the null character. There is a standard string library in C. The defined functions work with the fact that end of string is a null character. The characters to its right are ignored. Since a null character is necessary to terminate a string, you must allocate a space at least 1 more than the maximum number of letters. For example, by saying "char isim[20];" we can hold names of length up to 19 (+ null character).

String declarations String can be initialized in several ways. char renk[ ] = "kırmızı" ; OR char *renk = "kırmızı" ; OR char renk[8] = {'k','ı','r','m','ı','z','ı','\0' ; In the first two methods, the necessary memory space is calculated according to the initial constant string (+1) In the third declaration, we must allocate sufficient space carefully.

void getstring(char *str, int max_len) { int i=0; do { str[i]=getche(); /* conio.h */ i++; while((str[i-1]!= \n )&&(i<max_len-1)); str[i-1]= \0 ; void main(void) { char my_string[100]; getstring( &( my_string [0]),100); printf( %s\n,my_string);

Exercise Write a function which converts an entered string into an integer assuming the entered string is proper. a float, assuming the entered string is proper. Write the two functions in such a way that they ignore improper entries. As examples, the strings at the left would be recognized as numbers at the right: 123se24 => 12324, 12.143ser.43 => 12.14343 Note: Functions such as i=atoi(str), or x=atof(str) can normally do this, but they are not allowed. They do not tolerate improper entries. Note: sscanf(str, %d,&i) or sscanf(str, %f,&x) are not allowed, either.

Note: sscanf and sprintf are two very powerful functions used for extracting variables from a string or to form a string with many variables. : i=10; j=20; x=3.14; char *str2= 101,32 21.13 olabilir ; sprintf(str, Degisken i=%d, j=%d, x=%f,i,j,x); printf( %s\n,str); sscanf(str2, %d,%d %f,&i,&j,%x);

String manipulation functions string.h must be included as a header. String copy: Used for copying contents of the second string str2 into the first string str1: char *strcpy(char *str1,const char *str2); String concatenation: str2 is appended to the last part of str1 char *strcat(char *str1,const char *str2);

String functions Length of a string str (except the null character) is evaluated. int strlen(const char *str1); To lexicographically compare to strings, use strcmp(). If str1 and str2 have the same content, strcmp() returns 0. strcmp(const char *str1,const char *str2);

#include <stdio.h> #include <string.h> void main() { char ad[100]; Example strcmp() printf("adınızı Yazınız: "); gets(ad); /* read one line */ if(strcmp(ad, Mehmet") == 0) { printf( Selam Mehmet");

Example: strlen #include <stdio.h> #include <string.h> void main() { char ad[100]; printf("adinizi Yazınız: "); gets(ad); /* read one line */ printf("ad Uzunluğu = %d\n",strlen(ad));

Exercise (difficult) Open a text file. Ask the user to enter two strings. Replace all first strings with the second string inside the file (find / replace) Note: Assuming the file is small, you can read the whole text file into a single string. But, you do not have to do that. The usage is like: Ali topu at, koş Ali koş. Ali -> Veli Veli topu at, koş Veli koş. (or) Ali -> O O topu at, koş O koş.

Midterm Exam-2 Questions (2013-2014)

Midterm Exam-2 Questions (2013-2014)

Midterm Exam-2 Questions (2013-2014)

static and automatic variables, and scope

Rem: Static variables We have seen that local variables are lost when exitting a function. Static variables are re-formed every time when entering the same function. They are different from automatic variables. These variables are formed at the beginning of the program, and their values are set. Obviously, they are valid only inside its declared function.

void fonk_yaz(void) { int a = 0; printf("deger = %d\n", a); a++; void main() { int i; for( i = 0 ; i < 3 ; i++ ) { fonk_yaz(); Automatic variables A new a is formed for each enterence to the function. This is the default way.

Example: without using static void fonk_yaz(void) { int a = 0; printf("deger = %d\n", a); a++; void main() { int i; A new a variable is formed at each enterence to the function. The variable a is destroyed whenever we quit the function. for( i = 0 ; i < 3 ; i++ ) { fonk_yaz(); So, on the screen, we would see three 0 (zero) values.

void fonk_yaz(void) { static int a = 0; Example re-formed every time when entering the same function printf("deger = %d\n", a); a++; void main() { int i; On the screen, you see deger = 0 deger = 1 deger = 2 for( i = 0 ; i < 3 ; i++ ) { fonk_yaz();

void fonk_yaz(void) { static int a = 0; Example The variable a is formed at the beginning of the program, and its value is kept. printf("deger = %d\n", a); a++; void main() { int i; The variable is not destroyed when quitting the program. for( i = 0 ; i < 3 ; i++ ) { fonk_yaz();

Enumerated types variables that are formed by the keyword: enum

Enumerated types Gives you a chance to form your own type of variables. Its usage improves intelligibility of the program. For example, we may create a type to contain week days: enum Gunler { Pazartesi, Sali, Carsamba, Persembe, Cuma, Cumartesi, Pazar ;

Enumerated types We may make variables of the created type enum Gunler gun; switch(gun) { case Pazartesi: printf("pazartesi"); break; case Sali: printf("sali"); break;...

Enumerated Types Actually, each element in an enum type is a number list starting from 0. enum Gunler { Pazartesi, /* 0 */ Sali, /* 1 */ Carsamba, /* 2 */ Persembe, /* 3 */ Cuma, /* 4 */ Cumartesi, /* 5 */ Pazar /* 6 */ ;

Enumerated Types Since enum elements are numerical, they can be used in comparisons of if expressions. enum Gunler gun1, gun2; gun1 = (enum Gunler) 2; /* carsamba */ gun2 = "Pazartesi"; if(gun2 < gun1) { printf("gun2 daha onceki gun\n");

Scope How long do the variables stay valid?

Scope of Variables The variable scope is defined as the program segment in which the variable can be used. The variable name is an alias for the address of the variable in the memory. For example, if the variable is defined right after "void main {", then it is valid only in main(). It cannot be used anywhere else.

Scope of Variables If a variable is defined inside a block ( { and ), then it is valid until the end of block. If the variable is defined before all the functions, they are called global variables, and they are valid throughout the whole file.

Scope of Variables No two variables may have the same name if they are defined in the same scope. In different scopes, you can use variables with the same name. Since they correspond to different memory places, there will be no ambiguity. Yet, try to avoid using the same variable names under any circumstances.

Example - 1 x variable is not defined yet. Compile error!!! #include <stdio.h> void main ( ) { if ( x == 3 ) { float x = 4.5; x was only in the block, and now not defined any more... printf ( "blok içinde x=%f", x); printf( "bloktan sonra x=%d\n", x);

Example - 2 x variable is defined. OK!! #include <stdio.h> void main ( ) { int x = 3; Here, the nearestly defined one is valid. if ( x == 3 ) { float x = 4.5; printf ( "blok içinde x=%f", x); printf( bloktan sonra x=%d\n", x);

Scope of Variables In the previous example, there is an x variable defined right after main(). But in if block, there is another variable called x. Inside the block, that new variable will be valid, and the outer x is not valid. Since the two variables correspond to two different memory addresses, they will not be confused.

Would they? Run the program and see the following output: blok içinde x=4.5 bloktan sonra x=3