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

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

Add Subtract Multiply Divide

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

Lecture 3. More About C

بسم اهلل الرمحن الرحيم

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Programming for Engineers Introduction to C

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

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

ANSI C Programming Simple Programs

Computer System and programming in C

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Course Outline Introduction to C-Programming

These are reserved words of the C language. For example int, float, if, else, for, while etc.

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

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

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Should you know scanf and printf?

CS313D: ADVANCED PROGRAMMING LANGUAGE

2. Numbers In, Numbers Out

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Structured Program Development

LECTURE 3 C++ Basics Part 2

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

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

Fundamental of Programming (C)

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

CS1100 Introduction to Programming

Unit 3. Operators. School of Science and Technology INTRODUCTION

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

Operators & Expressions

Fundamentals of Programming

Full file at

CS 106 Introduction to Computer Science I

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++

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Functions and Recursion

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

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

Variables and literals

Objectives. In this chapter, you will:

Reserved Words and Identifiers

CSE 130 Introduction to Programming in C Control Flow Revisited

Course Outline. Introduction to java

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Lecture 3 Tao Wang 1

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

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

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

BASIC ELEMENTS OF A COMPUTER PROGRAM

2. Numbers In, Numbers Out

Chapter 4: Control Structures I (Selection)

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

Chapter 2. C++ Basics

Informatica e Sistemi in Tempo Reale

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

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

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

Operators and Control Flow. CS449 Fall 2017

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

C - Basic Introduction

Basics of Programming

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Dept. of CSE, IIT KGP

n Group of statements that are executed repeatedly while some condition remains true

Chapter 2, Part III Arithmetic Operators and Decision Making

Expression and Operator

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Chapter 3 Structured Program Development

Selection Statements. Pseudocode

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Unit 4. Input/Output Functions

The C++ Language. Arizona State University 1

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

ECE 122 Engineering Problem Solving with Java

Programming and Data Structures

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

UNIT- 3 Introduction to C++

Flow Control. CSC215 Lecture

Operators And Expressions

Visual C# Instructor s Manual Table of Contents

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

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

Fundamentals of Programming

Chapter 4: Basic C Operators

Conditional Statement

Chapter 1 & 2 Introduction to C Language

C++ Programming: From Problem Analysis to Program Design, Third Edition

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

QUIZ: What value is stored in a after this

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Transcription:

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

Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the whole part of the division (the quotient) 12 / 3 is 4 15 / 2 is 7 Modulus (%) returns the remainder 12 % 3 is 0 15 % 2 is 1

Short hand Operators Some operators are shortcuts for others Ex. +=, -=, *=, /=, %=, ++, and -- x += 5; is the same as x = x + 5; y++; is the same as y = y + 1;

The Increment (++) and Decrement (--) Operators When used by themselves, y++ and ++y have identical results In an expression, they have different results The relative order of the operator matters: y++: use y s current value, then increment it ++y: increment y, then use the new value The same is true for decrement (--)

Operator Precedence Precedence rules specify the order in which operators are evaluated Remember PMDAS: Parentheses, Multiplication, Division, Addition, Subtraction Associativity determines left-right order

Precedence Examples 3-8 / 4 / has the highest precedence, so we compute 8 / 4 first, then subtract the result from 3 Equivalent expression: 3 - (8 / 4) What is the value of 3 * 4 + 18 / 2?

Precedence Examples 5-3 + 4 + 2-1 + 7 + and - have equal precedence, so this expression is evaluated left to right: (((((5-3) + 4) + 2) - 1) + 7) The innermost parentheses are evaluated first

Parentheses Parentheses can be used to force a different order of evaluation: 12-5 * 2 produces 2 (12-5) * 2 produces 14

Expression Examples What do the following expressions evaluate to? 1 + 2 * 3 (1 + 2) * 3 13 % 5 23 % 4 * 6

More Expression Examples 27.0 / 6.0 27.0 / 6 27 / 6 Given: int x = 5; int y = x++ * 6; int y = ++x * 6;

printf() and scanf() revisited Each of these functions takes a list of arguments (input values): a control string an optional list of other arguments (data) The control string determines how the other arguments are displayed

Control Strings A control string may contain one or more conversion specifications (formats) conversion specifications are replaced (or substituted) by the arguments that follow the control string, in order They begin with a % and end with a conversion character For example, the statement printf( %s, abc ); will replace %s with abc in the final output

printf() Conversion Characters Conversion character c d e f g s How the corresponding argument is printed as a character as a decimal integer as a floating-point number in scientific notation as a floating-point number in the e-format or f-format, whichever is shorter as a string

Three Equivalent Statements printf( abc ); printf( %s, abc ); printf( %c%c%c, a, b, c );

Fields A field is the area where an argument is printed The field width is the number of characters that make up the field Field width can be specified as an integer between the % and the conversion character For example, printf( %c%3c%5c, a, b, c ); will print a b c

Control Strings for scanf() scanf() is used to collect user input from the keyboard It is called with a control string and a list of addresses The control string conversion specifiers describe how the input stream characters should be interpreted The addresses correspond to the memory locations where variables are stored

Parsing Data scanf() will skip whitespace (tabs, blanks, and newlines) when reading in numbers Whitespace is NOT skipped when scanf() is reading in characters

scanf() Conversion Characters Conversion character How input stream characters are converted c as a character d as a decimal integer f as a floating-point number (float) lf or LF as a floating-point number (double) s as a string

#include <stdio.h> int main(void) { char c1, c2, c3; int i; float x; double y; printf( \n%s\n%s, Input three characters,, an int, a float, and a double: ); } scanf( %c%c%c%d%f%lf, &c1, &c2, &c3, &i, &x, &y); printf( \nhere is the data that you typed in:\n ); printf( %3c%3c%3c%5d%17e%17e\n\n, c1, c2, c3, i, x, y); return 0;

Return Values printf() and scanf() each return an integer value when they complete printf() returns the number of characters printed, or a negative value if an error occurred scanf() returns the number of successful conversions or the system-defined end-of-value.

Flow of Control

Control Flow Normally, C programs are executed sequentially We can alter this process using conditionals (which provide alternative actions) and loops (which repeat groups of statements)

Conditions Conditional statements execute a test to determine which path to follow This test consists of an expression that is evaluated Normally, this expression compares two or more values

True and False Values Any expression with a non-zero value is considered to be true Ex. 1, 3.14159, -23 An expression is only false if its value is 0 Common programming error: using = (assignment) instead of == (equality) Ex. if (x = 5)

Relational Operators Operator Meaning Example < Less than age < 30 > Greater than height > 6.2 <= Less than or equal to taxable <= 20000 >= Greater than/equal to temp >= 98.6 == Equal to grade == 100!= Not equal to number!= 250

The if Statement General form: if ( condition ) statement (or block of statements) to be executed if condition is true Ex. if (length < 2) printf( Too short!\n );

The if-else Statement Select one of two possible execution paths, based on the result of a comparison General format: if ( expression ) statement block 1 else statement block 2

Compound Statements if and else only execute a single following statement We can get around this by enclosing multiple statements in curly braces The resulting block is called a compound statement Style suggestion: always use curly braces around the body of an if or else clause

if (key == F ) { contemp = (5.0/9.0) * (intemp - 32.0); printf( Converted to Celsius\n ); } else { contemp = (9.0/5.0) * intemp + 32.0; printf( Converted to Fahrenheit.\n ); }

Iterative Programming Many programs perform the same task many times Operations are repeated on different data Ex.Adding a list of numbers Ex. Displaying a menu of options Repetitive tasks are specified using loops

Loop Elements All loop constructs share four basic elements: 1.Initialization 2.Testing the loop condition 3.The loop body (the task to be repeated) 4.The loop update The order of these elements may vary

Initialization This section of code is used to set starting values For example, setting a total to 0 initially This can be done as part of the loop, or separately before the loop code begins

Loop Tests Test expressions are used to determine whether the loop should execute (again) Tests compare one value/variable with another If the test evaluates to TRUE, then the loop will execute another time

Loop Update This step changes the value(s) of the loop variable(s) before the loop repeats Ex. moving to the next item to process This can be done explicitly as part of the loop, or it can be done inside the loop body

while Loops while loops can execute an arbitrary number of times Order of execution: 1. Initialization 2. Loop condition test 3. Loop body 4. Loop update

General Form initialization while ( loop condition test ) { loop body loop update }

while Loop Example int countdown = 5; while (countdown >= 0) { printf( %d..., countdown); countdown--; }

Loop Output 5...4...3...2...1...0...

Another Example int root = 0; while (root < 10) { root += 1; printf( %d * %d =, root, root); printf( %d\n, root * root); }

root output 0 1 * 1 = 1 1 2 * 2 = 4 2 3 * 3 = 9 3 4 * 4 = 16 4 5 * 5 = 25 5 6 * 6 = 36 6 7 * 7 = 49 7 8 * 8 = 64 8 9 * 9 = 81 9 10 * 10 = 100

for Loops for loops execute a fixed number of times Order of execution: 1.Initialization 2.Loop condition test 3.Loop body 4.Loop update

General Form for ( initialization ; loop condition test ; loop update ) { loop body }

for Loop Example int i; for (i = 0; i < 10; i++) { printf( %d, i); }

Loop Output 0123456789

Another Example int nextnumber, i, sum = 0; for (i = 0; i < 5; i++) { printf( \nenter a number: ); scanf( %d, nextnumber); sum += nextnumber; }

i nextnumber sum - - 0 0 2 2 1 15 17 2 5 22 3 7 29 4 3 32 5-32