David Notkin Autumn 2009 CSE303 Lecture 9 Dictionary.com, "c," in The American Heritage® Abbreviations Dictionary, Third Edition. Source location: Houghton.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
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.
Kernighan/Ritchie: Kelley/Pohl:
David Notkin Autumn 2009 CSE303 Lecture 10 "If it weren't for C, we'd be writing programs in BASI, PASAL, and OBOL."
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
1 CSE 303 Lecture 8 Intro to C programming read C Reference Manual pp. Ch. 1, , 2.6, 3.1, 5.1, , , , Ch. 8 ; Programming.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
Computer Science 210 Computer Organization Introduction to C.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
Chapter 2 : Overview of C By Suraya Alias. /*The classic HelloWorld */ #include int main(void) { printf(“Hello World!!"); return 0; }
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Yu Yuanming CSCI2100B Data Structures Tutorial 3
By Sidhant Garg.  C was developed between by Dennis Ritchie at Bell Laboratories for use with the Unix Operating System.  Unlike previously.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
1 計算機程式設計 Introduction to Computer Programming Lecture01: Introduction and Hello World 9/10/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction.
David Notkin Autumn 2009 CSE303 Lecture 12 October 24, 2009: Space Needle.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Chapter 3: Formatted Input/Output Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Introduction to Programming
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
CS 100Lecture 211 Announcements P5 due on Thursday FINAL EXAM Tuesday August 10, 8AM, Olin 155 Review sessions on Thursday and Friday Final grades posted.
Khalid Rasheed Shaikh Computer Programming Theory 1.
CSC141 Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture - 6.
Basic I/O in C Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens Stream Model of I/O header file: A stream provides a connection.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
E-1 University of Washington Computer Programming I Lecture 5: Input and Output (I/O) © 2000 UW CSE.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
CS 1704 Introduction to Data Structures and Software Engineering.
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
C is a high level language (HLL)
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Basic Data Types & Memory & Representation. Basic data types Primitive data types are similar to JAVA: char int short long float double Unlike in JAVA,
Chapter 3: Formatted Input/Output 1 Chapter 3 Formatted Input/Output.
Java Programming Language Lecture27- An Introduction.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
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.
C++ Lesson 1.
Formatted Input and Output
Chapter 7 User-Defined Methods.
Computer Science 210 Computer Organization
CSE 303 Lecture 9 C programming: types, functions, and arrays
A bit of C programming Lecture 3 Uli Raich.
Input/output.
Plan of the Day: More on type conversions scanf printf format strings
DATA HANDLING.
Computer Science 210 Computer Organization
Introduction to CS Your First C Programs
CS100A Lecture November 1998 Prelim 3 Statistics Maximum 94
Suggested self-checks: Section 7.11 #1-11
Module 2 Variables, Data Types and Arithmetic
Presentation transcript:

David Notkin Autumn 2009 CSE303 Lecture 9 Dictionary.com, "c," in The American Heritage® Abbreviations Dictionary, Third Edition. Source location: Houghton Mifflin Company, Available: Accessed: October 19,

Today Some C leftovers from Friday Primitive data types: integers, real numbers, characters, Boolean Functions Arrays Strings (briefly) CSE303 Au092

Mostly the same as Java Variables –can be used without being initialized (!) –must be declared at the start of a function or block (changed in C99) for loops –variable cannot be declared in the loop header if/else statements, while and do/while loops –there is no boolean type(changed in C99) –any type of value can be used as a test –0 means false, every other number means true Parameters / returns –C has certain features for values vs. references ("pointers")

Very different from Java Strings –very clunky to use in C; arrays of characters –are not objects; do not contain methods (external string functions) I/O to/from console and files –no Scanner; must use input functions such as scanf –console I/O different than file I/O Errors and exceptions –C has no try/catch and does not represent errors as objects –errors are usually returned as integer error codes from functions –crashes are mostly called "segmentation faults" and are not of much direct utility in figuring out what is wrong

Also very different Arrays –are just bare contiguous blocks of memory –have no methods and do not know their own length (!) Objects –C doesn't have them –closest similar feature: struct (a set of fields; no methods) Memory management –most memory that you consume, you must explicitly free afterward API and provided libraries –C doesn't have very many, compared to Java –you must write many things yourself (even data structures)

printf continued A placeholder can specify the parameter's width or precision: –%8d an integer, 8 characters wide, right-aligned –%-8d an integer, 8 characters wide, left-aligned –%.4f a real number, 4 digits after decimal –%6.2f a real number, 6 total characters wide, 2 after decimal Examples: int age = 45; double gpa = ; printf("%8d %7.3f\n", age, gpa); printf("%8.2f %.1f %10.5f", gpa, gpa, gpa);

scanf scanf("format string", variables); uses same syntax for formatted strings, placeholders as printf Must precede each variable with an & (address-of operator) int x; int y; printf("Type your x and y values: "); scanf("%d %d", &x, &y); functiondescription scanf reads formatted input from console

scanf continued scanf returns the number of values successfully read: can be examined to see whether the reading was successful if # of variables listed doesn't match # of format placeholders –too many variables:later ones ignored –too few variables:program crashes!

Practice exercise [if you want] Write a C program that makes change: –prompts the user for an amount of money –reports the number of pennies, nickels, dimes, quarters, and dollars Example Amount of money? Pennies : 2 Nickels : 1 Dimes : 1 Quarters: 3 Dollars : 17

Primitive numeric types –integer types: char (1B), short (2B), int (4B), long (8B) –real numbers: float (4B), double (8B) –modifiers: short, long, signed, unsigned (non-negative) typebytesrange of values printf char 1 0 to 255 %c short int 2 -32,768 to 32,767 %hi unsigned short int 2 0 to 65,535 %hu int 4 -2,147,483,648 to 2,147,483,647 %d, %i unsigned int 4 0 to 4,294,967,295 %u long long int 8 -9e18 to 9e %lli float 4 approx to %f double 8 approx to %lf long double 12 A lot! %Lf

const variables const type name = expression; –declares a variable whose value cannot be changed Example: const double MAX_GPA = 4.0;... MAX_GPA = 4.5; // grade inflation! (error) –The compiler will issue this warning: warning: assignment of read-only variable 'MAX_GPA'

Boolean type #include... bool b = false; C doesn't actually have a Boolean type (anything can be a test) including stdbool.h gives a pseudo-Boolean type bool (C99) –false is really a macro alias for 0 –true is really a macro alias for 1

Anything wrong here if (x < y == true) {... } bool b2 = x < 10; CSE303 Au0913

Quintessential C bug int x; printf("Please type your age: "); scanf("%d", &x); if (x = 18) { printf("You can now vote!\n"); }

Defining a function returnType name(type name,..., type name) { statements; } Example int sumTo(int max) { int sum = 0; int i; for (i = 1; i <= max; i++) { sum += i; } return sum; }

Problem: function ordering You cannot call a function that has not been declared (defined) yet int main(void) { int sum = sumTo(100); printf("The sum is %i\n", sum); return 0; } // sumTo is not declared until here int sumTo(int max) {... } Solution : Reverse the order of function definition, or...

Array usage type name[size] = {value, value,..., value}; –allocates an array and fills it with pre-defined element values –if fewer values are given than the size, the rest are filled with 0 name[index] = expression; // set an element int primes[6] = {2, 3, 5, 6, 11, 13}; primes[3] = 7; int allZeros[1000] = {0}; // 1000 zeros

Multi-dimensional arrays type name[rows][columns]; –creates a two-dimensional array of given sizes, full of garbage data type name[rows][columns] = {{values},..., {values}}; –allocates a 2D array and fills it with pre-defined element values int grid[10][10]; int matrix[3][5] = { {10, 5, -3, 17, 82}, { 9, 0, 0, 8, -7}, {32, 20, 1, 0, 14} };

Exercise Write a complete C program that outputs the first 16 Fibonacci numbers in reverse order, 8 numbers per line, 6 spaces per number

Arrays as parameters Arrays do not know their own size; they are just memory chunks – harder than in Java int sumAll(int a[]); int main(void) { int numbers[5] = {7, 4, 3, 15, 2}; int sum = sumAll(numbers); return 0; } int sumAll(int a[]) { int i, sum = 0; for (i = 0; i <... ??? }

Solution 1: declare size Declare a function with the array's exact size int sumAll(int a[5]); int main(void) { int numbers[5] = {7, 4, 3, 15, 2}; int sum = sumAll(numbers); return 0; } int sumAll(int a[5]) { int i, sum = 0; for (i = 0; i < 5; i++) { sum += i; } return sum; }

Solution 2: pass size Pass the array's size as a parameter int sumAll(int a[], int size); int main(void) { int numbers[5] = {7, 4, 3, 15, 2}; int sum = sumAll(numbers, 5); return 0; } int sumAll(int a[], int size) { int i, sum = 0; for (i = 0; i < size; i++) { sum += i; } return sum; }

Returning an array arrays (so far) disappear at the end of the function: this means they cannot be safely returned int[] copy(int a[], int size); int main(void) { int numbers[5] = {7, 4, 3, 15, 2}; int numbers2[5] = copy(numbers, 5); // no return 0; } int[] copy(int a[], int size) { int i; int a2[size]; for (i = 0; i < size; i++) { a2[i] = a[i]; } return a2; // no }

Solution: output parameter workaround: create the return array outside and pass it in -- "output parameter" works because arrays are passed by reference void copy(int a[], int a2[], int size); int main(void) { int numbers[5] = {7, 4, 3, 15, 2}; int numbers2[5]; copy(numbers, numbers2, 5); return 0; } void copy(int a[], int a2[], int size) { int i; for (i = 0; i < size; i++) { a2[i] = a[i]; }

A bit about strings (more soon) String literals are the same as in Java –printf("Hello, world!\n"); –but there is not actually a String type in C; they are just char[] Strings cannot be made, concatenated, or examined as in Java: String s = "hello"; // no int answer = 42; printf("The answer is " + answer); // no int len = "hello".length(); // no int printMessage(String s, int times) {... // no

Exercise Modify the previous program to prompt the user twice for a number and print that many Fibonacci numbers in reverse order, 8 numbers per line, 6 spaces per number. How many Fibonacci numbers? How many Fibonacci numbers?

Questions? CSE303 Au0927