Anda di halaman 1dari 34

By-Arvind Singh

History of C:C is a programming language developed at AT & Ts Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In that time some languages were there like Algol-60 and Pascal. C language is member of Algol-60 based languages. CPL (Combined Programming Language) was built but it never implemented after BCPL (Basic CPL) came as implemented language. It was rewritten by Ken Thompson in 1970 named B specially for UNIX Operating System. Dennis M. Ritche added some new features and introduced a new language called C language. The major advance of C over the languages B and BCPL was its typing structure. C language adopted some features from Algol-68 also. The Future of C Language:Although the C may be a base for successful object oriented extensions like C++ and Java, C still running to remain and be used with same qualities as ever. C is still a preferable language to write short efficient low-level code that interacts with the hardware and OS. The old C programmers sometimes used assembly language for doing jobs that is not possible to do in C. In future, the programmers in other programming languages may do the same. They will write the code in their favorite language and for low-level routines and efficiency they will code in C using it as an assembly language. Advantages of C language:- It's a systems language (which means it can be used to do low-level programming with minimal or no run-time). - It is essentially high level assembly (it was designed to write portable OS's in, ) - A lot of libraries are written in C and it's easy to find reference code, and to get support. - C code is readable by people who understand most other curly-bracket languages (C++, D, Java, C#). - It lacks advance features (somewhat a disadvantage), but combined with the above point it's a good language to demonstrate code in. C lacks features like classes, templates, and exceptions. Overall, it's declining as an applications language, but still holding strong as a systems language. Disadvantages of C Language:1. There is no runtime checking. 2.There is no strict type checking( for ex: we can pass an integer value for the floating data type). 3. As the program extends it is very difficult to fix the bugs What is the age of C ? Since the time, it was developed almost 30 years ago; C has been in use, without its importance being marginalized. Over a period of time a huge amount of source code has been developed and been made available, and therefore, there is a lot of C to be leant and to be used.

Why C is Well-researched and studied ? One of the best things about C is the amount of study, in-depth analysis, and research that has gone into it. This has meant that almost all issues concerned with C have been clearly understood and elucidated. There are a whole lot of tutorials that will help you learn the language, as well as solve, any kind of problems that might arise. You also get the help of a huge amount of expertise, insights, and opinions on the language that has been a result of years of development, study, and use.

Is C great for putting ideas into practice ? C is inherently easy to understand. Moreover, if you want to express some common ideas in programming, and in a way in which people are comfortable with, then using C is the best way you can accomplish this. You could call it the lingua franca, when it comes to programming. It can be adapted to suit the requirements of any development, and its current use and the languages used to program the UNIX system, illustrates this fact with aplomb.

C is Closer to the Machine When you are working with C, you are working with various aspects like individual bits, pointers, and bytes. This will allow you to understand the various optimization techniques for the computer system. It's always good to know, what is happening with regards to the components of the system that you are using. While working with higher level languages this is extremely useful, if something does not work or is slower than you thought it would be.

Data types:Primary data type, Integer Type, Floating Point Types, Void type, Character Type, Size and Range of Data Types on 16 bit machine, derived data type, Declaration of Variables, User defined type declaration, Declaration of Storage Class, auto, static, extern, and register, Defining Symbolic Constants, Declaring Variable as Constant and Volatile Variable C language data types can be classified as Primary data type Derived data type User-defined data type

Primary data type All C Compilers accept the following fundamental data types

1.

Integer

int

2.

Character

char

3.

Floating Point

float

4.

Double precision floating point

double

5.

Void

void

The size and range of each data type is given in the table below

DATA TYPE

RANGE OF VALUES

char

-128 to 127

Int

-32768 to +32767

float

3.4 e-38 to 3.4 e+38

double

1.7 e-308 to 1.7 e+308

Integer Type :

Integers are whole numbers with a machine dependent range of values. A good programming language as to support the programmer by giving a control on a range of numbers and storage space. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. A short int requires half the space than normal integer values. Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The long and unsigned integers are used to declare a longer range of values. Floating Point Types : Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space. Void Type : Using void data type, we can specify the type of a function. It is a good practice to avoid functions that does not return any values to the calling function. Character Type : A single character can be defined as a defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from 128 to 127. Size and Range of Data Types on 16 bit machine.

TYPE

SIZE (Bits)

Range

Char or Signed Char

-128 to 127

Unsigned Char

0 to 255

Int or Signed int

16

-32768 to 32767

Unsigned int

16

0 to 65535

Short int or Signed short int

-128 to 127

Unsigned short int

0 to 255

Long int or signed long int

32

-2147483648 to 2147483647

Unsigned long int

32

0 to 4294967295

Float

32

3.4 e-38 to 3.4 e+38

Double

64

1.7e-308 to 1.7e+308

Long Double

80

3.4 e-4932 to 3.4 e+4932

Non-Primitive Data Type:A non-primitive data type is am abstract data type that is built out of primitive data types linked list, queue, stack, etc. Declaration of Variables Every variable used in the program should be declared to the compiler. The declaration does two things. 1. Tells the compiler the variables name. 2. Specifies what type of data the variable will hold. Example: Int sum; Int number, salary; Double average

Datatype

Keyword Equivalent

Character

char

Unsigned Character

unsigned char

Signed Character

signed char

Signed Integer

signed int (or) int

Signed Short Integer

signed short int (or) short int (or) short

Signed Long Integer

signed long int (or) long int (or) long

UnSigned Integer

unsigned int (or) unsigned

UnSigned Short Integer

unsigned short int (or) unsigned short

UnSigned Long Integer

unsigned long int (or) unsigned long

Floating Point

float

Double Precision Floating Point

double

Extended Double Precision Floating Point

long double

User defined type declaration:In C language a user can define an identifier that represents an existing data type. The user defined datatype identifier can later be used to declare variables. The general syntax is typedef type identifier;> here type represents existing data type and identifier refers to the row name given to the data type. Example: typedef int salary; typedef float average; Here salary symbolizes int and average symbolizes float. They can be later used to declare variables as follows: Units dept1, dept2; Average section1, section2; Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2 are indirectly float data type. The second type of user defined datatype is enumerated data type which is defined as follows. Enum identifier {value1, value2 . Value n}; The identifier is a user defined enumerated datatype which can be used to declare variables that have one of the values enclosed within the braces. After the definition we can declare variables to be of this new type as below. enum identifier V1, V2, V3, Vn The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 .. value n Example: enum day {Monday, Tuesday, . Sunday}; enum day week_st, week end; week_st = Monday; week_end = Friday; if(wk_st == Tuesday) week_en = Saturday;

Declaration of Storage Class:Variables in C have not only the data type but also storage class that provides information about their location and visibility. The storage class divides the portion of the program within which the variables are recognized. auto :Auto is the default storage class. It is a local variable known only to the function in which it is declared. static : Local variable which exists and retains its value even after the control is transferred to the calling function. extern : Global variable known to all functions in the file register : Social variables which are stored in the register. Defining Symbolic Constants:A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value. The general form of a symbolic constant is # define symbolic_name value of constant Valid examples of constant definitions are : # define marks 100 # define total 50 # define pi 3.14159 These values may appear anywhere in the program, but must come before it is referenced in the program. It is a standard practice to place them at the beginning of the program. Declaring Variable as Constant:The values of some variable may be required to remain constant through-out the program. We can do this by using the qualifier const at the time of initialization. Example: Const int class_size = 40; The const data type qualifier tells the compiler that the value of the int variable class _size may not be modified in the program.

Format Specifiers in C:-

%c %d %i %f %e %E %g %G %o %s %u %x %X %p %n %%

The character format specifier. The integer format specifier. The integer format specifier (same as %d). The floating-point format specifier. The scientific notation format specifier. The scientific notation format specifier. Uses %f or %e, whichever result is shorter. Uses %f or %E, whichever result is shorter. The unsigned octal format specifier. The string format specifier. The unsigned integer format specifier. The unsigned hexadecimal format specifier. The unsigned hexadecimal format specifier. Displays the corresponding argument that is a pointer. Records the number of characters written so far. Outputs a percent sign.

Getting Started With C:Now we are going to starts with C language ----1. The Character Set Of C:- Character set can be of Alphabets, Digits or special symbols. It can be A,B,C.Z, a,b,cz, 1,29, !,@,#,$ and so on. 2. Constants, Variables and Keywords:- Alphabets, Digits and Special Symbols creates Constants, Variables and keywords. Constants:A constants is an entity that does not change. Whatever we calculated, it stores in memory. Computer memory has millions of cells also known as memory Locations. If the memory location has a value it does not change called constant. Types Of Constants:There are two types of constants

1. Primary Constants:-

2. Secondary Constants:-

Variables:The Name which are given to the memory locations called Variables. These memory location contains constants (Integer, Real and Character). Types of variables depend on types of variables that it can handle. Particular type of variable can hold only the same type of constants. For Examples:- A integer type of variable can hold integer constant. Rules for constructing a variable name:1. The first character in the variable name must be an alphabet or underscore. 2. There should be no commas or blank spaces within variable name. 3. There should not be any special symbol within a variable name except a underscore. 4. Variable name should be 31 characters long. 5. variable name should be meaningful so that user can understand. Variable type The Programming language C has two main variable types 1. Local Variables 2.Global Variables 1. Local Variables Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initialized by the system, you must initialize it yourself. When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

2.

Global Variables Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initialized automatically by the system when you define them!

Data Type int char float pointer

Initialser 0 '\0' 0 NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name. Identifiers:Identifiers are names which are given to elements of a program such as variables , arrays & functions. Basically identifiers are the group of alphabets or digits. Rules for making identifier name 1. the first character of an identifiers must be analphabet or an underscore 2. all characters must be letters or digits. 3.There is no special characters are allowed except the underscore"_". 4. There is no two underscores are allowed. 5. don't use keywords as identifiers.

C Keywords:1. Keywords are the words whose meanings are already exist in the compiler. 2. Keywords can not be use as variable names. 3. Keywords are also called Reserved words. 4. There are only 32 keywords available in C. auto, double, int, struct, break, else, long, switch, case, enum, register, typedef, char, extern, return, union, const, float, short, unsigned, continue, for, signed, void, default, goto, sizeof, volatile, do, if, static, while

Definitions v/s Declaration in C A declaration is when you declare a new variable of some specific type. A definition is when you define a new name for some particular value or type. /* * A function is only defined if its body is given * so this is a declaration but not a definition */ int func_dec(void); /* * Because this function has a body, it is also * a definition. * Any variables declared inside will be definitions, * unless the keyword 'extern' is used. * Don't use 'extern' until you understand it! */ int def_func(void){ float f_var; /* a definition */ int counter; /* another definition */ int rand_num(void); /* declare (but not define) another function */ return(0); } How to write a first C program:Rules:1. In C program each instruction written as a separate statement. 2. The statement of a program must be in the sequence by which we want to execute. 3. Blank space are not allowed in the variable name but you can use blank spaces between two words which increase readability. 4. Statements should be in small case letters. 5. Every statement ends with a semicolon (;). 6. Semicolon is called statement terminator. 7. You can put the comment within a program by using /* .*/. 8. Comments are not necessary to use in a program but it is a good habit to use comments in a program. Compilation and Execution of a C Program:-

1. Write a program using editor. 2. Save the file with .c extension. 3. To compile the program you can select compile from compile menu and press enter
or you can press Alt+f9

4. It will check the errors if program has any error it will terminate the program then
you can find out he error and you can correct it. After correcting the error you can compile the program again. After compiling successfully it will create a object (.obj) file.

5. Once the source program has been converted into an object file, it is still not in the
form that you can run. The reason behind this is that there may be some references to standard library functions or user-defined functions in other object files, which are compiled separately. Therefore these object files are to be linked together along with standard library functions that are contained in library files. To link our object file, select Link from the Compile menu. After this the .OBJ file will be compiled with the one or more library files. The result of this linking process produces an executable file with .EXE extension. Figure-4 depicts this linking process.

6. .exe file is a stand alone executable file. which can direct execute from command prompt 7. After pressing Alt+f9 it will complete the whole process creating .OBJ and .EXE.

8. To display the output of the program press Alt+f5.

Examples of a simple C program:/* Calculation of simple interest */ main( ) { int p, n ; float r, si ; p = 1000 ; n=3; r = 8.5 ; /* formula for simple interest */ si = p * n * r / 100 ; printf ( "%f" , si ) ; } main():1. main() is a function which is entry point of any program. 2. main() is collective name which is given to a set of statements. 3. This name has to be main(). It can not be change. 4. Statements within a main() should be enclosed within a pair of { }. 5. main() { statement 1; statement 2; } 6. Every function used in a program must be declared. Difference between main() and other functions:1. parameters to main() are passed from command line, 2. main() is the only function declared by the compiler and defined by the user, 3. main() is by convention a unique external function, 4. main() is the only function with implicit return 0; at the end of main(). When control crosses the ending } for main it returns control to the operating system by returning 0 to it (if there is no explicit return statement with a return value). The OS normally treats return 0 as the successful termination of the program. 5. return type for main() is always is an int, (some compilers may accept void main() or any other return type, but they are actually treated as if it is declared as int main(). It makes the code non-portable. Always use int main() ). Example:main() { Int i; Static int j; }

NOTES:1. Parameters are passed from command line to main (). 2. It is the only function declares by the compiler and defines by the user. 3. Return type for main() is always is an int, (some compilers may accept void main() or any other return type, but they are actually treated as if it is declared as int main(). It makes the code non-portable. Always use int main() ).

Receiving Input:To receive the input from user we use scanf() function in C Language. scanf() is a function that reads data with specified format and is present in many other programming languages. int scanf(const char *format, ...); "scanf" stands for "scan format", because it scans the input for valid tokens and parses them according to a specified format.

#include <stdio.h> int main(void) { int n; while (scanf("%d", &n) == 1) printf("%d\n", n); return 0; } Types of Instructions in 'C' Language:There are basically three types of instructions in C: (a). Type Declaration Instruction (b). Arithmetic Instruction (c). Control Instruction The purpose of each of these instructions is given below: (a). Type Declaration Instruction: To declare the type of variables . (b). Arithmetic instruction: To perform arithmetic operations between constants and variables. (c). Control instruction: To control the sequence of execution of various statements.

1. An arithmetic operation between integer and integer is always integer. 2. An operation between real and real is always real. 3. An operation between integer and real is always real.Type Conversion in Assignments

the type of the expression and the type of the variable on the left-hand side of the assignment operator will not be same. In such a case the value of the expression is promoted or demoted depending on the type of the variable on left-hand side of equal(=). For example, consider the following assignment statements. int i ; float b ; i = 6.3 ; b = 60 ; in the example above i is type of integer and b is float type but the value assigned is opposite to each other. i is having 6.3 which is float and after assigning this value, it will contain only 6 rest of .3 is demoted. and variable b is having 60 which is integer type and it assign 60.000000, promoted the value. arithmetic operations are performed in an arithmetic expression is called as Hierarchy of operations. and if a=4,b=7,c=3 then using the same expression we will obtain two different answers as z=5.6 or z=7. To avoid this condition we must be aware of hierarchy of operations. In arithmetic expressions scanning is always done from left to right. The priority of operations is as shown below, Priority Operators First Third Fourth Parentheses or brackets() Addition & Subtraction Assignment i.e.= Second Multiplication & Division

If we consider the logical operators used in C language, the operator precedence will be like; Operators Type ! */% +Logical NOT Arithmetic and modulus Arithmetic Relational

== != && || =

Relational Logical AND Logical OR Assignment

In the tables above, the higher the position of an operator, higher is its priority. Control Instructions in C The Control Instructions enable us to specify the order in which instructions in a program are to be executed. or the control instructions determine the flow of control in a program. There are four types of control instructions in C. (a) Sequence Control Instruction The Sequence control instruction ensures that the instructions are executed in the same order in which they appear in the program. (b) Selection or Decision Control Instruction Decision instructions allow the computer to take a decision as to which instruction is to be executed next. (c) Repetition or Loop Control Instruction The Loop control instruction helps computer to execute a group of statements repeatedly. (d) Case Control Instruction same as decision control instruction. Control Statement:There are 3 types of control statement:1. If Statement 2. If-else Statement 3. The Conditional Operators If Condition:if (condition is true) execute the statement; The if condition tells the compiler that the condition is true, execute the statement. Condition of if is always within the pair of parentheses. If condition is true the statement will execute and condition is false, the statement will not execute. For checking condition is true or false we use the relational

operators. Relational Operators:-

The Expression x==y

Is True If x is equal to y x is not equal to y x is less than y x is greater than y x is less than or equal to y x is greater than or equal to y

x!=y x<y

x>y

x<=y

x>=y

Example:main( ) { int num ; printf ( "Enter a number less than 10 " ) ; scanf ( "%d", &num ) ; if ( num <= 10 ) printf ( "What an obedient servant you are !" ) ; } Multiple statements within if:We can execute more than one statements for that if condition should be satisfied. If-Else Statement:We can use If Else condition when we have more than one conditions. If block checks the condition 1 is true it will execute other else block condition will be executed. Or You can say we can execute group of statements by the If else condition.

Example:/* Calculation of gross salary */ main( ) { float bs, gs, da, hra ; printf ( "Enter basic salary " ) ; scanf ( "%f", &bs ) ; if ( bs < 1500 ) { hra = bs * 10 / 100 ; da = bs * 90 / 100 ; } else { hra = 500 ; da = bs * 98 / 100 ; } gs = bs + hra + da ; printf ( "gross salary = Rs. %f", gs ) ; } Nested If else:We can use several If else condition within if block or else block. This is called nested if else condition. Example:/* program of nested if-else */ main( ) { int i ; printf ( "Enter either 1 or 2 " ) ; scanf ( "%d", &i ) ; if ( i == 1 ) printf ( "You would go to heaven !" ) ; else { if ( i == 2 ) printf ( "Hell was created with you in mind" ) ; else printf ( "How about mother earth !" ) ; } } Logical operators:There are only three logical operator in C. 1. && AND 2. || OR 3. ! NOT The first two operator allows two or more conditions to be combined in an if statement. Example:-

main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ; } Loops:Loops are required to perform the same series of actions. We frequently need to perform an action over and over. Ability to perform a set of instructions repeatedly called loops. There are three types of loops:1. for 2. while 3. do while

1. for loop:for (initialization_expression; loop_condition; increment_expression){ // statements There are three parts which is separated by semi-colons in control block of the for loop. initialization_expression is executed before execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations. You can initialize a counter for the loop in this part. The execution of the loop continues until the loop_condition is false. This expression is checked at the beginning of each loop iteration. The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.

Here is an example of using for loop statement to print an integer five times

#include <stdio.h> void main(){ // using for loop statement int max = 5; int i = 0; for(i = 0; i < max;i++){ printf("%d\n",i); } } 2. While Loop:A loop statement allows you to execute a statement or block of statements repeatedly. First it check the condition then execute it. If condition is true it execute otherwise dont execute the statement. Here is syntax of while loop statement: while (expression) { // statements } Here is a while loop statement demonstration program: #include <stdio.h> void main(){ int x = 10; int i = 0; // using while loop statement while(i < x){ i++; printf("%d\n",i); } // when number 5 found, escape loop body int numberFound= 5; int j = 1; while(j < x){ if(j == numberFound){ printf("number found\n"); break; } printf("%d...keep finding\n",j); j++; } } Do While Loop:do while loop statement allows you to execute code block in loop body at least once. Here is do while loop syntax: do { // statements } while (expression); Here is an example of using do while loop statement:

#include <stdio.h> void main(){ int x = 5; int i = 0; // using do while loop statement do{ i++; printf("%d\n",i); }while(i < x); } The Odd Loop Odd loop executed the statements within them a finite number of times. it execute the statements finite times in the loop. /* Execution of a loop an unknown number of times */ main( ) { char another ; int num ; do { printf ( "Enter a number " ) ; scanf ( "%d", &num ) ; printf ( "square of %d is %d", num, num * num ) ; printf ( "\nWant to enter another number y/n " ) ; scanf ( " %c", &another ) ; } while ( another == 'y' ) ; } Bitwise operations

& &= | |= ^ ^= ~ << <<

AND AND OR OR XOR XOR one's compliment Shift Left Shift Left

>>= Shift Right >>= Shift Right

AND OR and XOR These require two operands and will perform bit comparisons. AND & will copy a bit to the result if it exists in both operands. main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a & b; /* 12 = 0000 1100 */ } OR | will copy a bit if it exists in either operand. main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a | b; } XOR ^ copies the bit if it is set in one operand (but not both). main() { unsigned int a = 60; /* 60 = 0011 1100 */ unsigned int b = 13; /* 13 = 0000 1101 */ unsigned int c = 0; c = a ^ b; } Ones Complement This operator is unary (requires one operand) and has the effect of 'flipping' bits. main() { unsigned int Value = 4; Value = ~ Value; } Bit shift. The following operators can be used for shifting bits left or right. /* 49 = 0011 0001 */ /* 61 = 0011 1101 */

/* 4 = 0000 0100 */

/* 251 = 1111 1011 */

<<,>>,<<=,>>= The left operands value is moved left or right by the number of bits specified by the right operand. For example: main() { unsigned int Value=4; unsigned int Shift=2; Value = Value << Shift; Value <<= Shift;

/* 4 = 0000 0100 */

/* 16 = 0001 0000 */ /* 64 = 0100 0000 */

printf("%d\n", Value); /* Prints 64 */ } Assignment Operators:The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. Example x=a+b Here the value of a + b is evaluated and substituted to the variable x. In addition, C has a set of shorthand assignment operators of the form. var oper = exp; Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator. Logical operators:There are only three logical operator in C. 1. && AND 2. || OR 3. ! NOT The first two operator allows two or more conditions to be combined in an if statement. Example:main( ) { int m1, m2, m3, m4, m5, per ; printf ( "Enter marks in five subjects " ) ; scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ; if ( per >= 60 ) printf ( "First division" ) ; if ( ( per >= 50 ) && ( per < 60 ) ) printf ( "Second division" ) ; if ( ( per >= 40 ) && ( per < 50 ) ) printf ( "Third division" ) ; if ( per < 40 ) printf ( "Fail" ) ;

} Break Statement:break statement is used to break any type of loop such as while, do while and for loop. break statement terminates the loop body immediately. Example:#include <stdio.h> #define SIZE 10 void main(){ // demonstration of using break statement int items[SIZE] = {1,3,2,4,5,6,9,7,10,0}; int number_found = 4,i; for(i = 0; i < SIZE;i++){ if(items[i] == number_found){ printf("number found at position %d\n",i); break;// break the loop } printf("finding at position %d\n",i); } Continue Statement:continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions. Example continues:// demonstration of using continue statement for(i = 0; i < SIZE;i++){ if(items[i] != number_found){ printf("finding at position %d\n",i); continue;// break current iteration } // print number found and break the loop printf("number found at position %d\n",i); break; } }

Switch Statement:The switch statement allows you to select from multiple choices based on a set of fixed values for a given expression. break keyword is used to signal the end of the block. Here are the common switch statement syntax:

switch (expression){ case value1: /* execute unit of code 1 */ break; case value2: /* execute unit of code 2 */ break;

default: /* execute default action */ break; } Here is an example of using C switch statement #include <stdio.h> const int RED = 1; const int GREEN = 2; const int BLUE = 3; void main(){ int color = 1; printf("Enter an integer to choose a color(red=1,green=2,blue=3):\n"); scanf("%d",&color); switch(color){ case RED: printf("you chose red color\n"); break; case GREEN:printf("you chose green color\n"); break; case BLUE:printf("you chose blue color\n"); break; default:printf("you did not choose any color\n"); } }
Goto statement:The goto statement is use for a jump from one point to another point within a function.

Example:#include <stdio.h> #include <conio.h> int main() { int n = 0; loop: ; printf("\n%d", n); n++; if (n<10) { goto loop; } getch(); return 0; }

Functions:A function is a block of code that performs a particular task. It has a name and it is reusable and it can be executed from as many different parts in a C Program as required. It also optionally returns a value to the calling program So function in a C program has some properties discussed below. Every function has a unique name. This name is used to call function from main() function. A function can be called from within another function. A function is independent and it can perform its task without intervention from or interfering with other parts of the program. A function performs a specific task. A task is a distinct job that your program must perform as a part of its overall operation, such as adding two or more integer, sorting an array into numerical order, or calculating a cube root etc. A function returns a value to the calling program. This is optional and depends upon the task your function is going to accomplish. Suppose you want to just show few lines through function then it is not necessary to return a value. But if you are calculating area of rectangle and wanted to use result somewhere in program then you have to send back (return) value to the calling function. C language is collection of various inbuilt functions. If you have written a program in C then it is evident that you have used Cs inbuilt functions. Printf, scanf, clrscr etc. all are Cs inbuilt functions. You cannot imagine a C program without function.

Example:int sum (int x, int y) { int result; result = x + y; return (result); } Types of functions: A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. 4. Functions that return multiple values. 5. Functions with no arguments and return values. #include<stdio.h> #include<conio.h> void add(int x,int y) { int result; result = x+y; printf("Sum of %d and %d is %d.\n\n",x,y,result); } void main() { clrscr(); add(10,15); add(55,64);

add(168,325); getch(); } Call by value and Call by reference:The argument passed to a function can be of two types:1. value passed (call by value) 2. address passed (call by reference) Let's say we have an integer variable named x. A call to a function by value using x means (a copy of) the value that x stores is passed in the function call and no matter what the function does with that value, the value stored in x remains unchanged. A call to a function by reference using x means a reference (also called a pointer or alias) to the variable x is passed in the function call and so any changes the function makes using this reference will actually change the value stored in x. Pointer:In c a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer. Pointer declaration: A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable. Finally you give the name of the variable. type * variable name Example: int *ptr; float *string; Address operator: Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address of the variable you want to point as in the following example: ptr=&num; This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260. /* A program to illustrate pointer declaration*/ main() { int *ptr;

int sum; sum=45; ptr= printf (\n Sum is %d\n, sum); printf (\n The sum pointer is %d, ptr); } /* Program to display the contents of the variable their address using pointer variable*/ #include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=a; intptr=&x; cptr=&ch; floptr=&x; printf(Num %d stored at address %u\n,*intptr,intptr); printf(Value %f stored at address %u\n,*floptr,floptr); printf(Character %c stored at address %u\n,*cptr,cptr); } Pointer expressions & pointer arithmetic: Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the /* Program to display the contents of the variable their address using pointer variable*/ include< stdio.h > { int num, *intptr; float x, *floptr; char ch, *cptr; num=123; x=12.34; ch=a; intptr=&x; cptr=&ch; floptr=&x; printf(Num %d stored at address %u\n,*intptr,intptr); printf(Value %f stored at address %u\n,*floptr,floptr); printf(Character %c stored at address %u\n,*cptr,cptr); } /*Pointer expression and pointer arithmetic*/ #include< stdio.h > main() {

int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; printf(\nAddress of a +%u,ptr1); printf(\nAddress of b %u,ptr2); printf(\na=%d, b=%d,a,b); printf(\nx=%d,y=%d,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(\na=%d, b=%d,a,b); } Pointers and function: The pointer are very much used in a function declaration. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function definition may be classified into two groups. 1. Call by reference 2. Call by value. Call by value: We have seen that a function is invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored. The formal parameters picks up its value from storage area the mechanism of data transfer between actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of corresponding actual parameter becomes the initial value of formal parameter. The value of formal parameter may be changed in the body of the actual parameter. The value of formal parameter may be changed in the body of the subprogram by assignment or input statements. This will not change the value of actual parameters. #include< stdio.h > void main() { int x,y; x=20; y=30; printf(\n Value of a and b before function call =%d %d,a,b); fncn(x,y); printf(\n Value of a and b after function call =%d %d,a,b); } fncn(p,q) int p,q; { p=p+p; q=q+q; } Call by Reference:

When we pass address to a function the parameters receiving the address should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call. /* example of call by reference*/ #include< stdio.h > void main() { int x,y; x=20; y=30; printf(\n Value of a and b before function call =%d %d,a,b); fncn(&x,&y); printf(\n Value of a and b after function call =%d %d,a,b); } fncn(p,q) int p,q; { *p=*p+*p; *q=*q+*q; } Pointer to arrays: An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator. /* A program to display the contents of array using pointer*/ main() { int a[100]; int i,j,n; printf("\nEnter the elements of the array\n"); scanf(%d,&n); printf("Enter the array elements"); for(I=0;I< n;I++) scanf(%d,&a[I]); printf("Array element are"); for(ptr=a,ptr< (a+n);ptr++) printf("Value of a[%d]=%d stored at address %u",j+=,*ptr,ptr); } Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.

Pointers and structures: We know the name of an array stands for the address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of struct type. Consider the following declaration: struct products { char name[30]; int manufac; float net; item[2],*ptr; This statement declares item as array of two elements, each type struct products and ptr as a pointer data objects of type struct products, the assignment ptr=item; would assign the address of zeroth element to product[0]. Its members can be accessed by using the following notation. ptr- >name; ptr- >manufac; ptr- >net; The symbol - > is called arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing product[0]. When the pointer is incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array. for(ptr=item; ptr< item+2;ptr++) printf("%s%d%f\n",ptr- >name,ptr- >manufac,ptr- >net); We could also use the notation (*ptr).number to access the member number. The parenthesis around ptr are necessary because the member operator . Has a higher precedence than the operator *.

Pointers on pointer: While pointers provide enormous power and flexibility to the programmers, they may use cause manufactures if it not properly handled. Consider the following precautions using pointers to prevent errors. We should make sure that we know where each pointer is pointing in a program. Here are some general observations and common errors that might be useful to remember. A pointer contains garbage until it is initialized. Since compilers cannot detect un initialized or wrongly initialized pointers, the errors may not be known until we execute the program remember that even if we are able to locate a wrong result, it may not provide any evidence for us to suspect problems in the pointers.
main()

{ unsigned int a = 60; unsigned int b = 13; unsigned int c = 0; c = a & b; */ }

/* 60 = 0011 1100 */ /* 13 = 0000 1101 */

/* 12 = 0000 1100

Anda mungkin juga menyukai