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

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

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

UNIT- 3 Introduction to C++

Full file at

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

Typescript on LLVM Language Reference Manual

Work relative to other classes

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

Lecture 3. More About C

The SPL Programming Language Reference Manual

Computer System and programming in C

BASIC ELEMENTS OF A COMPUTER PROGRAM

Basics of Programming

CHAPTER 3 Expressions, Functions, Output

Computers Programming Course 5. Iulian Năstac

Fundamental of Programming (C)

Visual C# Instructor s Manual Table of Contents

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Introduction to C Language

Review of the C Programming Language for Principles of Operating Systems

1 Lexical Considerations

3. Java - Language Constructs I

The PCAT Programming Language Reference Manual

Chapter 2: Using Data

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

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

Fundamentals of Programming

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

Objectives. In this chapter, you will:

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

Course Outline Introduction to C-Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

A Java program contains at least one class definition.

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

Language Reference Manual simplicity

Programming for Engineers Iteration

Programming in C++ 5. Integral data types

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

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

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

CS201 Some Important Definitions

Programming in C++ 6. Floating point data types

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

C Introduction. Comparison w/ Java, Memory Model, and Pointers

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

C: How to Program. Week /Mar/05

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

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

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

Review of the C Programming Language

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

Data Types and Variables in C language

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Computers Programming Course 6. Iulian Năstac

Chapter 2 - Introduction to C Programming

Programming for Engineers Introduction to C

Variables and literals

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

ANSI C Programming Simple Programs

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

CSC 1107: Structured Programming

Lexical Considerations

ET156 Introduction to C Programming

Lexical Considerations

ARG! Language Reference Manual

Chapter 3 Structure of a C Program

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

Reserved Words and Identifiers

Introduction to C. Systems Programming Concepts


DEPARTMENT OF MATHS, MJ COLLEGE

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Operators and Control Flow. CS449 Fall 2017

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

Decaf Language Reference Manual

C-LANGUAGE CURRICULAM

CSCI 171 Chapter Outlines

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

Operators in C. Staff Incharge: S.Sasirekha

Programming. Elementary Concepts

Chapter 3: Operators, Expressions and Type Conversion

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

Operators & Expressions

Program Fundamentals

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Chapter 2 Basic Elements of C++

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

CSI33 Data Structures

Declaration and Memory

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Transcription:

C Language Part 1 (Minor modifications by the instructor)

References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian, and Dennis Ritchie, Prentice Hall, 1988 2

Compilers vs Interpreters Compiler Generates a file containing the translation of the program into the machines native code. Does not actually execute the program Interpreter Reads and performs (executes) the program file directly read translate execute cycle me@computer:~$ gcc my_program.c me@computer:~$./a.out GCD: 8 3

C Functions All C code must be nested within functions C program: a list of function definitions Functions cannot be nested within each other Function definition: type of its return value, its name, a list of arguments, block of code main function A special C function where the program execution begins 4

C Statements A C statement ends with ; or a block statement 1. int x; // declarations 2. x = y + z ; // expressions as statements 3. printf( hello, world ); // expression 4. return 0; 5. if (x<0) { printf( negative! ); } 6. while (i >= 0) { i--; printf(i); } 7. for (i=0; i<10; i++) { printf(i);} 5

Block Statement Also known as a compound statement It is a statement, but does not need to end with ; A group of any number of declarations and statements Surrounded by a pair of curly braces Treated as a single statement Can be nested A variable declared within a block has block scope An identifier is active and accessible from its declaration point to the end of the block If an identifier is redeclared in an inner block, the original declaration is hidden by the redeclaration in the inner block from the redeclaration point to the end of the inner block 6

7

Whitespaces Space, newline, tab Only have meaning in separating words and operators 1 whitespace = 100 whitespaces = 1000 disc = b * b - 4 * a * c; if (disc < 0) { num_sol = 0; } else { t0 = -b / a; if (disc == 0) { num_sol = 1; sol0 = t0 / 2; } else { num_sol = 2; t1 = sqrt(disc) / a; sol0 = (t0 + t1) / 2; sol1 = (t0 - t1) / 2; } } disc=b*b-4*a*c;if(disc<0){ num_sol=0;}else{t0=-b/a;if( disc==0){num_sol=1;sol0=t0/2 ;}else{num_sol=2;t1=sqrt(disc/a; sol0=(t0+t1)/2;sol1=(t0-t1)/2;}} 8

C Declarations Names (identifiers) in C Case sensitive Contain digits and underscores (_), but may not begin with a digit In C, all identifiers must be declared before they are used Type information for storage allocation by the compiler Help the compiler to choose correct operations 9

Declarations (contd.) To declare a variable, specify the type of the variable, and then its name The variable can have an initial value Multiple variables can be declared after the type by separating them with commas 10

Data Type The name that specifies the kind of data values Determines The possible values in the category The operations that can be performed on the values The way the values can be stored Used by the compiler 11

Fundamental Types in C There are several basic data types in C: char: a single byte holding one character int: an integer typically having the integer size of the host machine float: single-precision floating point double: double-precision floating point 12

C Variables A named storage location that contains some value The name is bound to the location 13

C Assignment Operation Denoted by = Assigns the value of the right-hand side operand to the storage location bound to the left-hand side operand For example, x = y stores the value stored in the storage location bound to y to the storage location bound to x 14

C Pointers A reference to a variable The location (address) of the variable in the memory A pointer is a variable that stores a reference to another variable It is said to point to the variable Used in programs to access memory and manipulate addresses The basic syntax to declare a pointer is a type name followed by * and an identifier int *x; x is a pointer to an integer x contains the address of an integer variable or value A null pointer has a special value (NULL) reserved for indicating that it does not refer to any valid object int *x = NULL; 15

Reference Operator address of operator The reference (address) of a variable is obtained by preceding the variable with & 16

Dereference Operator value pointed by operator Pointer dereferencing Obtaining the value stored in the location which the pointer points to Preceding the pointer with * If a NULL pointer is dereferenced then a run-time error will occur and execution will stop likely with a segmentation fault 17

Void Type The type for the result of a function that does not return anything The type of a pointer which does not point to any particular type For example, void *x; The pointer contains an address and the compiler has no idea what type of object the pointer points to To indicate that a function does not take any parameters int foo(void) int foo() // equivalent to the above 18

Local Variables Local variables A variable declared inside a function Function parameters A variable declared inside a block Not visible to other functions Each local variable in a function or a block comes into existence when the function is called or the block is entered, and it disappears when the function or the block is exited The memory space for a local variable is allocated in the associated function s stack frame Called automatic variables Exists solely for the duration of the stack frame 19

Non-local Variables in C Exist for all time from the beginning of program execution to the end of the execution Accessible to all functions 20

21

C Constants An integer constant is a decimal integer like 75 and -492 A floating point constant contains a decimal point like 3.14 or an exponent like 4e-1 (which means 0.4) A character constant is one character within single quotes like a 22

C Constants (contd.) A qualifier const can be applied to any variable declaration to specify that its value will not be changed any more const float pi = 3.14; pi cannot be assigned to a new value 23

C Arithmetic Operators + Addition - Subtraction * Multiplication / Division If both of its operands are integers, / gives the quotient The value of 9/4 is 2 % Remainder It requires integer operands and gives the remainder The value of 9%4 is 1 24

True and False in C 0 (zero) evaluates to false and any other number to true 25

C Relational Operators < less than > greater than <= less than or equal to >= greater than or equal to == equal to!= not equal to Returns either 0 (false) or 1 (true) The value of 7 < 9 is 1 The value of 7 > 9 is 0 26

C Logical Operators! Logical NOT && Logical AND Logical OR Returns either 0 or 1 27

Operator Precedence The unary! operator has the same precedence as the unary + and operators, and they have higher precedence than any binary operators Expressions connected by && or are evaluated left to right, and evaluation stops as soon as the result is determined i > 0 && n / i == 10 means (i > 0) && ((n / i) == 10) Short circuit evaluation In (i > 0 && n / i == 10), if i>0 is false, the rest needs not to be evaluated Highest * / % + - < > <= >= ==!= && Lowest 28

Type Conversion in C Type conversions can occur across an assignment or when the operands of a binary operator are evaluated To choose a proper machine instruction to perform the operation An expression (such as x + y) has both a value and a type To perform a binary operation, its operands must be of the same type When two operands are of different types, generally the more restricted operand is converted to the more general one 29

Type Conversion (contd.) Examples int i; float f; In i + f, the operand i gets promoted to a float and the expression i + f as a whole has type float double d; int i; In d = i, i is converted to double and assigned to d Other names: automatic conversion, implicit conversion, coercion, promotion, widening 30

Type Conversion (contd.) char c; short s; int i; long l; unsigned u; unsigned long ul; float f; double d; long double ld; c s/i (int) u*3.0-i (double) c+4 (int) c+3.0 (double) d+s (double) 7*i/l (long) u*4-i (unsigned) f*8-i (float) 8*s*ul (unsigned long) ld + c (long double) u-ul (unsigned long) 31

Type Casts Explicit type conversion by the programmer Examples (double) i (long) ( A + 1.0) (double) (x = 22) (float) i + 3 ((float) i) + 3 d = (double) i / 5 32

Increment and Decrement Operators C has special operators for increment (add by 1) and decrement (subtract by 1), ++ and -- They can be used as prefix operators like ++i or postfix operators like i++ ++i increment i before its value is used, while i++ increments after its value is used Assume i has the value 7 n = ++i; sets n to 8 n = i++; sets n to 7 In both cases, i becomes 8 ++ and -- have higher precedence than any binary operators 33

printf Function prototypes A way of declaring functions int foo(int a); float bar(void); Printf s prototype is included in stdio.h Printf is passed a list of arguments: a format string and other arguments The format string contains both ordinary characters and conversion specifications (format specifiers) 34

printf (contd.) printf( abcde ); printf( %s, abcde ); printf( %c%c%c%c%c, a, b, c, d, e ); printf( %c%4c%4c, a, b, c ); c d e f g s Character Decimal integer Floating-point number in scientific notation Floating-point number In the e-format or f-format, whichever is shorter string 35

printf (contd.) 36

scanf Analogous to printf, but used for input scanf is passed a list of arguments: a format string and other arguments Other arguments Addresses scanf( %d, &x); The format specifier %d is matched with &x Treat characters in the input stream as a decimal integer and store it at the address of x 37

scanf (contd.) When reading numbers, white spaces (blanks, newlines, and tabs) are skipped, but when reading in a character, they are not c d f Character Decimal integer Floating-point number (float) LF or lf Floating-point number (double) s string 38

scanf (contd.) 39

Call by Value Arguments to functions are always passed by value When a function is called, the value of each real argument is assigned to the corresponding formal parameter, and any changes in a formal parameter does not affect the value of the associated real argument The expression passed as an argument to a function is first evaluated, and its value is passed to the function a b c 4 3 5 + 7 5 x y foo(a + b, c); int foo(int x, int y) 40

Call by Value (contd.) 41

Swap 42

Swap (contd.) 43