program structure declarations and definitions expressions and statements more standard I/O

Similar documents
introduction week 1 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 20 imperative programming about the course

Variables and literals

Add Subtract Multiply Divide

LESSON 4. The DATA TYPE char

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

arrays and strings week 3 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 22 imperative programming review

Unit 3. Operators. School of Science and Technology INTRODUCTION

block structure, scope and macros

C: How to Program. Week /Mar/05

8. Characters and Arrays

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

scanf erroneous input Computer Programming: Skills & Concepts (CP) Characters Last lecture scanf error-checking our input This lecture

Tail recursion. Decision. Assignment. Iteration

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

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

COSC2031 Software Tools Introduction to C

Full file at

Basics of Java Programming

Programming for Engineers Introduction to C

Introduction to C Programming

Imperative Programming

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Fundamental of Programming (C)

Chapter 2 - Introduction to C Programming

Lecture 4 CSE July 1992

COP4020 Programming Assignment 1 - Spring 2011

Operators. Lecture 3 COP 3014 Spring January 16, 2018

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

CS102: Variables and Expressions

Our Strategy for Learning Fortran 90

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

LECTURE 3 C++ Basics Part 2

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Reminder. Sign up for ee209 mailing list. Precept. If you haven t received any from ee209 yet Follow the link from our class homepage

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

AN INTRODUCTION PROGRAMMING. Simon Long

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Iteration. Side effects

Lecture 3. More About C

QUIZ: What value is stored in a after this

SWEN-250 Personal SE. Introduction to C

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Multiple Choice Questions ( 1 mark)

Chapter 1 & 2 Introduction to C Language

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Language Reference Manual

Chapter 2. C++ Basics

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Should you know scanf and printf?

3. Simple Types, Variables, and Constants

Creating a C++ Program

Chapter 4 C Program Control

Chapter 3: Operators, Expressions and Type Conversion

Introduction to C. CS 2060 Week 1. Prof. Jonathan Ventura. Outline Introduction Introduction to C Homework 1 C Coding Style Wrap-up

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

BASIC ELEMENTS OF A COMPUTER PROGRAM

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

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

Course Outline. Introduction to java

C Examples. Goals of this Lecture. Overview of this Lecture

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

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Objectives. In this chapter, you will:

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C-programming. Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature

Introduction to Programming

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

C-LANGUAGE CURRICULAM

Chapter 2: Programming Concepts

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Strings. Steven R. Bagley

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Mid-term Exam. Fall Semester 2017 KAIST EE209 Programming Structures for Electrical Engineering. Name: Student ID:

Language Design COMS W4115. Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science

Typescript on LLVM Language Reference Manual

1 Lexical Considerations

Goals of this Lecture

Princeton University Computer Science 217: Introduction to Programming Systems. Goals of this Lecture. A Taste of C. Agenda.

2.8. Decision Making: Equality and Relational Operators

Control Statements: Part Pearson Education, Inc. All rights reserved.

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Fundamentals of Programming

Visual C# Instructor s Manual Table of Contents

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

Transcription:

imperative week 2 and definitions expressions and more standard I/O Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 21

: typical #include <header-file.h>... // library, definitions global variable and definitions... function and definitions... int main() { main program code... 0; } Ian Piumarta 2 / 21

the CPU deals only with patterns of bits representing numbers the basic in C reflect this C has only two basic : numeric types (integers and floating point numbers) no value (the absence of any value at all) the numeric types are integers and floating point numbers the default integer type is called int it represents the natural size of integer arithmetic on your CPU on desktop / laptop machine, an int is usually 32 bits wide if you need to store larger values then use a long integer on a 64-bit processor, a long is usually 64 bits wide Ian Piumarta 3 / 21

every variable has to be declared before it can be used a variable declaration specifies the type of the variable the name of the variable optionally: the initial value of the variable written using the assignment operator = type name; type name = expression; one or more can be declared in the same declaration int a; int b= 2; long c, d= 3, e= 4, f; note that declared inside a function are local to that function declared outside any function are global Ian Piumarta 4 / 21

if no initial value is given, the variable s value should be considered unknown the compiler usually warns you about using an uninitialised variable main.c:10:15: warning: variable a is uninitialized when used here int a, b= a; ˆ pro-tip: always initialise your, even when you don t need to prevents nasty surprises when optimising, the compiler will remove unnecessary s Ian Piumarta 5 / 21

: arithmetic and relational C s should be familiar many in Python and Java are named after similar ones in C operator operation () function call putchar(42); highest precedence ++ -- increment and decrement ++x; * / % multiply, divide, modulus dow = day % 7; + - addition, subtraction sum = x + y; < <= > >= arithmetic relations while (x < y) x = x * 2; ==!= equal, not-equal if (getchar() == \n ) ++nlines; && logical and if (happy && know_it) clap(); logical or success = plana() planb(); = assignment a = 42; lowest precedence note: logical and/or a && b x && y // these are the ones you need most often are quite different to arithmetic and/or a & b x & y // these are for serious hackers which we will discuss further in a week or two Ian Piumarta 6 / 21

: arithmetic and relational note that equality == and assignment = are similar easy to write = when you mean == this is bad, because x = y is an expression in C what is wrong with this? if (c = \n ) ++nlines; pro-tip: avoid the above mistake by writing assignment asymmetrically (no space on left, one space on right) if (x == y) x= -y; // easy to see = and == are different putting constants on the left side of the == operator if (c = \n ) ++nlines; // what I spent a week finding and debugging if (c == \n ) ++nlines; // what I really wanted the program to do if ( \n == c) ++nlines; // much safer way to type what I wanted, because... if ( \n = c) ++nlines; // this causes a compile-time error (yay!) I used to spend hours finding if (c = \n )... (and similar) bugs since adopting the above style I completely stopped making this kind of error Ian Piumarta 7 / 21

: programs (function bodies) are made from sequences of expression : expression; any expression can be a statement: just put ; after it putchar(getchar()); // getchar() is an expression getchar(); // or a statement x == y; // useless, but legal ; // empty statement compound (blocks): {statement... } group zero or more into a single statement { // <--- beginning of block firstthing(); secondthing(); } // <--- end of block {} // empty (compound) statement {;;;;;;} // ditto {}; // beware: this is two! Ian Piumarta 8 / 21

: if (condition) statement if (condition) statement else statement control whether or not something is executed note: the parentheses around the condition are mandatory if (somecondition) dosomething(); // runs only if somecondition is true if (raining) stayhome(); else havepicnic(); // executed if it is raining // executed if it is not raining Ian Piumarta 9 / 21

: pro-tip: use compound in if, even when unnecessary if (raining) stayhome(); else havepicnic(); goshopping(); if (raining) { stayhome(); } else { havepicnic(); goshopping(); } // oops: will go shopping regardless of weather // ready for more if necessary // much safer! // no more shopping in the rain... and always when necessary for disambiguation! ambiguous else z() if a and not b z() if not a if (a) if (b) y(); else z(); if (a) { if (b) y(); else z(); } if (a) { if (b) y(); } else z(); Ian Piumarta 10 / 21

note: be careful with compound and semicolons : if (serioussecurity()) if (authorised()) {}; // do nothing else selfdestruct(); // when does this explode? nested if...else... can be confusing if (raining()) watchmovie(); else if (sunny()) sunbathe(); else walkdog(); pro-tip: format your code to make it more readable if (raining()) watchmovie(); else if (sunny()) sunbathe(); else walkdog()(); useful idiom: if (0) statement // temporarily disable statement Ian Piumarta 11 / 21

: while loop while (condition) statement; execute statement while condition remains true useful idioms: while (1) dosomething(); // repeat forever while (stillwaiting()) {} // do nothing while waiting while (stillwaiting()); while (stillwaiting()) ; // ditto, but maybe less readable // ditto, possibly an improvement Ian Piumarta 12 / 21

every function has to be declared or defined before it can be used a function declaration specifies the type of the result the name of the function a parenthesised list of zero or more parameters, separated by commas each parameter looks like a complete variable declaration optionally: the implementation of the function written as a compound statement type functionname(parametertype parametername,...); // declaration type functionname(parametertype parametername,...) { statement... } // definition a function can be declared any number of times but every declaration must be the same a function can be defined only once Ian Piumarta 13 / 21

pass zero or more arguments to a function when called function(expression,...) the argument expressions must match the declaration of function same number of arguments as declared parameters each argument type must match the corresponding parameter declaration int putchar(int c); putchar(); putchar("*"); putchar( x, y ); // as declared in stdio.h // bad: wrong number of arguments // bad: wrong type of argument // bad: wrong number of arguments putchar(42); // ok (but ignores result) int error= putchar( * ); // ok Ian Piumarta 14 / 21

the statement s a result from a function value; the type of value must match the function declaration C s other basic data type is void, which means no value at all if your function takes no arguments, declare its parameters as void if your function s nothing, declare its result type as void you can still use inside, but it must not have any value void byanymeansnecessary(void) { if (plana()) ; // yay success! if (planb() planc()) ; // try another tactic giveup(); // it s pointless } Ian Piumarta 15 / 21

more standard is performed on streams of bytes getchar reads one character from the standard input e.g., from your keyboard or from a disk file putchar sends one character to the standard output e.g., to your terminal window or to a disk file writing one character at a time is tedious, so we have... and puts("hello, world") ("hello, world\n") // write string and newline to output // write string to output Ian Piumarta 16 / 21

more standard puts does for strings what putchar does for is more complicated it can be called with more than one argument it sends each character in its first argument (a format string) to the output if it sees a %letter sequence within that string, it reads another parameter from the arguments that were supplied converts that argument into a string, and sends that string to the output for example %c converts an integer argument into the corresponding single character %d converts an integer argument into its decimal representation ("the character %c has integer value %d\n", 42, 42); ("the character %c has integer value %d\n",!,! ); produces the following output the character * has integer value 42 the character! has integer value 33 Ian Piumarta 17 / 21

more standard standard input and output can be connected to real when running a command, connect the standard input to a file like this $ command < input-filename and/or the standard output to a file like this $ command > output-filename warning: be very careful when redirecting output to a file if the file already exists, it will be deleted and then recreated do not type > file.c when you really mean < file.c! especially if you care about losing the contents of file.c Ian Piumarta 18 / 21

more standard imagine a program is reading from a file (not the terminal), then how does the program know when it reaches the end of the file? have values in the range [0, 255] getchar s an int value in this range when the input reaches the end of the file, getchar must somehow tell you use a sentinel value that is outside the above range use the sentinel value to indicate the end of file the value is given the symbolic name EOF EOF is a constant defined in stdio.h always check the value ed by getchar when getchar s EOF, you have reached the end of the file note: typing ˆD on the keyboard generates EOF Ian Piumarta 19 / 21

character tests the defined in ctype.h are useful when dealing with #include it at the top of your program, then you can call // these which non-zero (true) if c is... int isspace(int c); // whitespace (space, tab, newline) int isalpha(int c); // alphabetic (a letter) int isupper(int c); // an upper-case letter (A...Z) int islower(int c); // a lower-case letter (a...z) // or theses... which... int toupper(c); // convert c to upper case int tolower(c); // convert c to lower case run man ctype to see a (long) list of them all most of them have self-explanatory names, but if in doubt... run man isalpha (for example) to see an explanation of what it tests for Ian Piumarta 20 / 21

putting it all together how would you modify your program from last week to echo indefinitely, until the is reached? delete all the vowels from the input? print a summary of how many vowels were deleted? Ian Piumarta 21 / 21