Vous êtes sur la page 1sur 20

Overview of C language C Fundamental : Introduction to C, Character Set, Identifiers, Keywords, Data types, Constants, variable, User defined data

types, arithmetic, unary, relational, logical, assignment and conditional operators & expressions, Basic structure of C program. Data I/O statement: Single character I/O, Formatted I/O, String I/O functions. Introduction to C C was invented and first implemented by Dennis Ritchie on a DEC PDP-11 that used the UNIX operating system. C is the result of a development process that started with an older language called BCPL. BCPL was developed by Martin Richards, and it influenced a language called B, which was invented by Ken Thompson. B led to the development of C in the 1970s. C is often called a middle-level computer language. This does not mean that C is less powerful, harder to use, or less developed than a high-level language such as BASIC or Pascal, nor does it imply that C has the cumbersome nature of assembly language. Rather, C is thought of as a middle-level language because it combines the best elements of high-level languages with the control and flexibility of assembly language. As a middle-level language, C allows the manipulation of bits, bytes, and addressesthe basic elements with which the computer functions. Despite this fact C code is also very portable. Portability means that it is easy to adapt software written for one type of computer or operating system to another. For example, if you can easily convert a program written for DOS so that it runs under Windows, that program is portable. Characterstics of C

There are various characteristics of C. These are 1. Modularity. 2. Portability.

3. Extendibility. 4. Speed. 5. Flexibility. Modularity: Ability to breakdown a large module into manageable sub modules called as modularity that is an important feature of structured programming languages. Advantages: 1. Projects can be completed in time. 2. Debugging will be easier and faster. Portability: The ability to port i.e. to install the software in different platform is called portability. Highest degree of portability: C language offers highest degree of portability i.e., percentage of changes to be made to the sources code is at minimum when the software is to be loaded in another platform. Percentage of changes to the source code is minimum. The software that is 100% portable is also called as platform independent software or architecture neutral software. E.g.: Java. Extendibility: Ability to extend the existing software by adding new features is called as extendibility. SPEED: C is also called as middle level language because programs written in c language run at the speeds matching to that of the same programs written in assembly language so c language has both the merits of high level and middle level language and because if this feature it is mainly used in developing system software. Flexibility:

Key words or reverse words. ANSIC has 32 reverse words. C language has right number of reverse words which allows the programmers to have complete control on the language. The simplest C program

C is a high level programming language and that you need a C compiler to translate your C programs into binary code that your computer can understand and execute.

In this chapter we will write a simple C program and the basics of that c program.

/* This is my first C program */ 1. 2. 3. 4. 5. #include<stdio.h> void main() { printf(Hello World); }

This is a very simple program which you can save with any name with extension .c.

#include <stdio.h> is a header file which is a standard input output file. Void is a keyword. Main() is a function. Printf is an output function.

The Five Basic Data Types

There are five atomic data types in C: character, integer, floating-point, double floating-point and valueless (char, int, float, double, and void, respectively). The exact format of floating-point values will depend upon how they are implemented. Integers will generally correspond to the natural size of a word on the host computer. Values of type char are generally used to hold values defined by the ASCII character set. Values outside that range may be handled differently by different compilers. The range of float and double will depend upon the method used to represent the floating-point numbers. Whatever the method, the range is quite large. The minimum number of digits of precision for each floating-point type is shown in Table.

Modifying the Basic Types Except for type void, the basic data types may have various modifiers preceding them. You use a modifier to alter the meaning of the base type to fit various situations more precisely. The list of modifiers is shown here: Signed Unsigned Long

Short You can apply the modifiers signed, short, long, and unsigned to integer base types. You can apply unsigned and signed to characters. You may also apply long to double. Operators C/C++ is very rich in built-in operators. In fact, it places more significance on operators than do most other computer languages. There are four main classes of operators: arithmetic, relational, logical, and bitwise. In addition, there are some special operators for particular tasks. The Assignment Operator You can use the assignment operator within any valid expression. The general form of the assignment operator is variable_name = expression; e.g x=a; here the value of a is assigned to x. Arithmetic Operators The operators +, -, *, and / work as they do in most other computer languages. You can apply them to almost any built-in data type. When you apply / to an integer or character, any remainder will be truncated. For example, 5/2 will equal 2 in integer division. The modulus operator % also works in C/C++ as it does in other languages, yielding the remainder of an integer division. However, you cannot use it on floating-point types. The following code fragment illustrates %: int x, y; x = 5; y = 2; printf("%d ", x/y); /* will display 2 */ printf("%d ", x%y); /* will display 1, the remainder of the integer division */ x = 1; y = 2;

printf("%d %d", x/y, x%y); /* will display 0 1 */ The last line prints a 0 and a 1 because 1/2 in integer division is 0 with a remainder of 1. The unary minus multiplies its operand by 1. That is, any number preceded by a minus sign switches its sign.

Increment and Decrement C/C++ includes two useful operators not generally found in other computer languages. These are the increment and decrement operators, ++ and - -. The operator ++ adds 1 to its operand, and subtracts one. In other words: x = x+1; is the same as ++x; and x = x-1; is the same as x--; Both the increment and decrement operators may either precede (prefix) or follow (postfix) the operand. For example, x = x+1; can be written ++x; or x++; There is, however, a difference between the prefix and postfix forms when you use these operators in an expression. When an increment or decrement operator precedes its operand, the increment or decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, the value of the operand is obtained before incrementing or decrementing it. For instance, x = 10; y = ++x; sets y to 11. However, if you write the code as x = 10;

y = x++; y is set to 10. Either way, x is set to 11; the difference is in when it happens. Relational and Logical Operators In the term relational operator, relational refers to the relationships that values can have with one another. In the term logical operator, logical refers to the ways these relationships can be connected. Because the relational and logical operators often work together, they are discussed together here. The idea of true and false underlies the concepts of relational and logical operators. In C, true is any value other than zero. False is zero. Expressions that use relational or logical operators return 0 for false and 1 for true. C++ fully supports the zero/non-zero concept of true and false. Table shows the relational and logical operators. The truth table for the logical operators is shown here using 1's and 0's.

Bitwise Operators Unlike many other languages, C/C++ supports a full complement of bitwise operators. Since C was designed to take the place of assembly language for most programming tasks, it needed to be able to support many operations that can be done in assembler, including operations on bits. Bitwise operation refers to testing,

setting, or shifting the actual bits in a byte or word, which correspond to the char and int data types and variants. You cannot use bitwise operations on float, double, long double, void, bool, or other, more complex types. Table 2-6 lists the operators that apply to bitwise operations. These operations are applied to the individual bits of the operands.

Type Conversion in Expressions


When constants and variables of different types are mixed in an expression, they are all converted to the same type. The compiler converts all operands up to the type of the largest operand, which is called type promotion. First, all char and short int values are automatically elevated to int. (This process is called integral promotion.) Once this step has been completed, all other conversions are done operation by operation, as described in the following type conversion algorithm: IF an operand is a long double THEN the second is converted to long double ELSE IF an operand is a double THEN the second is converted to double ELSE IF an operand is a float THEN the second is converted to float ELSE IF an operand is an unsigned long THEN the second is converted to unsigned long ELSE IF an operand is long THEN the second is converted to long ELSE IF an operand is unsigned int THEN the second is converted to unsigned int

Casts You can force an expression to be of a specific type by using a cast. The general form of a cast is

(type) expression where type is a valid data type. For example, to make sure that the expression x/2 evaluates to type float, write (float) x/2 Casts are technically operators. As an operator, a cast is unary and has the same precedence as any other unary operator. Although casts are not usually used a great deal in programming, they can be very useful when needed. For example, suppose you wish to use an integer for loop control, yet to perform computation on it requires a fractional part, as in the following program: #include <stdio.h> int main(void) /* print i and i/2 with fractions */ { int i; for(i=1; i<=100; ++i) printf("%d / 2 is: %f\n", i, (float) i /2); return 0; } Without the cast (float), only an integer division would have been performed. The cast ensures that the fractional part of the answer is displayed. Constants and Variables The alphabets, numbers and special symbols when properly combined form constants, variables and keywords. A constant is an entity that does not change. E.G int a=5; Now the value of a will be 5 throughout the program. Variables: A variable is an entity that may change it value. In any program we typically do lots of calculations. The results of these calculations are stored in computer memory locations. To make the retrieval and usage of these values we give names to the memory locations. These names are called variables. int i,j,l; short int si; unsigned int ui;

double balance, profit, loss; Keywords: A keyword is a word that is part of C Language itself. These words have predefined meanings and these words cannot be used as variable names.

Types of Variables There are two main types of variables in C: numeric variables that hold only numbers or values, and string variables that hold text, from one to several characters long. Basic fundamental data types in C Language Name Description Size Range signed: -128 to 127 Char Character or small integer. 1byte unsigned: 0 to 255 signed: -32768 to 32767 short int Short Integer. 2bytes unsigned: 0 to 65535 signed: -2147483648 to long int (long) Long integer. 4bytes2147483647 unsigned: 0 to 4294967295 Boolean value. It can take Bool one of two values: true or 1byte true or false false. Float Floating point number. 4bytes+/- 3.4e +/- 38 (~7 digits) Double precision floating Double 8bytes+/- 1.7e +/- 308 (~15 digits) point number. Long double precision long double 8bytes+/- 1.7e +/- 308 (~15 digits) floating point number.

Loops in c Loops are used to repeat one statement or set statements more than one time. Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory. There are several ways to loop in C. For Loop For loop is a counter loop. The for loop allows automatic initialization of instrumentation of a counter variable. The general form is for (initialization; condition; increment/decrement) { statements block } If the statement block is only one statement, the braces are not necessary. Although the for allows a number of variations, generally the initialization is used to set a counter variable to its starting value. The condition is generally a relational statement that checks the counter variable against a termination value, and the increment increments (or decrements) the counter value. The loop repeats until the condition becomes false. Example Main() { int i;

for(i = 0; i < count; i++) {

printf(%d\n,i); } } While Loop The while loop repeats a statement until the test at the top proves false. The while loop has the general form: while(condition) { statement block }

The while tests its condition at the top of the loops. Therefore, if the condition is false to begin with, the loop will not execute at all. The condition may be any expression. An example of a while follows. It reads characters until end-of-file is encountered. Example main(){ int t = 0; while(t<=10) { printf(%d\n,t); t=t+1; } } do-while loop This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable. void main(void){ int val; do

{ printf("Enter 1 to continue and 0 to exit :"); scanf("%d\n", &val); } while (val!= 1 && val!= 0) }

Control Structure in c C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements. 1. if statement 2. switch statement 3. Conditional operator statement 4. goto statement

if Statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. Syntax if (conditional) { block of statements executed if conditional is true; } else { block of statements if condition false; } Example

main() { int x=5 if (x > 1) { x=x+10; } printf("%d", x); } ifelse statement The if....else statement is an extension of the simple if statement. The general form is if (condition) { True-block statement(s) } else { False-block statement(s) }

If the condition is true, then the true-block statement(s), immediately following the if statement are executed; otherwise the false-block statement(s) are executed. void main(void) { int a, b; char ch;

printf("Choice:\n"); printf("(A) Add, (S) Subtract, (M) Multiply, or (D) Divide?\n"); ch = getchar(); printf("\n"); printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); if(ch=='A') printf("%d", a+b); else if(ch=='S') printf("%d", a-b); else if(ch=='M') printf("%d", a*b); else if(ch=='D' && b!=0) printf("%d", a/b); } if-else-if statement void main() { int numb;

printf("Type any Number : "); scanf("%d", &numb); if(numb > 0) { printf("%d is the positive number", numb); } else if(numb < 0) printf("%d is the Negative number", numb); else printf("%d is zero",numb);

} Switch Statement: The switch and case statements help control complex conditional and branching operations. The switch statement transfers control to a statement within its body. Syntax: switch (expression) { case item: statements; break; case item: statements; break; case item: statements; break; default: statement; break; } Example: #include <stdio.h> void main(){ int n; printf(Type any Number); scanf(%d,&n); switch(n) { case 0 : printf("Monday);

break; case 1 : printf("Tuesday); break; case 2 : printf("Wednesday); break; case 3 : printf("Thursday); break; case 4 : printf("Friday); break; case 5 : printf("Saturday); break; case 6 : printf(Sunday); break; } } Ternary condition The ? (ternary condition) operator is a more efficient form for expressing simple if statements. It has the following form: expression1 ? expression2: expression3 Example: res = (a>b) ? a : b; if a is greater than b than res has the value a else the res has value b. break statement break statement is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch. With loops, break can be used to force an early exit from the loop, or to implement

a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition. Example For(i=0;i<=10;i++) { if(i==5){ break; } printf(\n%d,i); } Output: 0 1 2 3 4 continue statement

continue is similar to the break statement but it only works within loops where its effect is to force an immediate jump to the loop control statement. Like a break, continue should be protected by an if statement. Example For(i=0;i<10;i++) { if(i==5){ continue; } printf(\n%d,i); } Output: 0 1 2 3 4 6

7 8 9

The goto statement The goto is a unconditional branching statement used to transfer control of the program from one statement to another. One must ensure not to use too much of goto statement in their program because its functionality is limited. It is only recommended as a last resort if structured solutions are much more complicated.

Vous aimerez peut-être aussi