NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.
|
|
- Candice Knight
- 6 years ago
- Views:
Transcription
1 NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313
2 Programming in C! Characters and Strings!! 1/19/10
3 ASCII! The American Standard Code for Information Interchange (ASCII) character set, has 128 characters designed to encode the Roman alphabet used in English and other Western European languages.! C was designed to work with ASCII and we will only use the ASCII character set in this course. The char data type is used to store ASCII characters in C! ASCII can represent 128 characters and is encoded in one eight bit byte with a leading 0. Seven bits can encode numbers 0 to 127. Since integers in the range of 0 to 127 can be stored in 1 byte of space, the sizeof(char) is 1.! The characters 0 through 31 represent control characters (e.g., line feed, back space), are printable characters, and 127 is delete.! 1/19/10
4 char type! C supports the char data type for storing a single character.! char uses one byte of memory! char constants are enclosed in single quotes! char mygrade = A ;! char yourgrade =? ;!! 1/19/10
5 1/19/10 ASCII Character Chart!
6 Special Characters! The backslash character, \, is used to indicate that the char that follows has special meaning. E.g. for unprintable characters and special characters.! For example! \n is the newline character! \t is the tab character! \ is the double quote (necessary since double quotes are used to enclose strings! \ is the single quote (necessary since single quotes are used to enclose chars! \\ is the backslash (necessary since \ now has special meaning! \a is beep which is unprintable! 1/19/10
7 Special Char Example Code! What is the output from these statements?! printf( \t\tmove over\n\nworld, here I come\n");!!!move over!! World, here I come! printf("i\ ve written \ Hello World\ \n\t many times\n\a ); I ve written Hello World!!many times <beep>! 1/19/10
8 Character Library! There are many functions to handle characters. To use these functions in your code,!!!#include <ctype.h>! Note that the function parameter type is int, not char. Why is this ok?! Note that the return type for some functions is int since ANSI C does not support the bool data type. Recall that zero is false, non-zero is true.! A few of the commonly used functions are listed on the next slide. For a full list of ctype.h functions, type man ctype.h at the unix prompt.! 1/19/10
9 int isdigit (int c);! ctype.h! Determine if c is a decimal digit ( 0-9 )! int isxdigit(int c);! Determines if c is a hexadecimal digit ( 0-9, a - f, or A - F )! int isalpha (int c);! Determines if c is an alphabetic character ( a - z or A- Z )! int isspace (int c);! Determines if c is a whitespace character (space, tab, etc)! int isprint (int c);! Determines if c is a printable character! int tolower (int c);! int toupper (int c);! Returns c changed to lower- or upper-case respectively, if possible! 1/19/10
10 Character Input/Output! Use %c in printf( )and fprintf( )to output a single character.! char yourgrade = A ;! printf( Your grade is %c\n, yourgrade);!! Input char(s) using %c with scanf( ) or fscanf( )!!!char grade, scores[3];! %c inputs the next character, which may be whitespace!scanf( %c, &grade);! %nc inputs the next n characters, which may include whitespace.!!!scanf( %3c, scores);! // note -- no & needed! 1/19/10
11 Array of char! An array of chars may be (partially) initialized. This declaration reserves 20 char (bytes) of memory, but only the first 5 are initialized! char name2 [ 20 ] = { B, o, b, b, y }; You can let the compiler count the chars for you. This declaration allocates and initializes exactly 5 chars (bytes) of memory! char name3 [ ] = { B, o, b, b, y }; An array of chars is NOT a string! 1/19/10
12 Strings in C! In C, a string is an array of characters terminated with the null character ( \0, value = 0, see ASCII chart).! A string may be defined as a char array by initializing the last char to \0! char name4[ 20 ] = { B, o, b, b, y, \0 }; Char arrays are permitted a special initialization using a string constant. Note that the size of the array must account for the \0 character.! char name5[6] = Bobby ; // this is NOT assignment Or let the compiler count the chars and allocate the appropriate array size! char name6[ ] = Bobby ; All string constants are enclosed in double quotes and include the terminating \0 character! 1/19/10
13 String Output! Use %s in printf( ) or fprintf( ) to print a string. All chars will be output until the \0 character is seen.! char name[ ] = Bobby Smith ;! printf( My name is %s\n, name);! As with all conversion specifications, a minimum field width and justification may be specified! char book1[ ] = Flatland ;! char book2[ ] = Brave New World ;!! printf ( My favorite books are %12s and %12s\n, book1, book2);! printf ( My favorite books are %-12s and %-12s\n, book1, book2);!!! 1/19/10
14 Dangerous String Input! The most common and most dangerous method to get string input from the user is to use %s with scanf( ) or fscanf( )! This method interprets the next set of consecutive non-whitespace characters as a string, stores it in the specified char array, and appends a terminating \0 character.! char name[22];! printf( Enter your name: );! scanf( %s, name);! Why is this dangerous?! 1/19/10
15 Safer String Input! A safer method of string input is to use %ns with scanf( ) or fscanf( ) where n is an integer! This will interpret the next set of consecutive nonwhitespace characters up to a maximum of n characters as a string, store it in the specified char array, and append a terminating \0 character.! char name[ 22 ];! printf( Enter your name: );! scanf( %21s, name);!// note 21, not 22! 1/19/10
16 C String Library! C provides a library of string functions.! To use the string functions, include <string.h>. Some of the more common functions are listed here on the next slides.! To see all the string functions, type man string.h at the unix prompt.! 1/19/10
17 C String Library (2)! Commonly used string functions! These functions look for the \0 character to determine the end and size of the string! strlen( const char string[ ] )! Returns the number of characters in the string, not including the null character! strcpy( char s1[ ], const char s2[ ] )! Copies s2 on top of s1.! The order of the parameters mimics the assignment operator! strcmp ( const char s1[ ], const char s2[ ] )! Returns < 0, 0, > 0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically! strcat( char s1[ ], const char s2[ ])! Appends (concatenates) s2 to s1! 1/19/10
18 C String Library (3)! Some function in the C String library have an additional size parameter.! strncpy( char s1[ ], const char s2[ ], int n )! Copies at most n characters of s2 on top of s1.! The order of the parameters mimics the assignment operator! strncmp ( const char s1[ ], const char s2[ ], int n )! Compares up to n characters of s1 with s2! Returns < 0, 0, > 0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically! strncat( char s1[ ], const char s2[ ], int n)! Appends at most n characters of s2 to s1! 1/19/10
19 String Code! char first[10] = bobby ; char last[15] = smith ; char name[30]; char you[ ] = bobo ; strcpy( name, first ); strcat( name, last ); printf( %d, %s\n, strlen(name), name ); strncpy( name, last, 2 ); printf( %d, %s\n, strlen(name), name ); int result = strcmp( you, first ); result = strncmp( you, first, 3 ); strcat( first, last ); 1/19/10
20 Simple Encryption! char c, msg[] = "this is a secret message"; int i = 0; char code[26] = /* Initialize our encryption code */ {'t','f','h','x','q','j','e','m','u','p','i','d','c', 'k','v','b','a','o','l','r','z','w','g','n','s','y'} ; /* Print the original phrase */ printf ("Original phrase: %s\n", msg); /* Encrypt */ while( msg[i]!= '\0 ){ if( isalpha( msg[ i ] ) ) { c = tolower( msg[ i ] ) ; msg[ i ] = code[ c - a ] ; } ++i; } printf("encrypted: %s\n", msg ) ;
21 Arrays of Strings! Since strings are arrays themselves, using an array of strings can be a little tricky! An initialized array of string constants! char months[ ][ 12 ] = { Jan, Feb,... };! int m;! for ( m = 0; m < 12; m++ )!!printf( %s\n, months[ m ] );! 1/19/10
22 Arrays of Strings (2)! An array of string 12 variables, each 20 chars long! char names[ 12 ] [ 21 ];! int n;! for( n = 0; n < 12; ++n )! {! }!!printf( Please enter your name: );!!scanf( %20s, names[ n ] );! 1/19/10
23 gets( ) to read a line! The gets( ) function is used to read a line of input (including the whitespace) from stdin until the \n character is encountered. The \n character is replaced with the terminating \0 character.!! #include <stdio.h> char mystring[ 101 ]; gets( mystring ); Why is this dangerous?! 1/19/10
24 fgets( ) to read a line! The fgets( ) function is used to read a line of input (including the whitespace) from the specified FILE until the \n character is encountered or until the specified number of chars is read.! 1/19/10
25 fgets( )! #include <stdio.h> #include <stdlib.h> /* exit */ int main ( ) { double x ; FILE *ifp ; char myline[42 ]; /* for terminating \0 */ ifp = fopen("test_data.dat", "r"); if (ifp == NULL) { printf ("Error opening test_data.dat\n"); exit (-1); } fgets(myline, 42, ifp ); /* read up to 41 chars*/ fclose(ifp); /* close the file when finished */ } /* check to see what you read */ printf( myline = %s\n, myline); return 0; 1/19/10
26 Detecting EOF with fgets( )! fgets( ) returns the memory address in which the line was stored (the char array provided). However, when fgets( ) encounters EOF, the special value NULL is returned.! FILE *infile; infile = fopen( myfile, r ); /* check that the file was opened */ char string[120]; while ( fgets(string, 120, infile )!= NULL ) printf( %s\n, string ); fclose( infile );! 1/19/10!
27 Using fgets( ) instead of gets( )! Since fgets( ) can read any file, it can be used in place of gets( ) to get input from the user!! #include <stdio.h> char mystring[ 101 ];!!Instead of! gets( mystring );!Use!!fgets( mystring, 100, stdin ); 1/19/10
28 Big Enough! The owner of a string is responsible for allocating array space which is big enough to store the string (including the null character).! scanf( ), fscanf( ), and gets( ) assume the char array argument is big enough! String functions that do not provide a parameter for the length rely on the \0 character to determine the end of the string.! Most string library functions do not check the size of the string memory. E.g. strcpy 1/19/10
29 What can happen?! int main( ) { char first[10] = "bobby"; char last[15] = "smith"; printf("first contains %d chars: %s\n", strlen(first), first); printf("last contains %d chars: %s\n", strlen(last), last); strcpy(first, " "); /* too big */ printf("first contains %d chars: %s\n", strlen(first), first); printf("last contains %d chars: %s\n", strlen(last), last); } return 0; /* output */ first contains 5 chars: bobby last contains 5 chars: smith first contains 13 chars: last contains 5 chars: smith Segmentation fault 28
30 The Lesson! Avoid scanf( %s, buffer);! Use scanf( %100s, buffer); instead! Avoid gets( );! Use fgets(...,..., stdin); instead! 1/19/10
31 sprintf( )! Sometimes it s necessary to format a string in an array of chars. Something akin to tostring( ) in Java.! sprintf( ) works just like printf( ) or fprintf( ), but puts its output into the specified character array.! As always, the character array must be big enough.!! char message[ 100 ]; int myage = 4; sprintf( message, I am %d years old\n, age); printf( %s\n, message); 1/19/10
32 NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313
33 Programming in C Structs and Unions
34 Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane. In Java, you d correctly design a Point class and a Line class using composition. What about in C?
35 No Classes in C Because C is not an OOP language, there is no way to combine data and code into a single entity. C does allow us to combine related data into a structure using the keyword struct. All data in a struct variable can be accessed by any code. Think of a struct as an OOP class in which all data members are public, and which has no methods.
36 Struct definition The general form of a structure definition is struct tag Note the semi-colon { member1_declaration; member2_declaration; member3_declaration;... membern_declaration; }; where struct is the keyword, tag names this kind of struct, and member_declarations are variable declarations which define the members.
37 C struct Example Defining a struct to represent a point in a coordinate plane struct point { int x; /* x-coordinate */ int y; /* y-coordinate */ }; Given the declarations struct point p1; struct point p2; point is the struct tag we can access the members of these struct variables: * the x-coordinate of p1 is p1.x * the y-coordinate of p1 is p1.y * the x-coordinate of p2 is p2.x * the y-coordinate of p2 is p2.y
38 Using structs and members The members of a struct are variables just like any other and can be used wherever any other variable of the same type may be used. For example, the members of the struct point can then be used just like any other integer variables.
39 Using struct members int main ( ) { struct point lefeendpt, rightendpt, newendpt; // get x- and y-coordinates of left end point printf( Left end point cooridinates ); scanf( %d %d, &lefeendpt.x, &leftendpt.y); // get x- and y-coordinates of right end point printf( Right end point s x-coordinate: ); scanf( %d %d, &righteendpt.x, &rightendpt.y); // add the endpoints newendpt.x = leftendpt.x + rightendpt.x; newendpt.y = leftendpt.y + rightendpt.y; // print new end point printf( New endpoint (%2d, %2d), newendpt.x, newendpt.); } return 0;
40 Initializing A struct A struct variable may be initialized when it is declared by providing the initial values for each member in the order they appear struct point middle = { 6, -3 }; defines the struct point variable named middle and initializes middle.x = 6 and middle.y = -3
41 struct Variants struct variables may be declared at the same time the struct is defined struct point { int x, y; } endpoint, upperleft; defines the structure named point AND declares the variables endpoint and upperleft to be of this type.
42 struct typedef It s common to use a typedef for the name of a struct to make code more concise. typedef struct point { int x, y; } POINT; defines the structure named point and defines POINT as a typedef (alias) for the struct. We can now declare variables as struct point endpoint; or as POINT upperright;
43 struct assignment The contents of a struct variable may be copied to another struct variable of the same type using the assignment (=) operator After this code is executed struct point p1; struct point p2; p1.x = 42; p1.y = 59; p2 = p1; /* structure assignment copies members */ The values of p2 s members are the same as p1 s members. E.g. p1.x = p2.x = 42 and p1.y = p2.y = 59
44 struct within a struct A data element in a struct may be another struct (similar to composition with classes in Java / C++). This example defines a line in the coordinate plane by specifying its endpoints as POINT structs typedef struct line { POINT leftendpoint; POINT rightendpoint; } LINE; Given the declarations below, how do we access the x- and y-coodinates of each line s endpoints? struct line line1, line2; line1.leftendpoint.x line1.rightendpoint.y line2.leftendpoint.x line2.rightendpoint.y
45 Arrays of struct Since a struct is a variable type, we can create arrays of structs just like we create arrays of primitives. Write the declaration for an array of 5 line structures name lines struct line lines[ 5 ]; or LINE lines[ 5 ]; Write the code to print the x-coordinate of the left end point of the 3rd line in the array printf( %d\n, lines[2].leftendpoint.x); 1/20/10 13
46 Array of struct Code /* assume same point and line struct definitions */ int main( ) { LINE sides[5]; int k; /* write code to initialize all data members to zero */ for (k = 0; k < 5; k++) { sides[k].leftendpoint.x = 0; sides[k].leftendpoint.y = 0; sides[k].rightendpoint.x = 0; sides[k].rightendpoint.y = 0; } /* write the code to print the x-coordinate of ** the left end point of the 3rd line */ } return 0; 14
47 Arrays within a struct Structs may contain arrays as well as primitive types struct month { int nrdays; char name[ ]; }; struct month january = { 31, JAN };
48 A bit more complex struct month allmonths[ 12 ] = { {31, JAN }, {28, FEB }, {31, MAR }, {30, APR }, {31, MAY }, {30, JUN }, {31, JUL }, {31, AUG }, {30, SEP }, {31, OCT }, {30, NOV }, {31, DEC } }; // write the code to print the data for September printf( %s has %d days\n, allmonths[8].name, allmonths[8].nrdays); // what is the value of allmonths[3].name[1] P
49 Size of a struct As with primitive types, we can use sizeof( ) to determine the number of bytes in a struct int pointsize = sizeof( POINT ); int linesize = sizeof (struct line); As we ll see later, the answers may surprise you!
50 Bitfields When saving space in memory or a communications message is of paramount importance, we sometimes need to pack lots of information into a small space. We can use struct syntax to define variables which are as small as 1 bit in size. These variables are known as bit fields. struct weather { }; unsigned int temperature : 5; unsigned int windspeed : 6; unsigned int israining : 1; unsigned int issunny : 1; unsigned int issnowing : 1;
51 Using Bitfields Bit fields are referenced like any other struct member struct weather todaysweather; todaysweather.temperature = 44; todaysweather.issnowing = 0; todaysweather.windspeed = 23; /* etc */ if (todaysweather.israining) printf( %s\n, Take your umbrella ); if (todaysweather.temperature < 32 ) printf( %s\n, Stay home );
52 More on Bit fields Almost everything about bit fields is implementation (machine and compiler) specific. Bit fields may only defined as (unsigned) ints Bit fields do not have addresses, so the & operator cannot be applied to them We ll see more on this later
53 Unions A union is a variable type that may hold different type of members of different sizes, BUT only one type at a time. All members of the union share the same memory. The compiler assigns enough memory for the largest of the member types. The syntax for defining a union and using its members is the same as the syntax for a struct.
54 Formal Union Definition The general form of a union definition is union tag { member1_declaration; member2_declaration; member3_declaration;... membern_declaration; }; where union is the keyword, tag names this kind of union, and member_declarations are variable declarations which define the members. Note that the syntax for defining a union is exactly the same as the syntax for a struct.
55 An application of Unions struct square { int length; }; struct circle { int radius; }; struct rectangle { int width; int height; }; enum shapetype {SQUARE, CIRCLE, RECTANGLE }; union shapes { struct square asquare; struct circle acircle; struct rectangle arectangle; }; struct shape { enum shapetype type; union shapes theshape; };
56 An application of Unions (2) double area( struct shape s) { switch( s.type ) { case SQUARE: return s.theshape.asquare.length * s.theshape.asquare.length; case CIRCLE: return 3.14 * s.theshape.acircle.radius * s.theshape.acircle.radius; case RECTANGLE : return s.theshape.arectangle.height * s.theshape.arectangle.width; } }
57 Union vs. Struct Similarities Definition syntax virtually identical Member access syntax identical Differences Members of a struct each have their own address in memory. The size of a struct is at least as big as the sum of the sizes of the members (more on this later) Members of a union share the same memory. The size of a union is the size of the largest member.
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, FALL 2012
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, FALL 2012 TOPICS TODAY Characters & Strings in C Structures in C CHARACTERS & STRINGS char type C supports the char data type
More information10/6/2015. C Input/Output. stdin, stdout, stderr. C Language II. CMSC 313 Sections 01, 02. C opens three input/output devices automatically:
C Input/Output stdin, stdout, stderr C opens three input/output devices automatically: C Language II CMSC 313 Sections 01, 02 stdin The "standard input" device, usually your keyboard stdout The "standard
More informationArrays, Strings, & Pointers
Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering Arrays, Strings, & Pointers Arrays, Strings, & Pointers are
More informationC mini reference. 5 Binary numbers 12
C mini reference Contents 1 Input/Output: stdio.h 2 1.1 int printf ( const char * format,... );......................... 2 1.2 int scanf ( const char * format,... );.......................... 2 1.3 char
More informationtoday cs3157-fall2002-sklar-lect05 1
today homework #1 due on monday sep 23, 6am some miscellaneous topics: logical operators random numbers character handling functions FILE I/O strings arrays pointers cs3157-fall2002-sklar-lect05 1 logical
More informationC Libraries. Bart Childs Complementary to the text(s)
C Libraries Bart Childs Complementary to the text(s) 2006 C was designed to make extensive use of a number of libraries. A great reference for student purposes is appendix B of the K&R book. This list
More informationChapter 8 - Characters and Strings
1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions 8.5 Standard Input/Output Library
More informationChapter 8 C Characters and Strings
Chapter 8 C Characters and Strings Objectives of This Chapter To use the functions of the character handling library (). To use the string conversion functions of the general utilities library
More informationSWEN-250 Personal SE. Introduction to C
SWEN-250 Personal SE Introduction to C A Bit of History Developed in the early to mid 70s Dennis Ritchie as a systems programming language. Adopted by Ken Thompson to write Unix on a the PDP-11. At the
More informationC Programming. Unit 9. Manipulating Strings File Processing.
Introduction to C Programming Unit 9 Manipulating Strings File Processing skong@itt-tech.edu Unit 8 Review Unit 9: Review of Past Material Unit 8 Review Arrays Collection of adjacent memory cells Each
More informationCS1100 Introduction to Programming
CS1100 Introduction to Programming Arrays Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB, PSK, NSN, DK, TAG CS&E, IIT M 1 An Array
More informationFile Handling in C. EECS 2031 Fall October 27, 2014
File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically
More informationVariables Data types Variable I/O. C introduction. Variables. Variables 1 / 14
C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition
More informationC: How to Program. Week /May/28
C: How to Program Week 14 2007/May/28 1 Chapter 8 - Characters and Strings Outline 8.1 Introduction 8.2 Fundamentals of Strings and Characters 8.3 Character Handling Library 8.4 String Conversion Functions
More informationChapter 8: Character & String. In this chapter, you ll learn about;
Chapter 8: Character & String Principles of Programming In this chapter, you ll learn about; Fundamentals of Strings and Characters The difference between an integer digit and a character digit Character
More informationScientific Programming in C V. Strings
Scientific Programming in C V. Strings Susi Lehtola 1 November 2012 C strings As mentioned before, strings are handled as character arrays in C. String constants are handled as constant arrays. const char
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationCS 261 Fall Mike Lam, Professor. Structs and I/O
CS 261 Fall 2018 Mike Lam, Professor Structs and I/O Typedefs A typedef is a way to create a new type name Basically a synonym for another type Useful for shortening long types or providing more meaningful
More information8. Characters, Strings and Files
REGZ9280: Global Education Short Course - Engineering 8. Characters, Strings and Files Reading: Moffat, Chapter 7, 11 REGZ9280 14s2 8. Characters and Arrays 1 ASCII The ASCII table gives a correspondence
More informationC BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.
C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,
More informationSyntax and Variables
Syntax and Variables What the Compiler needs to understand your program, and managing data 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line
More informationProgramming in C. Pointers and Arrays
Programming in C Pointers and Arrays NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313 http://www.csee.umbc.edu/courses/undergraduate/313/fall11/" Pointers and Arrays In C, there is a strong relationship
More informationMain Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University
C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types
More informationCharacters and Strings
Characters and Strings 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2013 Instructor: Dr. Asish Mukhopadhyay Character constants A character in single quotes,
More informationCourse organization. Course introduction ( Week 1)
Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and
More informationSystem Design and Programming II
System Design and Programming II CSCI 194 Section 01 CRN: 10968 Fall 2017 David L. Sylvester, Sr., Assistant Professor Chapter 10 Characters, Strings, and the string Class Character Testing The C++ library
More informationOverview. Concepts this lecture String constants Null-terminated array representation String library <strlib.h> String initializers Arrays of strings
CPE 101 slides based on UW course Lecture 19: Strings Overview Concepts this lecture String constants ull-terminated array representation String library String initializers Arrays of strings
More informationApproximately a Test II CPSC 206
Approximately a Test II CPSC 206 Sometime in history based on Kelly and Pohl Last name, First Name Last 5 digits of ID Write your section number(s): All parts of this exam are required unless plainly and
More informationFeatures of C. Portable Procedural / Modular Structured Language Statically typed Middle level language
1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC
More informationmith College Computer Science CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut
mith College CSC352 Week #7 Spring 2017 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 2 Hours D. Thiebaut Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to Assembly Unix Standard
More informationComputers Programming Course 11. Iulian Năstac
Computers Programming Course 11 Iulian Năstac Recap from previous course Cap. Matrices (Arrays) Matrix representation is a method used by a computer language to store matrices of different dimension in
More informationHigh Performance Computing
High Performance Computing MPI and C-Language Seminars 2009 Photo Credit: NOAA (IBM Hardware) High Performance Computing - Seminar Plan Seminar Plan for Weeks 1-5 Week 1 - Introduction, Data Types, Control
More informationIntroduction to string
1 Introduction to string String is a sequence of characters enclosed in double quotes. Normally, it is used for storing data like name, address, city etc. ASCII code is internally used to represent string
More informationMuntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types
Programming Fundamentals for Engineers 0702113 5. Basic Data Types Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 2 C Data Types Variable definition C has a concept of 'data types' which are used to define
More informationStandard C Library Functions
Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of
More information211: Computer Architecture Summer 2016
211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Data Representation I/O: - (example) cprintf.c Memory: - memory address - stack / heap / constant space - basic data layout Pointer:
More informationWhy arrays? To group distinct variables of the same type under a single name.
Lesson #7 Arrays Why arrays? To group distinct variables of the same type under a single name. Suppose you need 100 temperatures from 100 different weather stations: A simple (but time consuming) solution
More informationFundamentals of Programming. Lecture 11: C Characters and Strings
1 Fundamentals of Programming Lecture 11: C Characters and Strings Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this
More informationC for C++ Programmers
C for C++ Programmers CS230/330 - Operating Systems (Winter 2001). The good news is that C syntax is almost identical to that of C++. However, there are many things you're used to that aren't available
More informationC PROGRAMMING. Characters and Strings File Processing Exercise
C PROGRAMMING Characters and Strings File Processing Exercise CHARACTERS AND STRINGS A single character defined using the char variable type Character constant is an int value enclosed by single quotes
More informationCopyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented
More informationCSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.
Chapter 9 Scanning Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Stephen Scott (Adapted from Christopher M. Bourke) Scanning 9.1 String 9.2 Functions: Assignment
More informationComputer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Scanning Stephen Scott (Adapted from Christopher M. Bourke) 1 / 51 Fall 2009 cbourke@cse.unl.edu Chapter 9 Scanning
More informationComputer Science & Engineering 150A Problem Solving Using Computers
Computer Science & Engineering 150A Problem Solving Using Computers Lecture 07 - Strings Stephen Scott (Adapted from Christopher M. Bourke) 1 / 51 Fall 2009 Chapter 9 9.1 String 9.2 Functions: Assignment
More informationC: How to Program. Week /Mar/05
1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers
More informationThe Design of C: A Rational Reconstruction (cont.)
The Design of C: A Rational Reconstruction (cont.) 1 Goals of this Lecture Recall from last lecture Help you learn about: The decisions that were available to the designers of C The decisions that were
More informationCS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation
CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More informationInput/Output: Advanced Concepts
Input/Output: Advanced Concepts CSE 130: Introduction to Programming in C Stony Brook University Related reading: Kelley/Pohl 1.9, 11.1 11.7 Output Formatting Review Recall that printf() employs a control
More informationC Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017
C Concepts - I/O Lecture 19 COP 3014 Fall 2017 November 29, 2017 C vs. C++: Some important differences C has been around since around 1970 (or before) C++ was based on the C language While C is not actually
More informationConverting a Lowercase Letter Character to Uppercase (Or Vice Versa)
Looping Forward Through the Characters of a C String A lot of C string algorithms require looping forward through all of the characters of the string. We can use a for loop to do that. The first character
More informationFloating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions
Announcements Thursday Extras: CS Commons on Thursdays @ 4:00 pm but none next week No office hours next week Monday or Tuesday Reflections: when to use if/switch statements for/while statements Floating-point
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering
More informationAnnouncements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays
Strings and Pointers Announcements Lab 4 Why are you taking this course? Lab 5 #, 8: Reading in data from file using fscanf Quiz Quiz Strings Special character arrays End in null character, \ char hi[6];
More informationReading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14
Reading Assignment Strings char identifier [ size ] ; char * identifier ; K.N. King Chapter 13 K.N. King Sections 23.4, 23.5 Supplementary reading Harbison & Steele Chapter 12, 13, 14 Strings are ultimately
More informationgcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world
alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1 A Quick guide to C for Networks and Operating Systems
More informationCSci 4061 Introduction to Operating Systems. Input/Output: High-level
CSci 4061 Introduction to Operating Systems Input/Output: High-level I/O Topics First, cover high-level I/O Next, talk about low-level device I/O I/O not part of the C language! High-level I/O Hide device
More informationFundamentals of Programming & Procedural Programming
Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Fundamentals of Programming & Procedural Programming Session Seven: Strings and Files Name: First Name: Tutor: Matriculation-Number: Group-Number:
More informationCS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files
CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as
More informationThe Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!
The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford! 1 Goals of this Lecture"" Help you learn about:! The decisions that were available to the designers of C! The decisions that were made
More informationChapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic
More informationLESSON 4. The DATA TYPE char
LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated
More informationC programming basics T3-1 -
C programming basics T3-1 - Outline 1. Introduction 2. Basic concepts 3. Functions 4. Data types 5. Control structures 6. Arrays and pointers 7. File management T3-2 - 3.1: Introduction T3-3 - Review of
More informationStrings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY
Strings Arrays of characters Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY 1 Basics Strings A string is a sequence of characters treated as a group We have already
More informationCMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012
CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012 TOPICS TODAY Project 5 Pointer Basics Pointers and Arrays Pointers and Strings POINTER BASICS Java Reference In Java,
More informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationLaboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information
Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify
More informationAdvanced C Programming Topics
Introductory Medical Device Prototyping Advanced C Programming Topics, http://saliterman.umn.edu/ Department of Biomedical Engineering, University of Minnesota Operations on Bits 1. Recall there are 8
More informationmith College Computer Science CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut
mith College CSC231 Bash Labs Week #10, 11, 12 Spring 2017 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 4 Hours! D. Thiebaut Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to
More informationGoals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"
Goals of this Lecture The Design of C: A Rational Reconstruction Help you learn about: The decisions that were available to the designers of C The decisions that were made by the designers of C Why? Learning
More informationCSC231 C Tutorial Fall 2018 Introduction to C
mith College CSC231 C Tutorial Fall 2018 Introduction to C Dominique Thiébaut dthiebaut@smith.edu Learning C in 4 Installments! Dennis Ritchie 1969 to 1973 AT&T Bell Labs Close to Assembly Unix Standard
More informationStrings and Library Functions
Unit 4 String String is an array of character. Strings and Library Functions A string variable is a variable declared as array of character. The general format of declaring string is: char string_name
More informationAppendix A Developing a C Program on the UNIX system
Appendix A Developing a C Program on the UNIX system 1. Key in and save the program using vi - see Appendix B - (or some other editor) - ensure that you give the program file a name ending with.c - to
More informationChapter 1 & 2 Introduction to C Language
1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History
More informationUNIT - I. Introduction to C Programming. BY A. Vijay Bharath
UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been
More informationProgramming for Engineers Structures, Unions
Programming for Engineers Structures, Unions ICEN 200 Spring 2017 Prof. Dola Saha 1 Structure Ø Collections of related variables under one name. Ø Variables of may be of different data types. Ø struct
More informationMultiple Choice Questions ( 1 mark)
Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s
More informationArrays array array length fixed array fixed length array fixed size array Array elements and subscripting
Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the
More informationCS Programming In C
CS 24000 - Programming In C Week Two: Basic C Program Organization and Data Types Zhiyuan Li Department of Computer Science Purdue University, USA 2 int main() { } return 0; The Simplest C Program C programs
More informationChapter 9 Strings. With this array declaration: char s[10];
Chapter 9 Strings 9.1 Chapter Overview There is no data type in C called ʻstringʼ; instead, strings are represented by an array of characters. There is an assortment of useful functions for strings that
More informationStandard File Pointers
1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf
More informationCompiling and Running a C Program in Unix
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name
More informationTypes, Operators and Expressions
Types, Operators and Expressions CSE 2031 Fall 2011 9/11/2011 5:24 PM 1 Variable Names (2.1) Combinations of letters, numbers, and underscore character ( _ ) that do not start with a number; are not a
More informationWork relative to other classes
Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language
More informationShould you know scanf and printf?
C-LANGUAGE INPUT & OUTPUT C-Language Output with printf Input with scanf and gets_s and Defensive Programming Copyright 2016 Dan McElroy Should you know scanf and printf? scanf is only useful in the C-language,
More informationFundamentals of Programming Session 4
Fundamentals of Programming Session 4 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2011 These slides are created using Deitel s slides, ( 1992-2010 by Pearson Education, Inc).
More information3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type
Pointer Basics What is a pointer? pointer = memory address + type C Language III CMSC 313 Sections 01, 02 A pointer can contain the memory address of any variable type A primitive (int, char, float) An
More informationContents. Preface. Introduction. Introduction to C Programming
c11fptoc.fm Page vii Saturday, March 23, 2013 4:15 PM Preface xv 1 Introduction 1 1.1 1.2 1.3 1.4 1.5 Introduction The C Programming Language C Standard Library C++ and Other C-Based Languages Typical
More information( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING UNIT V 2 MARKS
( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING FUNCTIONS AND POINTERS UNIT V Handling of Character Strings User-defined Functions
More informationLectures 5-6: Introduction to C
Lectures 5-6: Introduction to C Motivation: C is both a high and a low-level language Very useful for systems programming Faster than Java This intro assumes knowledge of Java Focus is on differences Most
More informationmith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut
mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut dthiebaut@smithedu Outline A Few Words about HW 8 Finish the Input Port Lab! Revisiting Homework
More informationONE DIMENSIONAL ARRAYS
LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers
More informationCS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017
CS 137 Part 6 ASCII, Characters, Strings and Unicode November 3rd, 2017 Characters Syntax char c; We ve already seen this briefly earlier in the term. In C, this is an 8-bit integer. The integer can be
More informationC LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS
C LANGUAGE AND ITS DIFFERENT TYPES OF FUNCTIONS Manish Dronacharya College Of Engineering, Maharishi Dayanand University, Gurgaon, Haryana, India III. Abstract- C Language History: The C programming language
More informationTypes, Operators and Expressions
Types, Operators and Expressions EECS 2031 18 September 2017 1 Variable Names (2.1) l Combinations of letters, numbers, and underscore character ( _ ) that do not start with a number; are not a keyword.
More informationCreate a Program in C (Last Class)
Create a Program in C (Last Class) Input: three floating point numbers Output: the average of those three numbers Use: scanf to get the input printf to show the result a function to calculate the average
More information10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013
Midterm Topic Review Pointer Basics C Language III CMSC 313 Sections 01, 02 1 What is a pointer? Why Pointers? Pointer Caution pointer = memory address + type A pointer can contain the memory address of
More informationtypedef int Array[10]; String name; Array ages;
Morteza Noferesti The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length; Length a, b, len ; Length
More informationPresented By : Gaurav Juneja
Presented By : Gaurav Juneja Introduction C is a general purpose language which is very closely associated with UNIX for which it was developed in Bell Laboratories. Most of the programs of UNIX are written
More informationInput / Output Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain
More information