Chapter 2 Introduction to the C Language

Similar documents
Sources: On the Web: Slides will be available on:

Informatica e Sistemi in Tempo Reale

The C Programming Language course syllabus associate level

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Pemrograman Dasar. Basic Elements Of Java

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

C++ Programming Language

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

C++ Language Tutorial

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Chapter One Introduction to Programming

The programming language C. sws1 1

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

C++ INTERVIEW QUESTIONS

1 Abstract Data Types Information Hiding

Chapter 1 Java Program Design and Development

JavaScript: Control Statements I

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

So far we have considered only numeric processing, i.e. processing of numeric data represented

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

El Dorado Union High School District Educational Services

CS 241 Data Organization Coding Standards

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Programming languages C

Fundamentals of Programming

How To Write Portable Programs In C

VB.NET Programming Fundamentals

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Tutorial on C Language Programming

Computer Programming Tutorial

Introduction to Java

5 Arrays and Pointers

I PUC - Computer Science. Practical s Syllabus. Contents

Basics of I/O Streams and File I/O

DNA Data and Program Representation. Alexandre David

Moving from CS 61A Scheme to CS 61B Java

Stacks. Linear data structures

Comp151. Definitions & Declarations

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Object Oriented Software Design

PL / SQL Basics. Chapter 3

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Number Representation

Programming Microcontrollers in C

Object Oriented Software Design

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Chapter 2 Introduction to Java programming

Chapter 13 Storage classes

Java Interview Questions and Answers

Variables, Constants, and Data Types

Introduction to Python

FEEG Applied Programming 5 - Tutorial Session

Object-Oriented Programming in Java

An Incomplete C++ Primer. University of Wyoming MA 5310

Data Storage: Each time you create a variable in memory, a certain amount of memory is allocated for that variable based on its data type (or class).

1 Description of The Simpletron

Chapter 5 Names, Bindings, Type Checking, and Scopes

Part 1 Foundations of object orientation

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

CP Lab 2: Writing programs for simple arithmetic problems

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

J a v a Quiz (Unit 3, Test 0 Practice)

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

MISRA-C:2012 Standards Model Summary for C / C++

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Sequential Program Execution

Introduction to Visual C++.NET Programming. Using.NET Environment

Objective-C Tutorial

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

C++ Input/Output: Streams

Introduction to Java. CS 3: Computer Programming in Java

sqlite driver manual

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Recognizing PL/SQL Lexical Units. Copyright 2007, Oracle. All rights reserved.

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

C++FA 5.1 PRACTICE MID-TERM EXAM

Simple C Programs. Goals for this Lecture. Help you learn about:

Chapter 2: Elements of Java

C LANGUAGE TUTORIAL. Version Sept 8, 1996

Object Oriented Software Design II

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Numbering Systems. InThisAppendix...

Lecture 22: C Programming 4 Embedded Systems

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

Java CPD (I) Frans Coenen Department of Computer Science

Transcription:

Objectives Chapter 2 Introduction to the C Language To understand the structure of a C-language program. To write your first C program. To introduce the include preprocessor command. To be able to create good identifiers for objects in a program. To be able to list, describe, and use the C basic data types. To be able to create and use variables and constants. To understand input and output concepts. To be able to use simple input and output statements. To understand the software engineering role. 1

2-1 Background C is a structured programming language. It is considered a high-level language because it allows the programmer to concentrate on the problem at hand and not worry about the machine that the program will be using. While many languages claim to be machine independent, C is one of the closest to achieving that goal. That is another reason why it is used by software developers whose applications have to run on many different hardware platforms. 2

FIGURE 2-1 Taxonomy of the C Language 3

2-2 C Programs It's time to write your first C program! This section will take you through all the basic parts of a C program so that you will be able to write it. Topics discussed in this section: Structure of a C Program Your First C Program Comments The Greeting Program 4

FIGURE 2-2 Structure of a C Program 5

Creating and Running Programs: 6

FIGURE 2-3 The Greeting Program 7

Preprocessor Directive # include: Is a preprocessor directive which directs to include the designated file which contains the declaration of library functions (pre defined). stdio.h (standard input output) : A header file which contains declaration for standard input and output functions of the program.like printf, scanf 8

When to use preprocessor directive When one or more library functions are used, the corresponding header file where the information about these functions will be present are to be included. When you want to make use of the functions(userdefined) present in a different program in your new program the source program of previous function has to be included. 9

Defining main( ) When a C program is executed, system first calls the main( ) function, thus a C program must always contain the function main( ) somewhere. A function definition has: heading { declarations ; statements; } 10

Basic Structure of a C program preprocessor directive int main( ) { declarations; ; body ; ; return 0; } 11

Concept of Comment Comments are inserted in program to maintain the clarity and for future references. They help in easy debugging. Comments are NOT compiled, they are just for the programmer to maintain the readability of the source code. Comments are included as /*.. */ 12

FIGURE 2-4 Examples of Block Comments 13

FIGURE 2-5 Examples of Line Comments 14

PROGRAM 2-1 The Greeting Program 15

Notion of keywords Keywords are certain reserved words, that have standard predefined meanings in C. All keywords are in lowercase. Some keywords in C: auto extern sizeof break static case for struct goto switch const if typedef enum signed default int union long continue unsigned do register oid double return volatile else short while float char 16

2-3 Identifiers One feature present in all computer languages is the identifier. Identifiers allow us to name data and other objects in the program. Each identified object in the computer is stored at a unique address. If we didn t have identifiers that we could use to symbolically represent data locations, we would have to know and use object s addresses. Instead, we simply give data identifiers and let the compiler keep track of where they are physically located. 17

Uppercase letters are different than lowercase, example amount, Amount and AMOUNT all three are different identifiers. Table 2-1 Rules for Identifiers 18

Note An identifier must start with a letter or underscore: it may not have a space or a hyphen. 19

Note C is a case-sensitive language. 20

Table 2-2 Examples of Valid and Invalid Names 21

2-4 Types A type defines a set of values and a set of operations that can be applied on those values. For example, a light switch can be compared to a computer type. It has a set of two values, on and off. Only two operations can be applied to a light switch: turn-on and turn-off. Topics discussed in this section: Void Type Integral Type Floating-Point Types 22

Data Types Every program specifies a set of operations to be done on some data in a particular sequence. However, the data can be of many types such as a number, real, character, string etc. C supports many data types out of which the basic types are: int, float, double and char. 23

FIGURE 2-7 Data Types 24

Format specifiers There are several format specifiers-the one you use should depend on the type of the variable you wish to print out.the common ones are as follows: Format Specifier %d int Type %c char %f float %lf double %s string To display a number in scientific notation,use %e. To display a percentage sign,use %% 25

FIGURE 2-8 Character Types 26

FIGURE 2-9 Integer Types 27

Note sizeof (short) sizeof (int) sizeof (long) sizeof (long long) 28

Table 2-3 Typical Integer Sizes and Values for Signed Integers 29

FIGURE 2-10 Floating-point Types 30

Note sizeof (float) sizeof (double) sizeof (long double) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. 31

Table 2-4 Type Summary 32

printf( ) 1. It is used to print message or result on the output screen.it is define in stdio.h header file. 2. Returns the number of characters it outputs on the screen. Example: printf( Enter the number whose multiplication table you want to generate ); printf( Balance in your account is %d, bal); /* where bal is int type*/ printf( Balance =%d,total tax is %f,bal, tax); float type */ /* where tax is 33

scanf( ) scanf( ) : It is used to input from the user numerical values, characters or strings.it is defined in stdio.h The function returns the number of data items that have been entered successfully. Example: int num1,num2,num3; char var; printf( enter the numbers ); scanf( %d%d%d, &num1,&num2,&num3); printf( enter a character ); scanf( %c, &var); 34

scanf( ) Don t try to display a decimal number using the integer format specifier, %d, as this displays unexpected values. Similarly,don t use %f for displaying integers. Mixing %d with char variables, or %c with int variables is all right 35

scanf( ) This function returns the number of data items that have been entered successfully #include<stdio.h> int main() { int n; printf("enter the value"); printf("%d", scanf("%d",&n)); return 0; } Similarly Write a program to find out what does printf( ) returns???? 36

Char Data type A variable of type char can store a single character. All character have a numeric code associated with them, so in reality while storing a character variable its numeric value gets stored. The set of numeric code is called as ASCII, American Standard Code for Information Interchange. 37

ASCII codes 38

Declaration of Variable To Declare a variable means to reserve memory space for it. In the declaration variable is provided a name which is used through out the program to refer to that character. Example: char c; OR char c, k, l; Declaring the character does not initialize the variable with the desired value. 39

Memory view char type c Each variable has an unique address of memory location associated with it i integer 40

Important about Variable Always remember in C, a variable must always be declared before it used. Declaration must specify the data type of the value of the variable. Name of the variable should match with its functionality /purpose. Example int count ; for counting the iterations. float per_centage ; for percentage of student 41

Char data type Characters (char) To store a character into a char variable, you must enclose it with SINGLE QUOTE marks i.e. by. The double quotes are reserved for string(a collection of character). The character that you assign are called as character constants. You can assign a char variable an integer.i.e. its integer value. a, z, A, Z,?, @, 0, 9 - Special Characters: preceded by \ \n, \t, \0, \, \\ etc. 42

Initialization Initializing a variable involves assigning(putting in) a value for the first time.this is done by using the ASSIGNMENT OPERATOR, denoted by the equals sign,=. Declaration and initializing can be done on separate lines, or on one line. char c= x ; or char c; c= x 43

Printing value of char variable printf( %c, a); This causes the %c to be replaced by value of character variable a. printf( \n %c, a); \n is a new line character which will print the value of variable on newline. 44

2-5 Variables Variables are named memory locations that have a type, such as integer or character, which is inherited from their type. The type determines the values that a variable may contain and the operations that may be used with its values. Topics discussed in this section: Variable Declaration Variable Initialization 45

FIGURE 2-11 Variables 46

Table 2-5 Examples of Variable Declarations and Definitions 47

FIGURE 2-12 Variable Initialization 48

Note When a variable is defined, it is not initialized. We must initialize any variable requiring prescribed data when the function starts. 49

PROGRAM 2-2 Print Sum of Three Numbers 50

PROGRAM 2-2 Print Sum of Three Numbers (continued) 51

PROGRAM 2-2 Print Sum of Three Numbers (continued) 52

2-6 Constants Constants are data values that cannot be changed during the execution of a program. Like variables, constants have a type. In this section, we discuss Boolean, character, integer, real, complex, and string constants. Topics discussed in this section: Constant Representation Coding Constants 53

Note A character constant is enclosed in single quotes. 54

Table 2-6 Symbolic Names for Control Characters 55

Table 2-7 Examples of Integer Constants 56

Table 2-8 Examples of Real Constants 57

Note The two components of a complex constant must be of the same precision, that is, if the real part is type double, then the imaginary part must also be type double. 58

Table 2-9 Examples of Complex Constants 59

FIGURE 2-13 Some Strings 60

FIGURE 2-14 Null Characters and Null Strings 61

Note Use single quotes for character constants. Use double quotes for string constants. 62

A width modifier is used to specify the minimum number of position in the output. It is very useful to align output in columns, such as when we need to print column of numbers. If we don't use a width modifier, each output value will take just enough room for data. Format of width modifier= %wd or %4d If a floating point number is being printed, then we may specify the no of decimal places to be printed with the precision modifier. Format of precision modifier =.m 63

When both width and precision are used, the width must be large enough to contain integral value,decimal point and no of digits after decimal point. For this Following format is used: %w.mf or %7.2f // float -7 print position : nnnn.dd Flag modifier(used for print modification) Justification Padding Sign flag Controls the placement it fills the unused it defines use or Of a value when it is space when the value absences of a sign shorter than Specified is smaller than the print in a numeric value. width. It can be right width. or left 64

Table 2-11 Flag Formatting Options 65

PROGRAM 2-3 Memory Constants 66

PROGRAM 2-3 Memory Constants (continued) 67

2-8 Programming Examples In this section, we show some programming example to emphasize the ideas and concepts we have discussed about input/output. Computer Science: A Structured Programming Approach Using C 68

PROGRAM 2-4 A Program That Prints Nothing! Computer Science: A Structured Programming Approach Using C 69

PROGRAM 2-5 Demonstrate Printing Boolean Constants Computer Science: A Structured Programming Approach Using C 70

PROGRAM 2-5 Demonstrate Printing Boolean Constants (continued) Computer Science: A Structured Programming Approach Using C 71

PROGRAM 2-6 Print Value of Selected Characters Computer Science: A Structured Programming Approach Using C 72

PROGRAM 2-6 Print Value of Selected Characters (continued) Computer Science: A Structured Programming Approach Using C 73

PROGRAM 2-6 Print Value of Selected Characters (continued) Computer Science: A Structured Programming Approach Using C 74

PROGRAM 2-6 Print Value of Selected Characters (continued) Computer Science: A Structured Programming Approach Using C 75

PROGRAM 2-7 Calculate a Circle s Area and Circumference Computer Science: A Structured Programming Approach Using C 76

PROGRAM 2-7 Calculate a Circle s Area and Circumference (continued) Computer Science: A Structured Programming Approach Using C 77

FIGURE 2-22 Output Specifications for Inventory Report Computer Science: A Structured Programming Approach Using C 78

PROGRAM 2-8 A Sample Inventory Report Computer Science: A Structured Programming Approach Using C 79

PROGRAM 2-8 A Sample Inventory Report (continued) Computer Science: A Structured Programming Approach Using C 80

FIGURE 2-23 Complex Number Attributes Computer Science: A Structured Programming Approach Using C 81

PROGRAM 2-9 Print Complex Number Attributes Computer Science: A Structured Programming Approach Using C 82

PROGRAM 2-9 Print Complex Number Attributes (continued) Computer Science: A Structured Programming Approach Using C 83

PROGRAM 2-10 Complex Number Arithmetic Computer Science: A Structured Programming Approach Using C 84

PROGRAM 2-10 Complex Number Arithmetic (continued) Computer Science: A Structured Programming Approach Using C 85

PROGRAM 2-10 Complex Number Arithmetic (continued) Computer Science: A Structured Programming Approach Using C 86