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