C Programs: Simple Statements and Expressions

Similar documents
INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

C Functions. 5.2 Program Modules in C

Functions. Systems Programming Concepts

ECET 264 C Programming Language with Applications

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Programming in C Quick Start! Biostatistics 615 Lecture 4

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Preview from Notesale.co.uk Page 2 of 79

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Using Free Functions

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Calling Prewritten Functions in C

1st and 3rd September 2015

Primitive Data Types: Intro

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

CSE123. Program Design and Modular Programming Functions 1-1

Expressions and operators

Introduction to Programming

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Operators and Expressions:

Introduction to C Language

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Chapter 4: Basic C Operators

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

ANSI C Programming Simple Programs

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University

CT 229 Java Syntax Continued

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

Functions and Recursion

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Chapter 3 - Functions

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

Fundamentals of Programming & Procedural Programming

Assoc. Prof. Dr. Tansu FİLİK

Programming in C. Part 1: Introduction

9 C Language Function Block

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

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Basics of Programming

Beginning C Programming for Engineers

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

Computer Science & Engineering 150A Problem Solving Using Computers

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

C Programming

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Data Types and Variables in C language

ENGI Introduction to Computer Programming M A Y 2 8, R E Z A S H A H I D I

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Operators & Expressions

Department of Computer Science

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Programming for Engineers Introduction to C

Lecture 2:- Functions. Introduction

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Expressions and Casting

CS110: PROGRAMMING LANGUAGE I

Operators. Java operators are classified into three categories:

Chapter 1 Getting Started Structured Programming 1

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Arithmetic Expressions in C

Split up Syllabus (Session )

Methods: A Deeper Look

Multiple Choice Questions ( 1 mark)

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

C++ Programming Lecture 11 Functions Part I

CA4003 Compiler Construction Assignment Language Definition

C Functions Pearson Education, Inc. All rights reserved.

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

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Programming and Data Structure

Programming in C++ 5. Integral data types

What did we talk about last time? Examples switch statements

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Slide Set 3. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

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

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

DUBLIN CITY UNIVERSITY

DUBLIN CITY UNIVERSITY

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

CSCE 110 PROGRAMMING FUNDAMENTALS

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Introduction to Programming

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

MATLAB Constants, Variables & Expression. 9/12/2015 By: Nafees Ahmed

JAVA OPERATORS GENERAL

Transcription:

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar.. C Programs: Simple Statements and Expressions C Program Structure A C program that consists of only one function has the following form: preprocessor directives main function heading { declarations statements We have already seen some preprocessor directives and have discussed some variable declarations. Statements Statements are instructions to be executed by the computer. C has a number of different types of instructions. In the course we will study most of them. Today we start with three basic types: function call, assignment and function return. Function Call Function call has the following syntax: <functionname>(<arg1>,<arg2>,...,<argn>); Here, <functionname> is the name of the function (e.g., printf), and <arg1>,... <arg2> are arguments that the function takes. C distinguishes between C standard library functions and user-defined functions. 1

2 Functions in standard C library. a wide range of tasks in C are not performed by C statements. Instead, these tasks are outsourced to a collection of functions that is available for use with any C program. This collection is called the standard C library. These functions have already been implemented by the C developers: all you need to do in order to use them is to provide a preprocessor directive #include which would specify the exact part of the standard C library which contains the function(s) you are using. The following standard C library files contain functions important for our course: File Explanation Examples stdio.h Standard Input/Output, File Input/Output printf(), scanf() math.h Mathematical functions sqrt(), sin(), cos(), log(), exp() stdlib.h Memory allocation functions, misc functions malloc(), free(), rand(), atoi() string.h String manipulation functions strcpy(), strcat(), strlen() time.h Functions related to time and system time clock(), localtime(), difftime() (note, other components of standard C library exist, but they will not be covered in the course). To specify that the included file belongs to the standard C library put the file name in angle brackets (<>) in the #include command: #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> User-defined functions. User-defined functions are reusable program components that the programmer elected to make structurally independent from the main program. Each user-defined function must have a name, a type and a list of input parameters (if any). The programmer is responsible for providing proper definition and (if necessary) declaration of the function. More on this - in two weeks! List of standard library functions. You have already seen two I/O functions: printf() and scanf(). The list below highlights some of the mathematical functions available to you in C. See Appendix B. of the textbook for full list. Function declaration Library header file Purpose Example int abs(int) stdlib.h absolute value abs(-4) = 4 double fabs(double) math.h abs() for floating point values fabs(-3.432)=3.432 double ceil(double) math.h smallest integral value ceil(7.453) = 7.0 no less than argument ceil(-4.53)= -4.0 double floor(double) math.h largest integral value floor(-4.56)=-5.0 no less than the argument floor(6.54) = 6.0 double cos(double) math.h cosine cos(0.0)=1.0 double sin(double) math.h sine sin(0.0) = 0.0 double tan(double) math.h tangent tan(0.0) = 0.0 double exp(double) math.h e x (x is argument) exp(1.0)=2.71828... double log(double) math.h natural logarithm log(exp(1.0))= 1.0 double log10(double) math.h base-10 logarithm log10(1000.0)= 3.0 double pow(double, double) math.h power pow(2.0,4.0) = 16.0 double sqrt(double) math.h square root sqrt(9.0)=3.0 int rand(void) stdlib.h pseudorandom number generator rand() void srand(unsigned int) stdlib.h reset random number generator srand(100) int main(). One user-defined C function, main() has special meaning in C. This function represents the main body of the C program. As such, when the

3 executable file of the C program is loaded into main memory to be run by the CPU, the execution of the program starts at the beginning of the main() function. In ANSI standard main() must have return type int and must have no input parameters. The type of the function must be explicitly declared in ANSI C (modern dialects of C do not require it, though). Function Return Statment Syntax. Function return statment has the following syntax: return <Expression>; Here, <Expression> is a C expression (see below). Note, ANSI C standard requires a return statement to be the last executed statement of any function (including main()). As such, it is a good practice to put a return statement at the end of each function as soon as the function is created. For example, start your main() functions with the following stub: /* Comment goes here */ int main() { return 0; Semantics. When return statement is encountered during the run of the program, the following actions are performed: 1. Expression <Expression> gets evaluated. 2. Curent function terminates its operation. 3. The computed value is returned to the caller function. 4. If current function is main(), the program terminates its work. Type match. The key rule to remember is that the value of the expression in the return statement must have the same type as the declared type of the function. For example, main() is always declared as int main(). Therefore, the following code: /* Comment goes here */ int main() { return 1.234; will result in a compiler error. Assignment Assignment statements are the building blocks of the C program. Assignment statements allow variables to receive new values as a result of various computations performed within a program.

4 Syntax. The assignment statements we will be studying for now have the following syntax: <VariableName> = <Expression>; Here, <VariableName> is a name of a program variable and <Expression> is a C expression (see below). Semantics. The assignment statement is evaluated as follows: 1. <Expression> is evaluated. 2. Computed value of <Expression> is stored in the memory cells allocated for the variable <VariableName>. Example. int x, y; float a,b; x = 0; y = x + 1; x = x + x; a = 2.0; b = a / (y + x); Constraints. The evaluation of the assignment statement is subject to the following conditions: 1. Declared variable. Varibable <VariableName> must be declared prior to its use in the assignment statement. 2. Type match. <Expression> must evaluate to a type compatible with the declared type for the variable <VariableName>. Expressions At this point we concentrate on arithmetic expressions. The three general forms of an expression are 1. <Operand> <Operation> 2. <Operation> <Operand> 3. <Operand> <Operation> <Operand> C has the following operations: Operation Arity Meaning Example + binary addition 5 + 6 evaluates to 11 - binary subtraction 6-5 evaluates to 1 * binary multiplication 4 * 3 evaluates to 12 / binary integer division 4/5 evaluates to 0 / binary division 4.0/5.0 evaluates to 0.8 % binary remainder 10 % 7 evaluates to 3 - unary unary minus - 4 evaluates to -4 + unary unary plus +4 evaluates to 4 <Operand> can be any of the following:

5 constant value (2, 5.6, etc.) defined constant (HUNDRED) variable name (currentstatevote) function call (log10(x)) (arithmetic) expression in parentheses ( (log10(x) + 5)) Evaluation, operation precedence. Arithmetic expressions in C are evaluated according to the mathematical rules. Generally speaking, given an arithmetic expression in C, its evaluation proceeds as follows: 1. Using C operator precedence and associativity rules, the operation <Op> with the least precedence (i.e., last to be evaluated) is established. 2. The expression is represented as <Operand1> <Op> <Operand2> 1 3. Operand <Operand1> is evaluated. 4. Operand <Operand2> is evaluated. 5. The result of the operation <Op> applied to the results of evaluating <Operand1> and <Operand2> is evaluated. This result is returned as the value of the expression. As seen, expression evaluation depends on operator precedence. The precedence rules are: Precedence level Operators 1. (highest) parentheses 2. +,- (unary) 3. *, /, & 4. (lowest) +, - (binary) The associativity rule is: Unary operators in the same subexpression and at the same precedence level are evaluated right-to-left (right-associativity). Binary operators in the same subexpression and at the same precedence level are evaluated left-to-right (left-associativity). Examples. Expressiona + b*c - (15 + a * n) + 23 has the following precedence of operations: ((a + (b*c)) - (15 + (a*n))) + 23. Expression a + b + -c* -+-d has the following precedence of operations: ((a+b)+ ((-c) * (-(+(- d)))). Expression b * c / e % f has the following precedence of operations: ((b*c)/e)% f. Type of expression. Type conversion. int. If both operands (sub-expressions) in an arithmetic expression evaluate to int values, then the expression evaluates to an int value. double/float. If both operands (sub-expressions) evaluate to float (or double), the the expression evaluates to a float (double) value. mix. If one sub-expression evaluates to an int and the other to a float (double), then the expression evaluates to a float (double). Note. This is how the type of the division operation is determined: if both operands are integers, integer division is applied, otherwise - floating point division. 1 In case of binary operators. For unary operators, similar intuition holds, except, only one operand gets evaluated.