Chapter 1 & 2 Introduction to C Language

Similar documents
C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

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

Chapter 1 Introduction to Computers and C++ Programming

SEQUENTIAL STRUCTURE. Erkut ERDEM Hacettepe University October 2010

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

Fundamentals of Programming Session 4

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

Introduction to Programming

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Programming for Engineers Introduction to C

Data types, variables, constants

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

Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Fundamental of Programming (C)

Introduction to C# Applications

IS 0020 Program Design and Software Tools

Chapter 2, Part I Introduction to C Programming

6.096 Introduction to C++ January (IAP) 2009

ANSI C Programming Simple Programs

1 EEE1008 C Programming

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

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

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

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Programming and Data Structures

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

Fundamentals of Programming

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

C Language, Token, Keywords, Constant, variable

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Basic Elements of C. Staff Incharge: S.Sasirekha

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

A Fast Review of C Essentials Part I

Chapter 2: Overview of C. Problem Solving & Program Design in C

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Lecture 3 Tao Wang 1

Instructor. Mehmet Zeki COSKUN Assistant Professor at the Geodesy & Photogrammetry, Civil Eng. (212)

Preview from Notesale.co.uk Page 6 of 52

Introduction to the C Programming Language

Introduction to Programming

Intro to Computer Programming (ICP) Rab Nawaz Jadoon

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Presented By : Gaurav Juneja

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

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

Programming. C++ Basics

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

ET156 Introduction to C Programming

Introduction to Computing Lecture 01: Introduction to C

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 3. Aykut Erdem, Erkut Erdem, Fuat Akal

Introduction to C Programming

Data Types and Variables in C language

DEPARTMENT OF MATHS, MJ COLLEGE

Course Outline. Introduction to java

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

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

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

IT 374 C# and Applications/ IT695 C# Data Structures

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

0 Introduction: Computer systems and program development

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Work relative to other classes

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Programming in C++ 4. The lexical basis of C++

BLM2031 Structured Programming. Zeyneb KURT

Creating a C++ Program

Basics of Programming

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lecture 02 C FUNDAMENTALS

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

Computer System and programming in C

Computer programming & Data Structures Unit I Introduction to Computers

INTRODUCTION 1 AND REVIEW

Syntax and Variables

BITG 1233: Introduction to C++

CS102: Variables and Expressions

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

Computers Programming Course 5. Iulian Năstac

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Fundamental of C programming. - Ompal Singh

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Programming in C and C++

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

CS 241 Computer Programming. Introduction. Teacher Assistant. Hadeel Al-Ateeq

C - Basic Introduction

Chapter 3 Structured Program Development

Fundamentals of C. Structure of a C Program

C Programming a Q & A Approach

Chapter 2, Part III Arithmetic Operators and Decision Making

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Programming with C++ Language

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

ET156 Introduction to C Programming

Transcription:

1 Chapter 1 & 2 Introduction to C Language Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 1 & 2 - Introduction to C Language 2 Outline 1.1 The History of C 1.2 The C Standard Library 1.3 C++ 1.4 The Basics of a typical C Program Development Environment 2.1 A Simple C Program: Printing a Line of Text 2.2 Another Simple C Program: Adding Two Integers 2.3 Memory Concepts 2.4 Arithmetic in C 2.5 Decision Making: Equality and Relational Operators

Objectives 3 In chapter 1&2, you will learn: The history of the C programming language. To become aware of the C standard library. The elements of a typical C program development environment. To be able to write simple programs in C. To be able to use simple input and output statements. To become familiar with fundamental data types. To understand computer memory concepts. To be able to use arithmetic operators. To understand the precedence of arithmetic operators. To be able to write simple decision making statements.

4 C Language 1.1 History of C Evolved by Dennis Ritchie from two previous programming languages, BCPL and B Used to develop UNIX Used to write modern operating systems Hardware independent (portable) Standardization Many slight variations of C existed, and were incompatible Committee formed to create a "unambiguous, machineindependent" definition Standard created in 1989 (ANSI), updated in 1999 (ISO)

5 1.2 The C Standard Library C programs consist of pieces/modules called functions A programmer can create his own functions Advantage: the programmer knows exactly how it works Disadvantage: time consuming Programmers will often use the C library functions Use these as building blocks Avoid re-inventing the wheel If a premade function exists, generally best to use it rather than write your own Library functions carefully written, efficient, and portable

6 C++ Language 1.3 C++ Superset of C developed by Bjarne Stroustrup at Bell Labs Extends the C, and provides object-oriented capabilities Object-oriented design is very powerful Dominant language in industry and academia Learning C++ Because C++ includes C, it is best to master C, then learn C++

1.4 Basics of a Typical C Program Development Environment Phases of C Programs: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute Editor Preprocessor Compiler Linker Loader Disk CPU Disk Disk Disk Disk Primary Memory... Primary Memory... 7 Program is created in the editor and stored on disk. Preprocessor program processes the code. Compiler creates object code and stores it on disk. Linker links the object code with the libraries Loader puts program in memory. CPU takes each instruction and executes it, possibly storing new data values as the program executes.

Comments 2.1 A Simple C Program: Printing a Line of Text 1 /* Fig. 2.1: fig02_01.c 2 A first program in C */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 printf( "Welcome to C!\n" ); 9 10 return 0; /* indicate that program ended successfully */ 11 12 } /* end function main */ Welcome to C! Text surrounded by /* and */ is ignored by computer Used to describe program #include <stdio.h> Preprocessor directive Tells computer to load contents of a certain file <stdio.h> allows standard input/output operations 8

2.1 A Simple C Program: Printing a Line of Text int main() C++ programs contain one or more functions, exactly one of which must be main Parenthesis used to indicate a function int means that main "returns" an integer value Braces ({ and }) indicate a block The bodies of all functions must be contained in braces 9

2.1 A Simple C Program: Printing a Line of Text printf( "Welcome to C!\n" ); Instructs computer to perform an action Specifically, prints the string of characters within quotes (" ") Entire line called a statement All statements must end with a semicolon (;) Escape character (\) Indicates that printf should do something out of the ordinary \nis the newline character 10

2.1 A Simple C Program: Printing a Line of Text 11 Escape Sequence Description \n Newline. Position the cursor at the beginning of the next line. \t Horizontal tab. Move the cursor to the next tab stop. \a Alert. Sound the system bell. \\ Backslash. Insert a backslash character in a string. \" Double quote. Insert a double quote character in a string. Fig. 2.2 Some common escape sequences.

2.1 A Simple C Program: Printing a Line of Text return 0; A way to exit a function return 0, in this case, means that the program terminated normally Right brace } Indicates end of main has been reached Linker When a function is called, linker locates it in the library Inserts it into object program If function name is misspelled, the linker will produce an error because it will not be able to find function in the library 12

1 /* Fig. 2.3: fig02_03.c 2 Printing on one line with two printf statements */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 printf( "Welcome " ); 9 printf( "to C!\n" ); 10 11 return 0; /* indicate that program ended successfully */ 12 13 } /* end function main */ Welcome to C! Outline fig02_03.c Program Output 13

1 /* Fig. 2.4: fig02_04.c 2 Printing multiple lines with a single printf */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 printf( "Welcome\nto to\nc! C!\n" ); 9 10 return 0; /* indicate that program ended successfully */ 11 12 } /* end function main */ Welcome to C! Outline fig02_04.c Program Output 14

1 /* Fig. 2.5: fig02_05.c 2 Addition program */ 3 #include <stdio.h> 4 5 /* function main begins program execution */ 6 int main() 7 { 8 int integer1; /* first number to be input by user */ 9 int integer2; /* second number to be input by user */ 10 int sum; /* variable in which sum will be stored */ 11 12 printf( "Enter first integer\n" n" ); /* prompt */ 13 scanf( "%d", &integer1 ); /* read an integer */ 14 15 printf( "Enter second integer\n" n" ); /* prompt */ 16 scanf( "%d", &integer2 ); /* read an integer */ 17 18 sum = integer1 + integer2; /* assign total to sum */ 19 20 printf( "Sum is %d\n" n", sum ); /* print sum s */ 21 22 return 0; /* indicate that program ended successfully */ 23 24 } /* end function main */ Outline fig02_05.c 15

Enter first integer 45 Enter second integer 72 Sum is 117 Outline Program Output 16

2.2 Another Simple C Program: Adding Two Integers As before Comments, #include <stdio.h> and main 17 int integer1, integer2, sum; Definition of variables Variables: locations in memory where a value can be stored int means the variables can hold integers (-1, 3, 0, 47) Variable names (identifiers) integer1, integer2, sum Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ ) Case sensitive Definitions appear before executable statements If an executable statement references and undeclared variable it will produce a syntax (compiler) error

18 Variable Naming Examples Invalid Variable Names: ÖğrenciNum, Öğr Num, Ogr-Num, 4.Ogr, α, θ, a 2, π Valid Variable Names: OgrenciNum, OgrNum, Ogr_Num, Ogr4 Sum, alfa, teta, asquare, Pi

2.2 Another Simple C Program: Adding Two Integers scanf( "%d", &integer1 ); Obtains a value from the user scanf uses standard input (usually keyboard) This scanf statement has two arguments %d-indicates data should be a decimal integer &integer1 - location in memory to store variable &is confusing in beginning for now, just remember to include it with the variable name in scanf statements 19 When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

2.2 Another Simple C Program: Adding Two Integers = (assignment operator) Assigns a value to a variable Is a binary operator (has two operands) sum = variable1 + variable2; 20 sum gets variable1 + variable2 Variable receiving value must be on left (target) Common mistake: The following gives a compiler error, becuase the left of the assignment operator (=) must always be the target variable. variable1 + variable2 = sum;

2.2 Another Simple C Program: Adding Two Integers 21 printf( "Sum is %d\n", sum ); Similar to scanf %dmeans decimal integer will be printed sumspecifies what integer will be printed Calculations can be performed inside printf statements printf( "Sum is %d\n", integer1 + integer2 );

22 Variables 2.3 Memory Concepts Variable names correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous value Reading variables from memory does not change them A visual representation integer1 45

23 2.3 Memory Concepts A visual representation (continued) integer1 45 integer2 72 sum 117

Storing Data in Variables 24 You can think of a variable as if it were a box inside your computer holding a data value. The value might be a number, character, or string of characters. Data is stored inside memory locations (RAM) which are defined as variables. Instead of remembering a specific storage location (called an address), you only have to remember the name of the variables you define. The variable is like a box that holds data, and the variable name is a label for that box. Examples: OgrNum 40020859 OgrAdSoyad Mehmet Demir

Swapping Variables (1) 25 Swapping values simply means replacing one variable s contents with another s and vice versa.

26 Swapping Variables (2) Suppose we assigned two variables named variable1 and variable2 with the following statements: int variable1 = 65 ; int variable2 = 97 ; Now we want to swap (i.e. exchange) their content values: CORRECT METHOD WRONG METHOD int temp; variable1 = variable2; temp = variable1; variable2 = variable1; variable1 = variable2; variable2 = temp;

Swapping Variables (3) 27 variable1 variable2 temp Initial state 65 97 First step 65 97 65 Second step 97 97 65 Third step 97 65 65

28 Example: Swapping Correctly #include <stdio.h> #include <stdlib.h> int main() { int variable1 = 65 ; int variable2 = 97 ; PROGRAM OUTPUT SWAP'TEN ONCE DEGISKENLER : 65 97 SWAP'TEN SONRA DEGISKENLER : 97 65 int temp; printf("swap'ten ONCE DEGISKENLER : %d %d \n\n", variable1, variable2); temp = variable1; variable1 = variable2; variable2 = temp; printf("swap'ten SONRA DEGISKENLER : %d %d \n\n", variable1, variable2); system("pause"); return 0; }

29 Arithmetic calculations 2.4 Arithmetic Use * for multiplication and / for division Integer division truncates remainder 7/5evaluates to 1 Modulus operator(%) returns the remainder 7%5evaluates to 2 Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: (a + b + c ) / 3.0

30 2.4 Arithmetic Arithmetic operators: C operation Arithmetic operator Algebraic expression C expression Addition + f + 7 f + 7 Subtraction - p c p - c Multiplication * b.r b * r Division / x / y x / y Modulus % r mod p r % p Rules of operator precedence: Operator(s) Operation(s) Order of evaluation (precedence) () Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. *, /, or % Multiplication,Division, Modulus + or - Addition Subtraction Evaluated second. If there are several, they are evaluated left to right. Evaluated last. If there are several, they are evaluated left to right.

31 2.4 Arithmetic Step 1. y = 2 * 5 * 5 + 3 * 5 + 7; 2 * 5 is 10 (Leftmost multiplication) Step 2. y = 10 * 5 + 3 * 5 + 7; 10 * 5 is 50 (Leftmost multiplication) Step 3. y = 50 + 3 * 5 + 7; 3 * 5 is 15 (Multiplication before addition) Step 4. y = 50 + 15 + 7; 50 + 15 is 65 (Leftmost addition) Step 5. y = 65 + 7; 65 + 7 is 72 (Last addition) Step 6. y = 72; (Last operation place 72 in y )

Example: Integer Division 32 #include <stdio.h> #include <stdlib.h> int main() { // This will display 12, not 15!! printf("%d\n\n", (15 / 4) * 4); } system("pause"); return 0; 3

Example: Divisions 33 #include <stdio.h> #include <stdlib.h> int main() { int X = 15; } printf("%d \n\n", X/2); // 7 printf("%f \n\n", X/2); // 0.000000 printf("%f \n\n", X/2.0); // 7.500000 printf("%f \n\n", (float) X / 2); // 7.500000 (float) means typecasting printf("%.3f \n\n", (float) X / 2); // 7.500 printf("%.1f \n\n", (float) X / 2); // 7.5 //printf("%d \n\n", 60 / 0); // Compiler error printf("%d \n\n", 60 / (X-15)); // Run-time error: Program will crash system("pause"); return 0;

2.5 Decision Making: Equality and Relational Operators Executable statements Perform actions (calculations, input/output of data) Perform decisions May want to print "pass" or "fail" given the value of a test grade ifcontrol statement Simple version in this section, more detail later If a condition is true, then the body of the if statement executed 0is false, non-zero is true Control always resumes after the if structure Keywords Special words reserved for C Cannot be used as identifiers or variable names 34

2.5 Decision Making: Equality and Relational Operators 35 Standard algebraic equality operator or relational operator Equality Operators C equality or relational operator Example of C condition = == x == y!= x!= y Meaning of C condition x is equal to y x is not equal to y Relational Operators > > x > y < < x < y >= >= x >= y <= <= x <= y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

1 /* Fig. 2.13: fig02_13.c 2 Using if statements, relational 3 operators, and equality operators */ 4 #include <stdio.h> 5 6 /* function main begins program execution */ 7 int main() 8 { 9 int num1, /* first number to be read from user */ 10 int num2; /* second number to be read from user */ 11 12 printf( "Enter two integers, and I will tell you\n" ); 13 printf( "the relationships they satisfy: " ); 14 15 scanf( "%d%d", &num1, &num2 ); /* read two integers */ 16 17 if ( num1 == num2 ) { 18 printf( "%d is equal to %d\n" n", num1, num2 ); 19 } /* end if */ 20 21 if ( num1!= num2 ) { 22 printf( "%d is not equal to %d\n" n", num1, num2 ); 23 } /* end if */ 24 Outline fig02_13.c (Part 1 of 2) 36

25 if ( num1 < num2 ) { 26 printf( "%d is less than %d\n" n", num1, num2 ); 27 } /* end if */ 28 29 if ( num1 > num2 ) { 30 printf( "%d is greater than %d\n" n", num1, num2 ); 31 } /* end if */ 32 33 if ( num1 <= num2 ) { 34 printf( "%d is less than or equal to %d\n" n", num1, num2 ); 35 } /* end if */ 36 37 if ( num1 >= num2 ) { 38 printf( "%d is greater than or equal to %d\n" n", num1, num2 ); 39 } /* end if */ 40 41 return 0; /* indicate that program ended successfully */ 42 43 } /* end function main */ Outline fig02_13.c (Part 2 of 2) 37 Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Program Output

Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 Outline Program Output (continued) 38 Enter two integers, and I will tell you the relationships they satisfy: 7 7 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7

2.5 Decision Making: Equality and Relational Operators 39 Operators Associativity * / % left to right + - left to right < <= > >= left to right ==!= left to right = right to left Fig. 2.14 Precedence and associativity of the operators discussed so far.

40 2.5 Decision Making: Equality and Relational Operators Keywords auto auto auto auto double double double double int int int int struct struct struct struct break break break break else else else else long long long long switch switch switch switch case case case case enum enum enum enum register register register register typedef typedef typedef typedef char char char char extern extern extern extern return return return return union union union union const const const const float float float float short short short short unsigned unsigned unsigned unsigned continue continue continue continue for for for for signed signed signed signed void void void void default default default default goto goto goto goto sizeof sizeof sizeof sizeof volatile volatile volatile volatile do do do do if if if if static static static static while while while while Fig. 2.15 C s reserved keywords.

41 Basic Data Types of Variables char int float double Modifiers for Sign and Size unsigned signed (by default) short long (by default)

42 Data Type Ranges (1) Keyword Size in Bytes Variable Type Range char 1 Character -128 to 127 (or string) int 4 Integer -2,147,483,648 to 2,147,483,647 long 4 Long integer -2,147,483,648 to 2,147,483,647 long int 4 Long integer -2,147,483,648 to 2,147,483,647 short 2 Short integer 32,768 to 32,767 short int 2 Short integer 32,768 to 32,767

43 Data Type Ranges (2) Keyword Size in Bytes Variable Type Range unsigned char 1 Unsigned character 0 to 255 unsigned int 4 Unsigned integer 0 to 4,294,967,295 unsigned long 4 Unsigned long integer 0 to 4,294,967,295 unsigned short 2 Unsigned short integer 0 to 65,535

44 Data Type Ranges (3) Keyword Size in Bytes Variable Type Range float 4 Single-precision -3.4 * 10 38 to floating-point 3.4 * 10 38 (7 digits) double 8 Double-precision -1.7 * 10 308 to floating-point 1.7 * 10 308 (15 digits) double x = 4.3E6; 4.3 * 10 6 long long y = 4.3E6; unsigned short int z = 70000; compiler warning due to overflow

45 Example: Range Overflow #include <stdio.h> #include <stdlib.h> void main() { unsigned short int X, Y; // Length of these are 2 bytes (16-bit) each X = 65535; // Maximum possible value for unsigned short integer numbers Y = X + 4; // Overflow is expected here (Y will be 3, instead of 65539) printf("sonuc = %d \n\n", Y); // It will display 3!! system("pause"); }