Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Similar documents
A Fast Review of C Essentials Part II

Fundamentals of Programming

Principles of C and Memory Management

Fundamental of Programming (C)

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

Fundamental of Programming (C)

Computer Programming Unit 3

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Pointers, Arrays, and Strings. CS449 Spring 2016

Chapter 8: Character & String. In this chapter, you ll learn about;

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Array Initialization

ARRAYS(II Unit Part II)

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

A Fast Review of C Essentials Part I


Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

8. Characters, Strings and Files

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

BLM2031 Structured Programming. Zeyneb KURT

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Technical Questions. Q 1) What are the key features in C programming language?

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Slide Set 3. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

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

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

Iterative Languages. Scoping

C Programming Language

M.EC201 Programming language

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

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

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Computers Programming Course 10. Iulian Năstac

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

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

BSM540 Basics of C Language

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture5 C Characters and Strings

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

Fundamentals of Programming

Intermediate Programming, Spring 2017*

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

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

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

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

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

QUIZ. What is wrong with this code that uses default arguments?

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

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Chapter 3: Arrays and More C Functionality

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

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

Array. Prepared By - Rifat Shahriyar

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

EM108 Software Development for Engineers

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

Lecture 04 Introduction to pointers

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Pointers and Lexical Scoping. CS449 Fall 2017

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Lesson 7. Reading and Writing a.k.a. Input and Output

Variation of Pointers

Data Types and Variables in C language

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Computers Programming Course 11. Iulian Năstac

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

CS 33. Introduction to C. Part 5. CS33 Intro to Computer Systems V 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

CS 61c: Great Ideas in Computer Architecture

Computer Programming: Skills & Concepts (CP) Strings

Storage class and Scope:

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

Fast Introduction to Object Oriented Programming and C++

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

Chapter 6. Section 6.4 Altering the Flow of Control. CS 50 Hathairat Rattanasook

Scientific Programming in C V. Strings

CSE2301. Arrays. Arrays. Arrays and Pointers

Procedural Programming & Fundamentals of Programming

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

Syntax and Variables

Model Viva Questions for Programming in C lab

EC312 Chapter 4: Arrays and Strings

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

Introduction to string

POINTER & REFERENCE VARIABLES

Flow Control. CSC215 Lecture

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

Programming and Data Structures

Write a C program using arrays and structure

Stream Model of I/O. Basic I/O in C

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

Language comparison. C has pointers. Java has references. C++ has pointers and references

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Assignment 1 Clarifications

Basic Types and Formatted I/O

Transcription:

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 strings Reading strings with scanf( The gets() and puts() functions

Strings What Is a String? As introduced in Lecture 6, "Storing Similar Data Items," a string is a character array terminated by a null character (\0). For instance, a character array, array_ch, declared in the following statement, is considered a character string: char array_ch[7] = {`H', `e', `l', `l', `o', `!', `\0'}; A series of characters enclosed in double quotes ("") is called a string constant.

Strings Declaring and Initializing Strings a character array can be declared and initialized like this: char arr_str[6] = {`H', `e', `l', `l', `o', `!'}; Here the array arr_str is treated as a character array. However,if you add a null character (\0) into the array, you can have the following statement: char arr_str[7] = {`H', `e', `l', `l', `o', `!', `\0'}; You can also initialize a character array with a string constant. For example, the following statement initializes a character array, str, with a string constant, "Hello!": char str[7] = "Hello!";

Strings Declaring and Initializing Strings You can declare an unsized character array if you want the compiler to calculate the total number of elements in the array. For instance, the folowing statement; char str[] = "I like C."; If you like, you can also declare a char pointer and then initialize the pointer with a string constant. The following statement is an example: char *ptr_str = "I teach myself C.";

Strings WARNING Don't specify the size of a character array as too small. Otherwise, it cannot hold a string constant plus an extra null character. For instance, the following declaration is considered illegal: char str[4] = "text"; The following statement is a correct one: because it is big enough to hold the string constant plus an extra null character \0 : char str[5] = "text";

Strings String Constants Versus Character Constants What Is a String? When a character variable ch and a character array str are initialized with the same character, x, such as the following, char ch = `x'; char str[] = "x"; 1 byte is required to hold char but 2 bytes are required to hold string.

Strings Another important thing is that a string is interpreted as a char pointer. Therefore, you can assign a character string to a pointer variable directly, like this: char *ptr_str; ptr_str = "A character string."; However, you can not assign a character constant to the pointer variable, as shown in the following: ptr_str = `x'; /* It's wrong. */ When a character variable ch and a character array str are initialized with the same character, x, such as the following,

Strings It's legal to assign a character constant to a dereferenced char pointer like this: char *ptr_str; *ptr_str = `x';

1: /* Initializing strings */ 2: #include <stdio.h> 3: 4: main() 5: { 6: char str1[] = {`A', ` `, 7: `s', `t', `r', `i', `n', `g', ` `, 8: `c', `o', `n', `s', `t', `a', `n', `t', `\0'}; 9: char str2[] = "Another string constant"; 10: char *ptr_str; 11: int i; 12: 13: /* print out str2 */ 14: for (i=0; str1[i]; i++) 15: printf("%c", str1[i]); 16: printf("\n"); 17: /* print out str2 */ 18: for (i=0; str2[i]; i++) 19: printf("%c", str2[i]); 20: printf("\n"); 21: /* assign a string to a pointer */ 22: ptr_str = "Assign a string to a pointer."; 23: for (i=0; *ptr_str; i++) 24: printf("%c", *ptr_str++); 25: return 0; 26: } Strings A string constant Another string constant Assign a string to a pointer.

How Long Is a String? Strings Sometimes, you need to know how many bytes are taken by a string. In C, you can use a function called strlen() to measure the length of a string.

1: /* Measuring string length */ 2: #include <stdio.h> 3: #include <string.h> 4: 5: main() 6: { 7: char str1[] = {`A', ` `, 8: `s', `t', `r', `i', `n', `g', ` `, 9: `c', `o', `n', `s', `t', `a', `n', `t', `\0'}; 10: char str2[] = "Another string constant"; 11: char *ptr_str = "Assign a string to a pointer."; 12: 13: printf("the length of str1 is: %d bytes\n", strlen(str1)); 14: printf("the length of str2 is: %d bytes\n", strlen(str2)); 15: printf("the length of the string assigned to ptr_str is: %d bytes\n", 16: strlen(ptr_str)); 17: return 0; 18: } Strings The length of str1 is: 17 bytes The length of str2 is: 23 bytes The length of the string assigned to ptr_str is: 29 bytes

Copying Strings with strcpy() Strings When a character variable ch and a character array str are initialized with the same character, x, such as the following, The syntax for the strcpy() function is #include <string.h> char *strcpy(char *dest, const char *src);

Strings 1: /* Copying strings */ 2: #include <stdio.h> 3: #include <string.h> 4: 5: main() 6: { 7: char str1[] = "Copy a string."; 8: char str2[15]; 9: char str3[15]; 1 0: int i; 11: 12: /* with strcpy() */ 13: strcpy(str2, str1); The content of str2: Copy a string. 14: /* without strcpy() */ The content of str3: Copy a string. 15: for (i=0; str1[i]; i++) 16: str3[i] = str1[i]; 17: str3[i] = `\0'; 18: /* display str2 and str3 */ 19: printf("the content of str2: %s\n", str2); 20: printf("the content of str3: %s\n", str3); 21: return 0; 22: }

Strings Reading and Writing Strings - The gets() and puts() Functions The gets() function can be used to read characters from the standard input stream. The syntax for the gets() function is #include <stdio.h> char *gets(char *s); The puts() function can be used to write characters to the standard output stream (that is, stdout). The syntax for the puts() function is #include <stdio.h> int puts(const char *s);

1: /* Using gets() and puts() */ 2: #include <stdio.h> 3: 4: main() 5: { 6: char str[80]; 7: int i, delt = `a' - `A'; 8: 9: printf("enter a string less than 80 characters:\n"); 10: gets( str ); 11: i = 0; 12: while (str[i]){ 13: if ((str[i] >= `a') && (str[i] <= `z')) 14: str[i] -= delt; /* convert to upper case */ 15: ++i; 16: } 17: printf("the entered string is (in uppercase):\n"); 18: puts( str ); 19: return 0; 20: } Strings Enter a string less than 80 characters: This is a test. The entered string is (in uppercase): THIS IS A TEST.

Strings Using %s with the printf() Function See previous example. The scanf() Function The syntax for the scanf() function is #include <stdio.h> int scanf(const char *format, );

1: /* 13L05.c: Using scanf() */ 2: #include <stdio.h> 3: 4: main() 5: { 6: char str[80]; 7: int x, y; 8: float z; 9: 10: printf("enter two integers separated by a space:\n"); 11: scanf("%d %d", &x, &y); 12: printf("enter a floating-point number:\n"); 13: scanf("%f", &z); 14: printf("enter a string:\n"); 15: scanf("%s", str); 16: printf("here are what you've entered:\n"); 17: printf("%d %d\n%f\n%s\n", x, y, z, str); 18: return 0; 19: } Strings Enter two integers separated by a space: 10 12345 Enter a floating-point number: 1.234567 Enter a string: Test Here are what you've entered: 10 12345 1.234567 Test

Scope and Storage Classes in C Block Scope In this section, a block refers to any sets of statements enclosed in braces ({ and }). A variable declared within a block has block scope. Thus, the variable is active and accessible from its declaration point to the end of the block. Sometimes, block scope is also called local scope. For example, the variable i declared within the block of the following main function has block scope: int main() { } int i; /* block scope */... return 0; Usually, a variable with block scope is called a local variable.

Nested Block Scope Scope and Storage Classes in C You can also declare variables within a nested block. If a variable declared in the outer block shares the same name with one of the variables in the inner block, the variable within the outer block is hidden by the one within the inner block for the scope of the inner block. int main() { } if(expression){ if(expression){ } }... return 0;

Scope and Storage Classes in C 1: /* 14L01.c: Scopes in nested block */ 2: #include <stdio.h> 3: 4: main() 5: { 6: int i = 32; /* block scope 1*/ 7: 8: printf("within the outer block: i=%d\n", i); 9: 10: { /* the beginning of the inner block */ 11: int i, j; /* block scope 2, int i hides the outer int i*/ 12: 13: printf("within the inner block:\n"); 14: for (i=0, j=10; i<=10; i++, j--) 15: printf("i=%2d, j=%2d\n", i, j); 16: } /* the end of the inner block */ 17: printf("within the outer block: i=%d\n", i); 18: return 0; 19: } Within the outer block: i=32 Within the inner block: i= 0, j=10 i= 1, j= 9 i= 2, j= 8 i= 3, j= 7 i= 4, j= 6 i= 5, j= 5 i= 6, j= 4 i= 7, j= 3 i= 8, j= 2 i= 9, j= 1 i=10, j= 0 Within the outer block: i=32

Scope and Storage Classes in C Function Scope Function scope indicates that a variable is active and visible from the beginning to the end of a function. In C, only the goto label has function scope. For example, the goto label, start, shown in the following code portion has function scope: int main() { int i; /* block scope */ }... start: /* A goto label has function scope */... goto start; /* the goto statement */... return 0;

Scope and Storage Classes in C Program Scope A variable is said to have program scope when it is declared outside a function. For instance, look at the following code: int x = 0; /* program scope */ float y = 0.0; /* program scope */ int main() { int i; /* block scope */ }... return 0; Here the int variable x and the float variable y have program scope.

Scope and Storage Classes in C The Storage Class Specifiers -The auto Specifier The auto specifier indicates that the memory location of a variable is temporary. In other words, a variable's reserved space in the memory can be erased or relocated when the variable is out of its scope. Only variables with block scope can be declared with the auto specifier. The auto keyword is rarely used, however, because the duration of a variable with block scope is temporary by default.

Scope and Storage Classes in C The Storage Class Specifiers -The static Specifier The static specifier can be applied to variables with either block scope or program scope. When a variable within a function is declared with the static specifier, the variable has a permanent duration. In other words, the memory storage allocated for the variable is not destroyed when the scope of the variable is exited, the value of the variable is maintained outside the scope, and if execution ever returns to the scope of the variable, the last value stored in the variable is still there. For instance, in the following code portion: int main() { } int i; /* block scope and temporary duration */ static int j; /* block scope and permanent duration */.. return 0;

Scope and Storage Classes in C File Scope and the Hierarchy of Scopes In C, a global variable declared with the static specifier is said to have file scope. A variable with file scope is visible from its declaration point to the end of the file. Here the file refers to the program file that contains the source code. Most large programs consist of several program files. The following portion of source code shows variables with file scope: int x = 0; /* program scope */ static int y = 0; /* file scope */ static float z = 0.0; /* file scope */ int main() { int i; /* block scope */ }... return 0;

Scope and Storage Classes in C The extern Specifier As stated in the section titled "Program Scope," a variable withprogram scope is visible through all source files that make up an executable program. A variable with program scope is also called a global variable. For instance, suppose you have two global int variables, y and z, that are defined in one file, and then, in another file, you may have the following declarations: int x = 0; /* a global variable */ extern int y; /* an allusion to a global variable y */ int main() { extern int z; /* an allusion to a global variable z */ int i; /* a local variable */... return 0; }

Scope and Storage Classes in C The Storage Class Modifiers - The const Modifier If you declare a variable with the const modifier, the content of the variable cannot be changed after it is initialized. const double circle_ratio = 3.141593; const char str[] = "A string constant"; In addition, you can declare a pointer variable with the const modifier so that an object pointed to by the pointer cannot be changed. For example,consider the following pointer declaration with the const modifier: char const *ptr_str = "A string constant"; After the initialization, you cannot change the content of the string pointed to by the pointer ptr_str. For instance, the following statement is not allowed: *ptr_str = `a'; /* It's not allowed here. */

Scope and Storage Classes in C The Storage Class Modifiers - The volatile Modifier Sometimes, you want to declare a variable whose value can be changed without any explicit assignment statement in your program. For instance,you might declare a global variable that contains characters entered by the user. The address of the variable is passed to a device register that accepts characters from the keyboard. However, when the C compiler optimizes your program automatically, it intends to not update the value held by the variable unless the variable is on the left side of an assignment operator (=). In other words, the value of the variable is likely not changed even though the useris typing in characters from the keyboard: void read_keyboard() { } volatile char keyboard_ch; /* a volatile variable */...