INC 161 , CPE 100 Computer Programming

Slides:



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

Lecture 2 Introduction to C Programming
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
More about Numerical Computation CS-2301, B-Term More about Numerical Computation CS-2301, System Programming for Non-Majors (Slides include materials.
Introduction to C Programming
Introduction to programming Language C, Data Types, Variables, Constants. Basics of C –Every program consists of one or more functions and must have main.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
 Input and Output Functions Input and Output Functions  OperatorsOperators Arithmetic Operators Assignment Operators Relational Operators Logical Operators.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
CS115 FALL Senem KUMOVA-METİN1 The Fundamental Data Types CHAPTER 3.
Chapter 6 Mathematical Operations. 6.1 Mathematical Expressions In mathematics this expression is valid 0 = -4y + 5 It is invalid in programming Left.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
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.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Dr. Sajib Datta Jan 21,  Declare a variable ◦ int height; [note that no value is still assigned]  Assign a variable a value ◦ height =
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
C Formatted Input/Output
Arithmetic Expressions
CSCE 206 Structured Programming in C
CSE 220 – C Programming Expressions.
Topics Designing a Program Input, Processing, and Output
ARITHMETIC IN C Operators.
Chap. 2. Types, Operators, and Expressions
INC 161 , CPE 100 Computer Programming
INSPIRING CREATIVE AND INNOVATIVE MINDS
Chapter 2 - Introduction to C Programming
Tokens in C Keywords Identifiers Constants
TMF1414 Introduction to Programming
Relational Operations
Chapter 2 - Introduction to C Programming
By: Syed Shahrukh Haider
Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
More about Numerical Computation
Chapter 2 - Introduction to C Programming
A First Book of ANSI C Fourth Edition
Introduction to C Programming
Lectures on Numerical Methods
Chapter 2 - Introduction to C Programming
Lecture3.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
OPERATORS in C Programming
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
OPERATORS in C Programming
Presentation transcript:

INC 161 , CPE 100 Computer Programming Lecture 3 Operator & Expression

Topics CPU Expression Operation Data type: int float char Flow Control if for while Function Data type: int float char Array Pointer Structure CPU 0011010101 0101010000 1001010101 0101010001 0101010110 0010101000 001101110101 010101011000 Input Output Command

Command Compiler translates a language to machine code. 010101000010010101010010001010101010010101010100001010010010100 Add Subtract Compiler Learn this format

Operator & Expression Operator: =, + ,- , < , etc. Expression: 12, a+b, a-3, etc.

The Assignment Operator = The regular assignment operator ‘=‘. It will calculate the right side of = and assign the right variable to the calculated value. When a floating-point number is assigned to an integer variable, the fractional part will be discarded. > int i; > float d = 10.789; > i = d; (i = 10) > i = d + 0.5; (i = 11)

Arithmetic Operators There are five arithmetic operators: + Addition - Subtraction * Multiplication / Division % Modulus The multiplication operator * is needed for multiplication. The result of the % operator is the remainder. If the value of the second operand is zero, the behavior is undefined. The operands of the % operator shall have integer type.

> int i = 10; > i = 5*i; (i = 50) > i = i / 11; (i = 4) > i = 50 % 11; (i = 6)

More Data Type Example from a 32-bit OS char - 8 bit short – 16 bit int – 32 bit float – 32 bit double – 64 bit long double – 128 bit Low order High order

The algorithms and resultant data types of operations depend on the data types of the operand. For binary operations, such as addition, subtraction, multiplication, and division, the resultant data type will take the higher order data type of two operands. For example, the addition of two float numbers will result in a float, while the addition of a float and a double will result in a double. 2 / 3 int / int -> int 0 2.0 / 3 float / int -> float 0.667

Precedence and Associativity of Operators The list of operators are shown on right. Operators at the higher level has precedence over operators at the lower level.

Precedence and Associativity of Operators Example: the order of the precedence for operators *, +, and =. Operator * is the highest, operator = the lowest in the expression i = 2 + 3 *4 > int i; > i = 2+3*4; (i = 14)

Mathematical Function Many mathematical functions are defined in <math.h> sqrt square root pow power sin cos tan trigonometry function abs absolute

Note: there is no exponential operator in C. Mathematical function pow(x, y) can be used to calculate the exponential expression xy. These functions are declared inside the header file math.h /* File: powsqrt.c */ #include <stdio.h> #include <math.h> /* for pow() and sqrt() */ main() { double p, x = 2.0, y = 3.0; p = pow(x,y); printf("pow(2,3) = %f\n", p); printf("sqrt(2) = %f\n", sqrt(x)); } Example: Output: pow(2,3) = 8.000000 sqrt(2) = 1.414214

Relational Operators The relational operators are listed below. Description < less than comparison <= less or equal comparison == equal comparison >= greater or equal comparison > greater comparison != not equal comparison

Examples: True = 1 False = 0 > int i = 5, j = 3 > i < j > j == j 1 // true > i > j > i >= j > i != j > i != i Examples: True = 1 False = 0

Logical Operators There are three logical operators in C: 1) ! --- logical negation 2) && --- logical AND 3) || --- local inclusive OR x y !x x && y x || y 1

Compound Assignment Operators Besides the regular assignment operator, there are ten additional compound assignment operators: 1) += 2) -= 3) *= 4) /= 5) %= 6) &= 7) |= 8) ^= 9) <<= 10) >>= An lvalue is any object that occurs on the left hand side of an assignment statement. It refers to a memory such as a variable or pointer, not a function or constant. The expression lvalue op= rvalue is defined as lvalue = lvalue op rvalue, where lvalue is any valid lvalue. For example, i += 3; is equivalent to i = i+3;

Increment and Decrement Operators The increment operator ++ adds 1 to its operand, and the decrement operator - - subtracts 1. If either is used as a prefix operator, the expression increments or decrements the operand before its value is used. If either is used as a postfix operator, the increment and decrement operation will be performed after its value has been used. Example: i = 5; i++; // i = i+1 i becomes 6 j = ++i; // i = i+1; j = i; i becomes 7 and j is 7 j = i++; // j = i; i = i+1; j is 7 and i becomes 8

Cast Operators (type)expr; Used to convert a value of one type explicitly to a value of another type. C cast operation (type)expr; where expr is an expression and type is a data type of a single object such as char, int, float, double, or and pointer declaration such as char *. Example: > int i = 2, j = 3; > double d; > i/j > 2/3 > d = (double)i/j; // d = 2.0000/3 0.6667

Comma Operator The comma operator ‘,’ introduces comma expression. The comma expression consists of two expressions separated by a comma. For example, a = 1, b=2; This is useful for a for-loop to be described in next chapter. The comma operator is syntactically left-associative. The following expression a = 1, ++a, a + 10; is equivalent to ((a = 1), ++a), a + 10; The left operand of a comma operator is evaluated as a void expression first. Then the right operand is evaluated; the result has its type and value. For example, > a = 1, ++a, a + 10 12 > a 2

The comma operator cannot appear in contexts where a comma is used as a separate item such as the argument list of a function. In these cases, it can be used within parenthesis. For example, the exponential function pow(x,y) defined in the header file math.h for the mathematical expression xy has two arguments. It can be evaluated as shown below. > double x= 2, y = 3 > pow(x,y) // pow(2,3) 8.0000 > pow((x=2, x+3), y) // pow(5,3) 125.0000

Bitwise Operators There are six bitwise operators: Operator Name Description & bitwise AND The bit is set to 1 if the corresponding bits in the two operands are both 1. | bitwise OR The bit is set to 1 if at least one of the corresponding bits in the two operands is 1. ^ bitwise exclusive OR The bit is set to 1 if exactly one of the corresponding bits in the two operands is 1. << left shift Shift the bits of the first operand left by the number of bits specified by the second operand; fill from right with 0 bits. >> right shift Shift the bits of the first operand right by the number of bits specified by the second operand; filling from the left is implementation dependent. ~ One’s complement Set all 0 bits to 1, and all 1 bits to 0.

Example: a 1 0 1 1 0 1 0 0 b 1 1 0 1 1 0 0 1 a & b 1 0 0 1 0 0 0 0 a | b 1 1 1 1 1 1 0 1 a ^ b 0 1 1 0 1 1 0 1 b << 1 1 0 1 1 0 0 1 0 a >> 1 1 1 0 1 1 0 1 0 ~a 0 1 0 0 1 0 1 1 3&5 = 011 & 101 = 001 = 1 4|5 = 100 | 101 = 101 = 5

Input & Output Human Interface Input: Keyboard Mouse Output: Monitor Speaker

Sample Program The CPU computes but you see nothing main () { int i; i = 0; i = i+2; i = i *3; i = i -1; } The CPU computes but you see nothing because you did not tell it to show you

How to show a character on screen? Know where memory of the screen is Know how to send command to the monitor Select the mode of the screen Select the font Fill the pixels correspond to the character Too complicate !

It takes lots of CPU commands to show a character on screen. It also requires knowledge of hardware. OS has a collection of frequent used CPU instructions, wrap them in a single command for easy use.

Library Library is a collection of useful complex commands. CPU commands is native to the compiler. Complex commands are composed on several CPU commands. They are located in a library.

Standard Input/Output library stdio.h is a library that collects input/output related commands. There are many commands, but we will initially cover two commands: printf() - print a set of characters on the screen scanf() - receive input from keyboard

How to use the library? Tell the program to load the library #include <stdio.h> main () { int i = 0; i = i+2; printf(“Hello World”); } Use commands in the library

Introduction to Formatted Input and Output Function printf() Precisely formatted output is accomplished using the output function printf. The printf function has following form printf( format-control-string, arguments ); Format-control-string: Using specifications to describe output format. Each specification begins with a percent sign (%), ends with conversion specified and is enclosed in quotation marks “ “. arguments: correspond to each conversion specification in format-control-string. The printf command is an extra function located in <stdio.h> library.

Format-Control-String Table below lists the format-control-string of different argument types for function printf(). Argument Type Format-Control-String char “%c” signed char, short, int “%d” unsigned char, short, int “%u” octal number “%o” hexadecimal number “%x” float “%f” double “%f” or “%lf” string “%s” pointer “%p”

The program will replace %d with the value of i and print out Double quote argument int i = 12; printf(“The distance is %d meters”, i); The program will replace %d with the value of i and print out The distance is 12 meters

Example: > printf(“%d”, 4261) // decimal integer 4261 > printf(“%ld”, 4261); // decimal long long integer > printf(“%o”, 4261); // octal number 10245 > printf(“%x”, 4261); // hexadecimal number 10a5 > printf(“%f”, 15.0F); // print out a float 15.000000 > printf(“%f”, 15.0); // print out a double float > printf(“%lf”, 15.0); > printf(“%c”, ‘a’); a > printf(“%s”, “This is a string.”); This is a string.

Special Characters

Printing Multiple Numerical Values in a Single Printing Statement Use multiple format specifiers. Each format specifier corresponds to an argument. > printf(”integer is %d, floating-point number is %f”, 10, 12.34) integer is 10, floating-point number is 12.340000

Precision of Floating-Point Numbers The precision of a floating-point number specifies the number of digits after the decimal point character. The precision typically takes the form of a period (.) followed by an decimal integer. For example, the format “%.2f” specifies the precision with 2 digits after the decimal point. > printf(”%.2f”, 12.1234) 12.12 > printf(”%.2f”, 12.5678) 12.57 > printf(”%.20f”, 0.2) 0.20000000000000001110 The fractional part after the specified precision number is rounded up. A floating-point number may not be represented exactly.

Program 1: Calculate the acceleration. /* File: accelvar.c */ #include <stdio.h> main() { /* declare variables */ double a, /* acceleration */ mu, /* friction coefficient */ m, /* mass */ p; /* external force */ /* Initialize variables */ mu = 0.2; m = 5.0; p = 20.0; /* Calculate the acceleration */ a = (p-mu*m*9.81)/m; /* display output */ printf("Acceleration a = %f (m/s^2)\n", a); } Output: Acceleration a = 2.038000 (m/s^2)

Function scanf() Precise formatting input is accomplished using the input function scanf. The scanf function has following form scanf( format-control-string, arguments ); Format-control-string: Using specifications to describe input format. Each specification begins with a percent sign(%), ends with conversion specifier and is enclosed in quotation marks. The format-control-string is similar to format-control-string discussed in printf function. arguments: pointers to variables in which the input value will be stored (a variable name preceded with &).

Format-Control-String Table below lists the format-control-string of different argument types for function scanf(). Argument Type Format-Control-String char “%c” int “%d” unsigned int “%u” float “%f” double “%lf” string “%s” pointer “%p”

Double quote & (indicate pointer) int i; scanf(“%d”, &i); The program will receive keyboard and try to match the keyboard input to the control string.

Example: > int i > float f > double d > char c > scanf(“%d”, &i); 10 > i > scanf(“%f”, &f); 10.2 > f 10.20 > scanf(“%lf”, &d); 15 > d 15.0000 > scanf(“%c”, &c); a > c

Example: > int i > scanf(“%d”, &i); // input number in decimal 4261 > i > scanf(“%o”, &i); // input number in octal 10245 // or ‘010245’ > scanf(“%x”, &i); // input number in hexadecimal 10A5 // or ‘0x10A5’ or ‘0X10A5’

Interactive execution of program scanf.c Example: Program scanfc.c /* File: scanfc.c for input and output example */ #include <stdio.h> main() { int num; double d; printf("Please input an integer and one floating-point number\n”); scanf("%d %lf",&num, &d); printf("Your input values are %d and %f\n“, num, d); } Interactive execution of program scanf.c > scanfc.c Please input one integer and one floating-point number 10 12.3456 Your input number is 10 and 12.345600 >