C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 2 Simple C Programs.
Advertisements

Computer Programming w/ Eng. Applications
Single Variable and a Lot of Variables The declaration int k; float f; reserve one single integer variable called k and one single floating point variable.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
C Programming Day 1 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
One-dimensional character Arrays C does not have string data type. So strings are represented as arrays of characters. The end of the string is marked.
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Please pick up an attendance question and submit in 5 minutes CS 1003 Lecture #3 Sept 12, 2006 Knarig Arabshian.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Chapter 8 Arrays and Strings
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
Basic Input/Output and Variables Ethan Cerami New York
String Escape Sequences
Computer Science 210 Computer Organization Strings in C.
Programming Variables. Named area in the computer memory, intended to contain values of a certain kind (integers, real numbers, characters etc.) They.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Array Lesson 1 CS1313 Spring Array Lesson 1 Outline 1.Array Lesson 1 Outline 2.Mean of a List of Numbers 3.mean: Declarations 4.mean: Greeting,
Input & Output: Console
A First Book of ANSI C Fourth Edition
STRING Dong-Chul Kim BioMeCIS UTA 10/7/
C programming for Engineers Lcc compiler – a free C compiler available on the web. Some instructions.
Chapter 8 Arrays and Strings
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Week 1 Algorithmization and Programming Languages.
1 C Programming Week 2 Variables, flow control and the Debugger.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
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.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
 Integers and Characters  Character Strings  Input and Output.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Pointers *, &, array similarities, functions, sizeof.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Computer Programming for Engineers
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 1 Scott Marino.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Arithmetic Expressions
Chapter 8 Arrays, Strings and Pointers
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
INC 161 , CPE 100 Computer Programming
Arrays in C.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Introduction to CS Your First C Programs
elementary programming
Exercise Arrays.
Presentation transcript:

C Programming Day 2 based upon Practical C Programming by Steve Oualline CS550 Operating Systems

Variable Names Variable names must start with a letter or an underscore No special characters may be used in variable names Letters, digits, or underscores may follow the first character in the variable name

Variable Name Examples Valid avg _pi number_of_students inT Invalid int double the end 3rd_entry all$done

Escape codes \n new line \r return \t tab \' single quote \" double quote \\ backslash

Floating Point vs. Integer Division 19/10 --> 1 Remember to truncate after the decimal point for integer division 19.0 / > / 10 --> / > 1.9

Character Data Type char - denotes the character data type and holds one character char a;

Example Code #include int main(int argc, char ** argv) { char c; //Declaration c = 'A'; //Initialization printf("%c\n", c); //print contents of c printf("%d\n", c); //print c as an int printf(”%u\n", &c); //print the address of c //Assume the address is 1000 return 0; }

Output A Notice that the ASCII code for 'A' is output ASCII codes can be found on the web

Reading Data with scanf Pretend a has an address of 205 &a is 205 in C because the ampersand means “address of” int a; printf("Please enter an integer: "); scanf("%d", &a); //Read data into //memory location 205 printf("a is %d\n", a); printf("The address of a is %u\n", &a);

Running the program gcc addrEx.c –o addrEx.exe or with the Intel compiler icc addrEx.c –o addrEx.exe Output: Please enter an integer: 5 a is 5 The address of a is 205

Multiple inputs with scanf int a, b, c; printf("Enter 3 ints on one line: "); scanf("%d %d %d", &a, &b, &c); printf("%d %d %d", a, b, c); Enter 3 ints on one line:

Field Width Specifiers printf("%c%4c%6c\n", ‘C', 'B', ‘A'); //Use 4 spaces for the 2nd character and 6 for the 3rd character C___B_____A printf(”%2d", 3000); 3000 printf("%5.2lf\n", 6.537); __6.54

Common number of bytes used on 64- bit machines char --> 1 byte float --> 4 bytes double --> 8 bytes long double --> 16 bytes int --> 4 bytes long --> 8 bytes Try the following: printf("%u\n", sizeof(char)); Note that %u represents an unsigned int

Arrays An array is a sequence of data items that are of the same type and are stored contiguously in memory. Elements of an array are accessed using square brackets []. Arrays in C are indexed from zero. type name[size]; //Array declaration //note that the size cannot be changed

Example int intarr[1000]; | | | |... | | Attempting to access data beyond the end of an array will often, but not always, result in a segmentation fault.

Other Examples char carr[4]; double darr[27]; unsigned char ucarr[78]; long larr[12];

More on Arrays An array's size cannot be changed. double darr[27]; We use a subscript or index to access an element of an array. darr[0] darr[19]

More on Arrays darr is the name of the array and represents the address of the first element in the array darr == 200 index |2.3|5.4|0.2|... |7.3| address

Addressing Arrays Notice the address changes by 8 because double values take up 8 bytes. Example darr[20] darr + index*sizeof(double) darr is the starting point in memory. The rest is the offset from the starting point Notice that darr is actually an unsigned integer

Another Example int arr[5] = {7, 25, 13, 2, -3}; | 7 | 25| 13| 2 |-13| We can also use the following and get the same effect int arr[] = {7, 25, 13, 2, -3};

Yet Another Example double data[5] = { 34.0, 27.0, 45.0, 82.0, 22.0 }; double total, avg; total = data[0] + data[1] + data[2] + data[3] + data[4]; avg = total / 5.0; printf("Total %lf\nAvg %lf\n", total, avg);

ASCII Art of the Previous Example data | 34.0| 27.0| 45.0| 82.0| 22.0| total |210.0| avg | 42.0| Total Avg 42.0

Strings In C, a string is a one-dimensional array of characters (type char ). Strings always end with a special character -- the NULL character The NULL character is all caps in C The character '\0', the integer 0, and NULL all represent the same null value in C.

Examples char a = '\0'; //The null character "abc" | 'a' | 'b' | 'c' | '\0'| The length of this string is 3. The size of this array is 4. When declaring an array that will contain a string, be sure to leave one extra character of space for the null character.

String Examples char name[100]; name[0] = 'H'; name[1] = 'e'; name[2] = 'l'; name[3] = 'l'; name[4] = 'o'; name[5] = '\0'; printf("%s\n", name); char name[] = "Hello"; char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};

scanf You can use scanf to read in a string. char name[100]; printf("Enter your name: "); scanf("%s", name); //Recall that name is the //address of the beginning //of the array (string).

scanf Enter your name: Dave name | 'D' | 'a' | 'v' | 'e' | '\0'|

Math Functions in C #include //to use math functions x^y is pow(x,y) pow(2,2) --> 2^2 = 4 double d; d = pow(2,3); d now contains 8.0

Math Functions in C A few other math functions: cos(x)tan(x) sin(x)sqrt(x) d = sqrt( ); //d will contain 10.0

Example #include int main() { double a,b,c; a = 3; b = 4; //compute the square root of a^2 + b^2 c = sqrt(pow(a,2) + pow(b,2)); printf("%lf is a, %lf is b, and %lf is c\n", a, b, c); printf("%lf is a, %lf is b, and %lf is c\n", a, b, sqrt(a*a + b*b) ); return 0; }

Problems with strings and scanf char line[100]; scanf("%s", line); //line is the address printf("%s\n", line); Assume an input of: Hello there The output will be: Hello Why? scanf counts white space as a delimiter.

fgets fgets reads an entire line. Similar to Scanner.readLine() Be sure to leave lots of space in your arrays when using fgets. Function call: fgets(name of string, size of string in bytes, where the input is coming from);

Example of fgets char name[50]; printf("Please enter your name: "); fgets(name, sizeof(name), stdin); //sizeof(name) returns the number // of bytes in the array name. //stdin is standard input. That // means we read from the console

Result Please enter your name: Dave Monismith Dave Monismith <-- has 14 characters name | 'D' | 'a' | 'v' | 'e' | ' ' |...| 't' | 'h' | '\n'| '\0'| Notice that the '\n' character is stored within our string. We need to remove it.

String Functions Use #include strlen(name of string) Provides the length of the string and excludes null character. strlen(name) is 15 We can remove the return character from name as follows: name[strlen(name) - 1] = 0;

sscanf sscanf is string scanf sscanf(name of string, control string, variables);

Example #include int main(int argc, char ** argv){ int a, b; char line[100]; fgets(line,sizeof(line), stdin); sscanf(line, "%d %d", &a, &b); printf("%d %d\n", a, b); }

String Functions To use string functions, #include Sometimes compilers will let you get away without it. strlen - # of characters in a string strcpy - allows you to copy the contents of one string into another strcpy(destination, source); strcat - allows you to concatenate (add to) a string to the end of another string strcat(destination, source); Do NOT use the + operator as you would in Java name1 = name1 + name2; //Don't do this in C

Example char first[100]; char last[100]; char full_name[200]; printf("%s%s","Please enter your ", "first name: "); fgets(first, sizeof(first), stdin); fgets(last, sizeof(last), stdin);

Example //Remove newline characters first[strlen(first) - 1] = '\0'; last[strlen(first) - 1] = '\0'; strcpy(full_name, first); strcat(full_name, " "); strcat(full_name, last); printf("%s\n", full_name);

String Comparison strcmp(str1, str2) result is zero if two strings are lexicographically equivalent A --> 65 a --> 97 Try the following: strcmp("a", "a"); strcmp("A", "a"); strcmp("a", "A");

Shorthand Operators a = a + 2; is the same as a += 2 Other operators include +=-=*=/=

Pre/Post Operators ++ adds one to a variable/expression (increment) -- subtracts one from a variable or expression (decrement) a++; //Post increment ++a; //Pre increment

Pre Increment Example //Try this a = 1; printf("%d\n", ++a); //Result is the same as a = a + 1; printf("%d\n", a);

Post Increment Example //Try this a = 1; printf("%d\n", a++); //Result is the same as printf("%d\n", a); a = a +1;

Problems with Pre/Post Increment value = 1; //Results from the following assignment //statement are undefined in the //C standard result = (value++ * 5) + (value++ * 3);

Example Answer 1 Evaluation could occur as follows: 1 * 5 = 5 value = 2 2 * 3 = 6 value = 3 result = 11

Example Answer 2 Or: 1 * 3 = 3 value = 2 2 * 5 = 10 value = 3 result = 13

Assignment Operator Don't play around with the assignment operator either a = (b = 2) + (c = 3); //is a valid C statement //Don't do this!

Multi-dimensional Arrays type arrayname[dim1][dim2][dim3]... int arr[2][3]; Example arr[1][0] = 23;