ppt lab 444

62
C Programming in Linux Lab Session 4 Editing, compiling and running C programs in Lin

Upload: muhammedyeshaw

Post on 08-Nov-2015

244 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

C Programming in LinuxLab Session 4Editing, compiling and running C programs in Linux Instructors:Reasons:Introduction C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C. C's power and flexibility soon became apparent. Because of this, the UNIX operating system which was originally written in assembly language was almost immediately re-written in C (only the assembly language code needed to "bootstrap" the C code was kept). During the rest of the 1970's, C spread throughout many colleges and universities because of its close ties to UNIX and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems. In response to this in 1983, the American National Standards Institute (ANSI) formed a committee to establish a standard definition of C which became known as ANSI Standard C. Today C is in widespread use with a rich standard library of functions.

Introduction Significant Features of C C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. It allows low level access to information and commands while still retaining the portability and syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs. C's power and fast program execution come from it's ability to access low level commands, similar to assembly language, but with high level syntax. Its flexibility comes from the many ways the programmer has to accomplish the same tasks. C includes bitwise operators along with powerful pointer manipulation capabilities. C use of modularity. Sections of code can be stored in libraries for re-use in future programs. The core C language leaves out many features included in the core of other languages. The UNIX operating system, the C compiler, and essentially all UNIX applications programs have been written in C. The C has now become a widely used professional language for various reasons. Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computer platforms. Facts about CC was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970sThe language was formalized in 1988 by the American National Standard Institute (ANSI). The UNIX OS was totally written in C by 1973. Today C is the most widely used and popular System Programming Language. Most of the state-of-the-art softwares have been implemented using C.Today's most popular Linux OS and RBDMS MySQL have been written in C.

C- Language Overview Why to use C??? C was initially used for system development work, in particular the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be: Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Databases Language Interpreters Utilities Strength : + Efficiency: intended for applications where assembly language had traditionally been used. + Portability: hasnt splintered into incompatible dialects; small and easily written + Power: large collection of data types and operators + Flexibility: not only for system but also for embedded system commercial data processing + Standard library + Integration with UNIX Weakness: + error-prone + difficult to understand + difficult to modify

Why to use C??? Creating and Compiling C Common editors to create C program by Shell are :- Gedit /Text editor GUI Text Editor like notepad or wordpad Pico/Nano editor simple text editor Pico/nano editors are easier to use (most command options are displayed at the bottom of the screen Vi Editor Open editor to create c files with FileName dot extension C (name.c)

Eg. gedit first.c , nano hello.c, vi name.c and etc

Compile and Run C Program How to Compile and Run a C Program on Ubuntu Linux Steps : Create C programs (Use a any editor) eg. gedit hello.c

Compile the program , type the command gcc -o hello hello.c invoke the GNU C compiler to compile the file hello.c and output (-o) the result to an executable called hello. Execute the program , type the command ./hello This should result in the output Hello WorldYou can execute the C program using command gcc $ gcc -o hello hello.c $ ./hello

// first progrma to display hello world /*comment */ #include // Preprocessor (header file)main() // Preprocessor (header file) {printf("Hello World\n"); // program statement (body) }(Compile:syntax:gcc o executable objectname source filename.c Compile:e.g: gcc o one one.c Run:./oneIdentifiers in C Identifiers also called programmer defined words used to represent and reference certain program entities. Variable, function, and user-defined type names are all examples of identifiers. In C identifiers are sequences of letters, digits, and underscores from one to several characters in length.Rules for constructing IdentifiersIdentifiers can consists of the capital letter A to Z, the lowercase letters a to z, the digits 0 to 9, the underscore character.The first character must be a letter or underscore.There is virtually no length limitation. However, in many implementations of the C language, the compiler recognizes only the first 32 characters as significant.There can be no embedded blanks.Reserved words cannot be used as identifiers.Identifiers are case sensitive. Therefore Tax and tax are valid identifiers but distinct.

Keywords

Data Type A data type is a set of data values and a set of operations on those values. C has two classes of data types:Built-in data types (that are recognized by the C programming language)Programmer-defined data types (that can be defined by the programmer)C also has two classes of built-in data types:Fundamental data types: corresponds to the most common. fundamental data type in C are in int , char and float. float tax, int x, char f , double z, .Derived data types: are derived form fundamental and programmer-defined types using some operators. eg. array, string and structures are derived data types

Data Type Basic data type in C are:- Integer: 1. Signed Short integer(short, short int, signed short, signed short int) Integer (int, signed, signed int) Long integer( long, long int, signed long, signed long int) 2. Unsigned Short integer ( unsigned short, unsigned short int) Integer (unsigned, unsigned int) Long integer (unsigned long, unsigned long int) Floating-point: 1. Floating-point (float) 2. Double floating-point (double) 3. Long double floating-point (long double) Character (char)

Constant Constants: are identifiers whose value is fixed and does not change during the execution of a program in which it appears. In C the declaration of a named constant begins with the keyword const, continues with a type specifier for the constant, and concludes with an initialization for the identifier that will be treated as a named constant as shown in the example below.const int idnumber = 34;The preprocessor #define is another more flexible method to define constants in a program. #define TRUE1 #define FALSE 0 #define NAME_SIZE 20Here TRUE, FALSE and NAME_SIZE are constant

Operators in C

Arithmetic Operators Equality Operators

Operators in C

C operators and operator precedence pOperators in C Relational Operators Relational operators are used to compare values. An expression that compares two expressions using a relational operator is called a simple predicate. C has six relational operators: Equal to = = Not equal to != Less than < These may be used in expressions of the form: Logical (Boolean) Operators There are three operators that are commonly used to combine expressions involving relational operators. These are 3 logical operators:and && or || not!

Less than or equal to Greater than or equal to >=pOperators in C Increment and Decrement Operators The operators ++ and - are called increment and decrement operators. a++ and ++a are equivalent to a += 1. a-- and --a are equivalent to a -= 1. ++a op b is equivalent to a ++; a op b; a++ op b is equivalent to a op b; a++; Example Let b = 10 then(++b)+b+b = 33b+(++b)+b = 33b+b+(++b) = 31b+b*(++b) = 132 pCasting Operator Explicit Type Conversions: The Cast Operator and Casting In C explicit type conversion is possible through the use of cast operator. The operation of explicitly converting the type of an expression in temporary storage to a specified type is called casting and its form is as follow: (type) Expression where Type is a type specifier such as int, double, or char. Let us assume that we have the following declaration: double first = 4.7; int second = 27; then we can use cast operator to convert the type of the operands in the statements below:

pExpression in C Expression is a combination of operators, variables based on the rule of programming language rule . Example of Expression in c : a = b += c++ - d + --e / -f a = b += (c++) - d + --e / -f a = (b += (((c++) d) + ((--e) / (-f)))) (a = (b += (((c++) d) + ((--e) / (-f))))) (A || B) num1 > num2a++ expr1? expr2:expr3; if expr1 is true then expr2 else expr3 (conditional expressions with Ternary Operator)Printf(%d=%d,a, (a+b)*c);

Input and Output Function The Standard Output Function printf The purpose of printf function is to print values using the standard output device, the monitor screen. There are two syntactical forms for the printf function call: printf (FormatControlString); or printf(FormatControlString, PrintList); An example of the first form is the output statement printf (This is Ethiopia); which prints the string constant This is Ethiopia on the monitor screen. For the second form let see the following declaration and output statement: float distance = 550.0; printf (The distance from Addis Ababa to Bahirdar is %f KM, distance); it prints the string constant The distance from Addis Ababa to Mekelle is 550 KM on the monitor screen.

printf(string, expr1, expr2, ..)string: ordinary characters and conversion specifications (%) %d --- int %s --- string %f --- floatWe can use the following format specifiers in the format control string of the printf function:

The Standard Input Function scanf As printf function the declaration of the standard library function scanf is contained in the header file . The syntax of the scanf function call is as follows: scanf (FormatControlString, InputList); The following input and output statements accept the distance from Addis Ababa to Bahirdar from the user of the program. printf (What is the distance from Addis Ababa to Bahirdar); scanf(%lf, &distance);The ampersand character & tell the scanf function where to find the variable into which values are to be stored. The format specifiers in the format control string of the scanf function is similar to printf as shown above. Input and Output Function

Comments are explanations or annotations that are included in a program for documentation and clarification purposes. Program comments describe the purpose of a program, function, or statement and they are completely ignored by the compiler. There are two ways to specify a comment in the C language. /* and */ to surround comments, or // (line comment) to begin comment lines. Rules for program commentsThe character /* start a comment. Such a comment can run any number of lines and over line boundaries. A comment that starts with /* should be terminated by the character */.The character // start a line comment. Such a comment terminates at the end of the line on which it occurs. If a line comment runs several lines, each line must begin with //.The comment characters //, /*, and */ are treated like other characters in a // comment.Comments in CStandard Library in C stdio library used for interactive I/O (input output) operations. # include math library contains some standard mathematical functions such as square root logarithm, trigonometry, etc.string library which is needed for character string processing. Each of such libraries consists of a header file & some object programs corresponding to the routines (functions) declared in the file. Most header files have the extension .h. To use a standard library you must put: # include at the start of your program.

Standard Library in C .. More header files complex number arithmetic Macro reporting error conditions limit float types format conversation of integer type sizes of basic types common mathematical functions variavle arguments atomic types Boolean type Fixed-width integer types input/output Non-returning functions String handling typed-generic math (macros wrapping math.h and complex.h) thread library Time/date utilities general utilities: memory Managements , program utilities, String converstions , random numbersStandard Library in C .. More header files Dynamic memory management: Defined in header malloc : allocates memory (function) calloc: allocates and zeroes memory(function) realloc: expands previously allocated memory blockfree: deallocates previously allocated memory aligned_alloc: allocates aligned memory Program support utilities: Defined in header abort : causes abnormal program termination (without cleaning up) exit : causes normal program termination with cleaning up quick_exit : causes normal program termination without completely cleaning up atexit : registers a function to be called on exit() invocation (function) Pseudo-random number generation : Defined in header rand: generates a pseudo-random number (function) srand : seeds pseudo-random number generator (function) RAND_MAX: maximum possible value generated by rand(() (macro constant) signal: sets a signal handler for particular signal (function) raise: runs the signal handler for particular signal (function) sig_atomic_t: the integer type that can be accessed as an atomic entity from an asynchronous signal handler (typedef) SIG_DELSIG_IGN: defines signal handling strategies (macro constant) SIG_ERR: error was encountered (macro constant)

Control Structure in C Control structure (instruction) enables us to specify the order in which instructions in a program are to be executed by the computer, i.e. it determines the flow of control in a program. The sequence control structure: step by step sequence The decision (conditional) control structure if and switchLoop control structure : For while and do

1. if : If statement: The syntax of an if-statement is if () ; 2. If-else statement: An if-statement may be followed immediately by an else-statement. The syntax of an else-statement is if () ; else ; /* end if */ 3. Nested If-Else statement: is formed when an entire if-else construct within either the body of the if-statement or the body of the else statement. This is also called nesting of ifs. The syntax of nested if statement is: if (){ orif (){ ; ; if () else ; if () else ; ;else else ; ;}}

Control Structure in C / conditional 4. Switch case The switch statement provides a very useful alternative to multiple if statements. It is used in conjunction with the case and default statements. The syntax is switch(integral expression) statement The controlled statement, known as the switch body will consist of a sequence of case statements. The syntax of a case statement is case constant-integral-expression : statementThe flow of control then continues from that point until a break is encountered or the end of the switch body is encountered. A break statement takes control out of the switch body.If none of the case labels match the value of the switch expression then no part of the code in the switch body is executed unless a default statement appears within the switch body.

Control Structure in C / conditional The example program below is a variant of a program that we have already seen in nested if-else statement. #include main() { intn1,n2; char c; char inbuf[30]; while(1) { printf("Enter Expression "); if(gets(inbuf) == NULL) break; scanf(inbuf,"%d%c%d",&n1,&c,&n2); switch(c) { case '+' : printf("%d\n",n1+n2);break; case '-' : printf("%d\n",n1-n2);break; case '*' : printf("%d\n",n1*n2);break; case '/' : printf("%d\n",n1/n2);break; default : printf("Unknown operator %c\n",c); } } }

Example 1. For loopThe for statement provides an alternative way of programming loops. The syntax of the for statement is as follow: For ( InitializationExpression; LoopControlExpression; UpdateExpression ) LoopBody /*end for*/In this syntax InitializationExpression is a C expression that may assign an initial value to a loop control variable, and UpdateExpression is one that may change value. The LoopControlExpression is an expression that computes to zero (for false) or a nonzero value (for true). In executing a for statement, the computer does the following:Executes the InitializationExpression.Evaluate the LoopControlExpression. If it computes to zero, the loop is exited.If the LoopControlExpression yields a nonzero value, the LoopBody is executed and then the UpdateExpression is evaluated.Test the LoopControlExpression again. Thus the LoopBody is repeated until the LoopControlExpression computes to a zero value.

Control Structure in C / loops 1. Example main(){inti;for(i=0;i=10) break; // what is the effect if it is continue? printf("%d %d %d\n",i,i*i,i*i*i); i++; } }

Break and Continue Example: main(){ int max; int sum=0,count=0; int i=0; printf("Enter largest number "); scanf("%d",&max); while(1) { i++; if(i == max) break; if(i%4 == 0) continue; count++; sum += i; } printf("There are %d numbers not divisible by 4" " and less than %d\nTheir total is %d\n", count,max,sum);}

Break and Continue Output:- Enter largest number : 15There are 11 numbers not divisible by 4 and less than 15Their total is 81 A nested loop is a repetition structure that contains one or more loops in its body. In a nested loop structure, in every repetition of the outer loop the inner loops are completely executed. A loop contained in another loop forms a doubly nested loop. A doubly nested loop can be placed inside another loop to form triply nested loop, and so on. In C a nested loop structure may be formed using while, for, and do-while statements.

Nested Loops The following example shows nested while loops being used to print out multiplication tables. main(){ int i=1,j; while(i