Sie sind auf Seite 1von 20

Unix, C & C++ UNIT II Snapshot

Introduction to Programming C Character Set Instructions Operators Data types Console based I/O Functions Preprocessor Directives Control Statements

2.0

Introduction

There are many programming languages used currently. One of the most popular programming language is C. C is a structured programming language. Dennis M Ritchie first developed the C language in 1972 at AT&T Bell labs primarily as a system programming language.

2.1

Objective

The objective of this lesson provides a detailed description about C programming language and its concepts in detail. The content of this lesson starts with introduction to programming language and ends with control structures.

2.2
2.2.1

Content

Introduction to Programming As a programming language, C is rather like Pascal or FORTRAN. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures. Of the three languages, C allows the most precise control of input and output. C is also rather terser than FORTRAN or Pascal. This can result in short efficient programs, where the programmer has made wise use of C's range of powerful operators. It also allows the programmer to produce programs which are impossible to understand. Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. The following example will illustrate a simple C program. This program which will print out the message This is a C program #include <stdio.h> main() { Page 16

Unix, C & C++


printf("This is a C program\n"); } Though the program is very simple, a few points are worthy of note. Every C program contains a function called main. This is the start point of the program. #include <stdio.h> allows the program to interact with the screen, keyboard and file system of your computer. You will find it at the beginning of almost every C program. Main () declares the start of the function, while the two curly brackets show the start and finish of the function. Curly brackets in C are used to group statements together as in a function, or in the body of a loop. Such a grouping is known as a compound statement or a block. Printf ("This is a C program\n"); prints the words on the screen. The text to be printed is enclosed in double quotes. The \n at the end of the text tells the program to print a new line as part of the output. Most C programs are in lower case letters. You will usually find upper case letters used in preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings. C is case sensitive, that is, it recognizes a lower case letter and its upper case equivalent as being different. Variables In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function. A declaration begins with the type, followed by the name of one or more variables. For example, int high, low, results[20]; Declarations can be spread out, allowing space for an explanatory comment. Variables can also be initialized when they are declared; this is done by adding an equals sign and the required value after the declaration. Every variable has a name and a value. The name identifies the variable, the value stores data. There is a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. C recognizes upper and lower case characters as being different. Finally, you cannot use any of C's keywords like main, while, switch etc as variable names. Local variables are declared within the body of a function, and can only be used within that function. This is usually no problem, since when another function is called, all required data is passed to it as arguments. Alternatively, a variable can be declared globally so it is available to all functions. Modern programming practice recommends against the excessive use of global variables. They can lead to poor program structure, and tend to clog up the available name space. A global variable declaration looks normal, but is located outside any of the program's functions. This is usually done at the beginning of the program file, but after preprocessor directives. The variable is not declared again in the body of the functions which access it.

Page 17

Unix, C & C++


Where a global variable is declared in one file, but used by functions from another, then the variable is called an external variable in these functions, and must be declared as such. The declaration must be preceded by the word extern. The declaration is required so the compiler can find the type of the variable without having to search through several source files for the declaration. Global and external variables can be of any legal type. They can be initialized, but the initialization takes place when the program starts up, before entry to the main function. Another class of local variable is the static type. A static can only be accessed from the function in which it was declared, like a local variable. The static variable is not destroyed on exit from the function; instead its value is preserved, and becomes available again when the function is next called. Static variables are declared as local variables, but the declaration is preceded by the word static. static int counter; Static variables can be initialized as normal; the initialization is performed once only, when the program starts up. 2.2.2 C Character Set Instructions The C Character set consists of upper and lower case alphabets, digits, special characters and white space. The alphabets and digits are together called the alphanumeric characters. 1. Alphabets: A B C D E F G H .. X Y Z A b c d e f g h x y z 2. Digits: 0123456789 3. Special Characters: , comma . period ; semicolon : colon # number sign quotation mark | Vertical bar ~ tilde \ backslash < opening angle bracket _ under score $ dollar sign ? question mark & ampersand * asterisk - minus sign + plus sign > closing angle bracket ( left parenthesis ) right parenthesis [ left bracket ] right bracket { left brace } right brace / slash

Page 18

Unix, C & C++


4. White space characters: blank space Horizontal tab 2.2.3 newline vertical tab carriage return formfeed

Operators One reason for the power of C is its wide range of useful operators. An operator is a function which is applied to values to give a result. You should be familiar with operators such as +, -, /. Arithmetic operators are the most common. Other operators are used for comparison of values, combination of logical states, and manipulation of individual binary digits. In C operators can be classified into various categories based on their utility and action. A list of operator types is given below: Arithmetic operators + * / % Addition Subtraction Multiplication Division modulo division

Relational operators < > <= >= == != less than greater than less than or equal to greater than or equal to equal to not equal to

Logical operators && || ! & ! logical AND logical OR logical NOT bitwise AND bitwise OR Page 19

Bitwise operators

Unix, C & C++


^ << >> ~ bitwise XOR shift left shift right bitwise complement <variable name>++ <variable name>--

Increment and decrement operators ++<variable name> --<variable name> Other operators Sizeof 2.2.4 Data types The C language supports the following basic data types char int float double a single byte that can hold one character an integer a single precision floating point number a double precision floating point number

The precision refers to the number of significant digits after the decimal point. In addition, applying qualifiers to the above data types yield additional data types. A qualifier alters the characteristics of the data type, such as sign or size. The qualifiers that alter the size are short and long. These qualifiers are applicable to integers, and yield two more data types short int long int integer represented by a lesser number of bits (16) integer represented by a greater number of bits (32)

The sign qualifiers are signed and unsigned. signed short int unsigned short int signed int unsigned int signed long int unsigned long int 2.2.5 Console based I/O Character Input / Output is the lowest level of input and output. It provides very precise control, but is usually too fiddly to be useful. Most computers perform buffering Page 20

Unix, C & C++


of input and output. This means that they'll not start reading any input until the return key is pressed, and they'll not print characters on the terminal until there is a whole line to be printed. getchar getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of file) is returned instead. It is therefore usual to compare this value against EOF before using it. If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly. As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control - d. #include <stdio.h> main() { int ch, i = 0; while((ch = getchar()) != EOF) i ++; printf("%d\n", i); } Putchar putchar puts its character argument on the standard output (usually the screen). The following example program converts any typed input into capital letters. To do this it applies the function toupper from the character conversion library ctype.h to each character in turn. #include <ctype.h> /* For definition of toupper */ #include <stdio.h> /* For definition of getchar, putchar, EOF */ main() { int ch; while((ch = getchar()) != EOF) putchar(toupper(ch)); } printf The printf function is a very versatile output function. It can handle any basic data type, and offers several facilities with which you can specify the way in which the data must be displayed. This offers more structured output than putchar. Its arguments are, in order; a control string, which controls what, gets printed, followed by a list of values to be substituted for entries in the control string.

Page 21

Unix, C & C++


%d %f %c %s A decimal integer A floating point value A character A character string

It is also possible to insert numbers into the control string to control field widths for values to be displayed. For example %6d would print a decimal value in a field 6 space wide; %8.2f would print a real value in a field 8 space wide with room to show 2 decimal places. Display is left justified by default, but can be right justified by putting a - before the format information, for example %-6d, a decimal integer right justified in a 6 space field. scanf scanf allows formatted reading of data from the keyboard. Like printf it has a control string, followed by the list of items to be read. However scanf wants to know the address of the items to be read, since it is a function which will change that value. Therefore the names of variables are preceded by the & sign. Character strings are an exception to this. Since a string is already a character pointer, we give the names of string variables unmodified by a leading &. Control string entries which match values to be read are preceeded by the percentage sign in a similar way to their printf equivalents. 2.2.6 Functions Almost all programming languages have some equivalent of the function. You may have met them under the alternative names subroutine or procedure. Some languages distinguish between functions which return variables and those which don't. C assumes that every function will return a value. If the programmer wants a return value, this is achieved using the return statement. If no return value is required, none should be used when calling the function. Here is a function which raises a double to the power of an unsigned, and returns the result. double power(double val, unsigned pow) { double ret_val = 1.0; unsigned i; for(i = 0; i < pow; i++) ret_val *= val; return(ret_val); } The function follows a simple algorithm, multiplying the value by itself pow times. A for loop is used to control the number of multiplications, and variable ret_val stores the value to be returned. Careful programming has ensured that the boundary condition is correct too. ie

Page 22

Unix, C & C++


Let us examine the details of this function. double power(double val, unsigned pow) This line begins the function definition. It tells us the type of the return value, the name of the function, and a list of arguments used by the function. The arguments and their types are enclosed in brackets, each pair separated by commas. The body of the function is bounded by a set of curly brackets. Any variables declared here will be treated as local unless specifically declared as static or extern types. return(ret_val); On reaching a return statement, control of the program returns to the calling function. The bracketed value is the value which is returned from the function. If the final closing curly bracket is reached before any return value, then the function will return automatically, any return value will then be meaningless. The example function can be called by a line in another function which looks like this result = power(val, pow); This calls the function power assigning the return value to variable result. Here is an example of a function which does not return a value. void error_line(int line) { fprintf(stderr, "Error in input data: line %d\n", line); } The definition uses type void which is optional. It shows that no return value is used. Otherwise the function is much the same as the previous example, except that there is no return statement. Some void type functions might use return, but only to force an early exit from the function, and not to return any value. This is rather like using break to jump out of a loop. This function also demonstrates a new feature. fprintf(stderr, "Error in input data: line %d\n", line); This is a variant on the printf statement; fprintf sends its output into a file. In this case, the file is stderr. stderr is a special UNIX file which serves as the channel for error messages. It is usually connected to the console of the computer system, so this is a good way to display error messages from your programs. Messages sent to stderr will appear on screen even if the normal output of the program has been redirected to a file or a printer. The function would be called as follows error_line(line_number); Scope of Function Variables Only a limited amount of information is available within each function. Variables declared within the calling function can't be accessed unless they are passed to the called function as arguments. The only other contact a function might have with the outside

Page 23

Unix, C & C++


world is through global variables. Local variables are declared within a function. They are created anew each time the function is called, and destroyed on return from the function. Values passed to the function as arguments can also be treated like local variables. Static variables are slightly different; they don't die on return from the function. Instead their last value is retained, and it becomes available when the function is called again. Global variables don't die on return from a function. Their value is retained, and is available to any other function which accesses them. 2.2.7 Processor Directives The C preprocessor is a tool which filters your source code before it is compiled. The preprocessor allows constants to be named using the #define notation. The preprocessor provides several other facilities which will be described here. It is particularly useful for selecting machine dependent pieces of code for different computer types, allowing a single program to be compiled and run on several different computers. The C preprocessor isn't restricted to use with C programs, and programmers who use other languages may also find it useful, however it is tuned to recognize features of the C language like comments and strings, so its use may be restricted in other circumstances. The preprocessor is called cpp, however it is called automatically by the compiler so you will not need to call it while programming in C. The preprocessor directive #include is an instruction to read in the entire contents of another file at that point. This is generally used to read in header files for library functions. Header files contain details of functions and types used within the library. They must be included before the program can make use of the library functions. Library header file names are enclosed in angle brackets, < >. These tell the preprocessor to look for the header file in the standard location for library definitions. For example #include <stdio.h> Another use for #include for the programmer is where multi-file programs are being written. Certain information is required at the beginning of each program file. Local header file names are usually enclosed by double quotes, " ". It is conventional to give header files a name which ends in .h to distinguish them from other types of file. 2.2.8 Programming Style in C Unlike some other programming languages (COBOL, FORTRAN), C is free form language. We can group statements together on one line. The statements a = b; x = y+1; z = a+x; It can be written in one line as a = b; x = y+1; z = a+x; The generous use of comments inside the program cannot be overemphasized. Sensibly inserted comments not only increase the readability but also help to understand the program logic. This is very important for debugging and testing the program. Page 24

Unix, C & C++


2.2.9 Control Structure

Control structure is used to control the sequence of the program flow. They are of two categories namely: Selection Loops

Selection In this case a statement is executed based on whether a condition is true or false. Following statements are used in selective execution of statements. a. The if Statement

The if statement is used for decision-making. It executes a statement based on the result of evaluation of an expression. The general form of the simple if statement is if (expression) statement; where statement may consist of a single statement or a set of statements. If the if expression evaluates to true, the statement or block following the if is executed. For example: #include<stdio.h> main() { int a=10,b=10; if (b= =a) printf( the 2 values are equal); } Output: the 2 values are equal In the above code since the value of a and b are the same, the expression in the if is true and hence the statement following the if expression is executed. b. if else The ifelse statement is used for decision-making. It executes a statement based on the result of evaluation of an expression. The general form of the if ..else statement is if (expression) statement 1; else statement 2;

Page 25

Unix, C & C++


where statement 1, statement 2 may consist of a single statement or a block of statements. If the if expression evaluates to true, the statement 1 or block following the if is executed; otherwise, the statement 2 or block following the else is executed. The else statement is optional. It is used only if a statement or a sequence of statements is to be executed in case the if expression evaluates to false. Consider the following Program: #include <stdio.h> main() { int x, y; x = 3; y = 4; if (x > y) printf(" x is greater"); else printf(" y is greater"); } Output: y is greater In the above program, variable x has been assigned the value 3 and variable y has been assigned the value 4. In this case, since the value of x is not greater than y, the if expression is false and hence the statement following if is not executed while the statement following else is executed. c. The if-else-if Statement

This is another common programming construct adapted from the initial if statement. The general form of this is: if (expression) statement; else if (expression) statement; else if (expression) statement; .. .. else statement; This construct is also known as the if-else-if ladder or if-else-if staircase. Though the above indentation is easily understandable with one or two ifs, it confuses as the number of if increases. This is because it gets deeply indented and so, the if-else-if is generally indented as:

Page 26

Unix, C & C++


if (expression) statement; else if (expression) statement; . else statement; The conditions are evaluated from top to bottom. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder is bypassed. If none of the conditions are true the final else is executed. If the final else is not present, no action takes place if all other conditions are false. The following example takes a choice from the user. If the choice ranges from 1 to 3 it prints the choice else it prints Invalid choice. #include <stdio.h> #include <conio.h> main() { int x; x = 0; clrscr(); printf("Enter Choice (1 - 3) : "); scanf("%d", &x); if (x == 1) printf("\nChoice is 1"); else if (x == 2) printf("\nChoice is 2"); else if (x == 3) printf("\nChoice is 3"); else printf("\nInvalid Choice "); } Output: Enter Choice (1 - 3) : 1 Choice is 1 If the first condition (x ==1) is true then, the following printf() will be executed and the control will come out of the block. If the first condition is not true, the if corresponding to the first else will be checked. In case this if condition is satisfied, the printf() corresponding to this if will be executed and the block will be exited; otherwise the else following this if will be executed.

Page 27

Unix, C & C++


The switch Statement The switch statement is a multi-way decision maker that tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. The general form of the switch statement is: switch (expression) { case constant1: statement sequence break; case constant 2: statement sequence break; case constant 3: statement sequence break; default: statement sequence }

where switch, case, break and default are the keywords and statement sequence can be simple statement or a compound statement which need not be enclosed in parentheses. The expression following switch must be enclosed in parentheses and the body of the switch must be enclosed within the curly braces. The datatype of the expression given and the datatype of the case constants given should be compatible. As suggested by the name, case labels can be only integer or character constant or constant expressions, which do not contain any variable names. Case labels must all be different. In the switch statement, the expression is evaluated and the value is compared with the case labels in the given order. If a label matches with the value of the expression, the statement mentioned will be executed. The break statement ensures immediate exit from the switch statement. If a break is not used in a certain case, the statements in the following case are also executed irrespective of whether that case value is satisfied or not. This execution will continue till a break is encountered. Therefore, break is said to be one of the most important statement while using a switch. The statements against default will be executed, if none of the other cases are satisfied. The default statement is optional. If it is not present and the value of the expression does not match with any of the cases, then no action will be taken. The order of the case labels and default is immaterial. /* switch Statement */ #include<stdio.h> #include<conio.h> Page 28

Unix, C & C++


main() { char ch; clrscr (); printf("\n Enter a lower case alphabet (a-z): "); scanf("%c", &ch); if (ch < 'a' || ch >'z') printf("\nCharacter not a lower case alphabet"); else switch(ch) { case 'a': case 'e': case 'i' : case 'o': case 'u': printf("\nCharacter is a vowel"); break; case 'z' : printf("\nLast Alphabet (z) was input"); break; default: printf("\nCharacter is a consonant"); break; } } Output: Enter a lower case alphabet (a z): g Character is a consonant The program will take a lower case alphabet as an input and display whether it is a vowel, the last alphabet or a consonant. Loops Loops follow the iteration concept. Loops allow a set of instructions to be performed until a certain condition becomes false. This condition may be predefined or open ended. The loop structures available in C are: The for loop The while loop The do...while loop for loop It is an entry-controlled loop that provides a more concise loop control structure. Page 29

Unix, C & C++


The general form is: for (initialization; test-condition; increment/decrement) { statement } The execution of for statement is as follows: Initialization of the control variables is done by using the assignment statement such as i= 1 and count =0. The variable i and count are known as loop-control variables. The value of the control variable is tested using the test-condition. The test condition is a relational expression, such as i < 10 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise, the loop is terminated and the execution continues with the statement that immediately follows the loop. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such as i = i + 1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test-condition. Consider the following segment of a program: for (x = 0 ; x<=9; x= x+1) { printf("%d",x); } printf("\n"); This for loop is executed 10 times and prints the digits 0 to 9 in one line. Semicolons must separate the three sections enclosed within parentheses. Note that there is no semicolon at the end of the increment section, x = x +1. /* Program to display 1 to 10 numbers on the screen */ #include <stdio.h> main() { int num; for(num =1 ; num <=10; num ++) printf("%d", num); } Output: 12345678910

Page 30

Unix, C & C++


a. The while Statement

The while statement is used to carry out looping operations, in which a group of statements is executed repeatedly, until some condition has been satisfied. The general form of while statement is while (expression ) { statement } The statement will be executed repeatedly, as long as the expression is true. This statement can be simple or compound, though it is usually a compound statement. It must include some feature that eventually alters the value of the expression, thus providing a stopping condition for the loop. #include <stdio.h> main() /* display the integers 0 through 9 */ { int digit = 0; while (digit <= 9) { printf("%d\n",digit); ++digit; } } Output: 0 1 2 3 4 5 6 7 8 9 Initially, digit is assigned a value 0. The whileloop then displays the current value of digit, increase its value by 1 and then repeats the cycle, until the value of digit exceeds 9. The net effect is that the body of the loop will be repeated 10 times, resulting in 10 consecutive lines of output. Each line will contain a successive integer value, beginning with 0 and ending with 9.

Page 31

Unix, C & C++


The dowhile Loop The dowhile loop is sometimes referred to as doloop in C. Unlike for and while loops, this loop checks its condition at the end of the loop, that is, after the loop has been executed. This means that dowhile loop will execute at least once, even if the condition is false initially. The general form of dowhile is: do { statements; } while (condition); The curly brackets are not necessary when only one statement is present within the loop, but it is a good habit to use them. do..while loop iterates until the condition becomes false. In the dowhile the statement (block of statements) is executed first, then the condition is checked. If it is true, control is transferred to the do statement. When the condition becomes false, control is transferred to the statement after the loop. Consider the following: /* accept only int values */ #include <stdio.h> main() { int I,j; I = j = 0; do { printf("\nEnter : "); scanf("%d",&I); printf("No. is %d", I); j++; } while (I !=0); printf("\nThe total numbers entered were %d", --j); /* j is decremented before printing because count for last integer (0) is not to be considered */ } Output: Enter : 5 No. is 5 Enter : 3 No. is 3 Enter : 0 No. is 0 The total numbers entered were 2 The above program accepts integers and display them until zero(0) is entered. It will then, exit the dowhile and print the number of integers entered. Page 32

Unix, C & C++ 2.3 Revision Points

Operators C supports a rich set of operators. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation. Operators are used in programs to manipulate data and variables. Control Statements C language possesses such decision making capabilities and supports the following statements known as control or decision making statements.

2.4

Intext Questions
1. 2. 3. 4. 5. List out the popular features of C. What are the different types of qualifiers? What are the components of a format specifier in a printf statement? In what ways does a switch statement is differ from if statement? Explain the differences between a break statement and continue statement with examples.

2.5

Summary
A variable is an entity that has value and is known to the program by a name. In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function. Every variable has a name and a value. The name identifies the variable, the value stores data. There is a limitation on what these names can be. Every variable name in C must start with a letter; the rest of the name can consist of letters, numbers and underscore characters. Local variables are declared within the body of a function, and can only be used within that function.

Page 33

Unix, C & C++


Alternatively, a variable can be declared globally so it is available to all functions. Modern programming practice recommends against the excessive use of global variables. A global variable declaration looks normal, but is located outside any of the program's functions. This is usually done at the beginning of the program file, but after preprocessor directives. An operator is a function which is applied to values to give a result. You should be familiar with operators such as +, -, /. Other operators are used for comparison of values, combination of logical states, and manipulation of individual binary digits. Operators and values are combined to form expressions. The values produced by these expressions can be stored in variables, or used as a part of even larger expressions. A program consists of a number of statements which are usually executed in sequence. Programs can be much more powerful if we can control the order in which statements are run.

2.6

Terminal Exercises
1. 2. 3. 4. 5. What are the various compilers available for C and the operating systems they run on? The maximum length of a variable in C is _______________. Character constants should be enclosed between _______________. The operator && is an example for ___ operator. The associativity of ! Operator is _______________.

2.7

Supplementary Materials
1. Byron Gottfried, Programming with C, Second Edition, TMH, 1998. 2. Deitel & Deitel, C How to program, Pearson Education Ltd, 2001.

Page 34

Unix, C & C++ 2.8 Assignments


1. 2. Write a program to generate the first fifteen terms of the Fibonacci series and print their sum and average. Write a program to find second largest and second smallest element from the set of elements.

2.9

Suggested Reading/Reference Books/Set Books


1. Venugopal and Prasad, Programming with C, TMH, 2001. 2. Balagurusamy, Programming in ANSI C, TMH, 1992.

2.10 Learning Activities


1. 2. Why UNIX is considered a natural operating environment for C programs? How can C exploit the features of UNIX? Contrast the salient features of exit control and entry control structures.

2.11 Keywords
Stdio.h Scanf if break int printf main else-if continue c preprocessor.

Page 35

Das könnte Ihnen auch gefallen