c programming language

81
C PROGRAMMING LANGUAGE BLOCK DIAGRAM DATA TYPES VARIABLES OPERATORS CONDITIONALS LOOPING

Upload: prasanya-k

Post on 12-Apr-2017

603 views

Category:

Documents


0 download

TRANSCRIPT

C PROGRAMMING LANGUAGE

C PROGRAMMING LANGUAGEBLOCK DIAGRAMDATA TYPESVARIABLESOPERATORSCONDITIONALSLOOPING

BLOCK DIAGRAM

DATA TYPES Data Types can also be classified as shown in the image below Primitive, Derived and User Defined.

DATA TYPES1.Primitive Data Types Fundamental data types are further categorized into 3 types. Let us discuss each of this type briefly.Int (Integer)Integer data type is used to store numeric values without any decimal point e.g. 7, -101, 107, etc. A variable declared as 'int' must contain whole numbers e.g. age is always in number.Syntax:int variable name;E.g. int roll, marks, age;FloatFloat data type is used to store numeric values with decimal point. In other words, float data type is used to store real values, e.g. 3.14, 7.67 etc. A variable declared as float must contain decimal values e.g. percentage, price, pi, area etc. may contain real values.

DATA TYPESSyntax:Float variable name;E.g. float per, area;

Char (Character)Char (Character) data type is used to store single character, within single quotes e.g. 'a', 'z','e' etc. A variable declared as 'char' can store only single character e.g. Yes or No Choice requires only 'y' or 'n' as an answer.Syntax:Char variable name;E.g. Char chi='a', cha;

DATA TYPESVoidVoid data type is used to represent an empty value. It is used as a return type if a function does not return any value.Type modifierType modifier is used to change the meaning of basic or fundamental data types so that they can be used in different situations. Various type modifiers are- signed, unsigned, short and long.C language offers 3 different 'int' type modifiers - short, int, and long that represents three different integer sizes. C language also offers 3 different floating point type modifiers - float, double, and long double. Two special 'char' type modifiers are- signed, unsigned.C language offers 3 different 'int' type modifiers - short, int, and long that represents three different integer sizes.

DATA TYPESC language also offers 3 different floating point type modifiers - float, double, and long double. Two special 'char' type modifiers are- signed, unsigned.

Type Size (in bytes) RangeInt (signed/ short) 2 -32768 to 32767Int (unsigned) 2 0 to 65535 Long (signed) 4 -2,147,483,648 to 2,147,483,648Long (unsigned) 4 0 to 4,294,467,295 Float 4 3.4*10-34 to 3.4*10-34 Double (long float) 8 1.7*10-308 to 1.7*10-308 -1 Long double 10 3.4*10-4932 to 3.4*10-4932 -1 Char 1 -128 to 127 Signed char 1 0 to 255 Unsigned char 1 -128 to 127

DATA TYPES2. Derived Data TypesData types that are derived from fundamental data types are called derived data types. Derived data types don't create a new data type; instead, they add some functionality to the basic data types. Two derived data type are - Array & Pointer.ArrayAn array is a collection of variables of same type i.e. collection of homogeneous data referred by a common name. In memory, array elements are stored in a continuous location.Syntax:[];E.g. int a[10]; Char chi [20];

DATATYPESAccording to the rules of C language, 1st element of array is stored at location a[0] , 2nd at a[1] & so on.PointerA pointer is a special variable that holds a memory address (location in memory) of another variable.Syntax:*Data type is the type whose address we want to store in the pointer variable. * is a pointer variable. 'var name' is the name where the variable is to be stored.E.g. if we want to store the address of an 'int' data type variable into a pointer variable, it is done in the following manner:

DATA TYPESint a,*b; b=&a;In the above case, variable 'b' stores the address of variable 'a'.3. User Defined Data TypeUser defined data type is used to create new data types. The new data types formed are fundamental data types. Different user defined data types are: struct, union, enum, typedef.StructA struct is a user defined data type that stores multiple values of same or different data types under a single name. In memory, the entire structure variable is stored in sequence.

DATA TYPESSyntax:Struct < structure name> { Var1; Var2; ----- ----- };Structure name is the name of structure that we have to give e.g. if we want to store details of a student as- name, roll, marks then in structure it will be declared in the following manner:

DATA TYPESStruct student { Char name [20]; Int roll, Float marks; };Now, its variable is declared as: structE.g. Struct student s1;And its variable is accessed using dot (.) operator.S1.roll, s1.name, s1.marksUnionA union is a user defined data type that stores multiple values of same or different data types under a single name. In memory, union variables are stored in a common memory location.

DATA TYPESSyntax:Union < tag name> { Var1; Var2; ----- ---- };Tag name is the name of union, e.g. if we want to store details of a student as- name, roll, marks then it will be done in the following manner :

DATA TYPESUnion student { Char name [20]; Int roll, Float marks; }; Now, the variable is declared as follows:structe.g. Union student s1;And its variable is accessed by using dot (.) operator.S1.roll, s1.name, s1.marksThe only difference between Union and Struct is allocation of memory. 'Union' is assigned a memory size equal to the biggest data type used in union declaration whereas 'struct' will occupy the size equal to the sum of all variables sizes.

DATA TYPESEnum:An enumeration is a data type similar to a struct or a union. Its members are constants that are written as variables, though they have signed integer values. These constant represent values that can be assigned to corresponding enumeration variables.Syntax:Enum {value1, value2, _ _ _ _ _ _, value n};Enum is the required keyword; Tag is the name that identifies enumerations having this composition; Value1, value2, - - - - - - , value n represents the individual identifiers that may be assigned to a variable of this type.E.g. : Enum colors {black, blue, cyan, green, red, yellow}; Color foreground, background;

DATA TYPESFirst line defines enum and second one defines enum variables. Thus, variables foreground and background can be assigned any one of constant black, blue, - - - - ,yellow.In declaration black is assigned 0 value, and blue 1, - - - -, and yellow 5. We can also assign the value accordingly as we want to assign, like:Enum colors {black, blue, cyan=4, green, red, yellow} Here black=0, blue=1, cyan=4, green=5, red=6, yellow=7

Typedef:The 'typedef' allows the user to define new data-types that are equivalent to existing data types. Once a user defined data type has been established, then new variables, array, structures, etc. can be declared in terms of this new data type.

DATA TYPESA new data type is defined as:Typedef type new-type;Type refers to an existing data type, New-type refers to the new user-defined data type.E.g. : typedef int numberNow we can declare integer variables as:number roll, age, marks;It is equivalent to:int roll, age, marks;

VARIABLESA variable can be defined in many ways. At the basic level, a variable can be defined as a memory location declared to store any kind of data (which may change many times during program execution). It can also be defined as any quantity/entity which may vary during program execution. To identify a variable (the declared memory location), it can be assigned a name known as variable name. The name given to a variable is known as an identifier. An identifier can be a combination of alphabets , digits and underscore. There are certain set of rules which must be observed while naming a variable.Rules for naming a variable:-A variable name (identifier) can be any combination of alphabets, digits and underscore.

VARIABLESFirst character should be a letter (alphabet).Length of variable name can range from 1 to 8. (Note: Different compilers may allow different ranges, say upto 31. But it is a good practice to keep the variable name short.)A space in between is not allowed. Ex: A variable name can not be declared as var nameUnderscore can be used to concatenate name combinations. Ex: var_name , var_123 are valid identifiers.No commas or other special characters (other than underscore _ ) are allowed in a variable name.C is a case sensitive language which means a variable name declared as flag is not same as FLAG. They both will be treated as different variables.There are certain reserved words in C language, known as keywords.

VARIABLESWords similar to a keyword can not be used as a variable name. Ex:- In the previous article on data types, we saw int, char, float etc. These are actually keywords. So you cant declare a variable with names int, char or float.Variable DeclarationA variable must be declared first before we can use it in a program for manipulations. A variable is declared with its storage class, data type and identifier. The format is shown below:-Storage-class Data-Type Variable-name;

VARIABLESStorage class is some thing we will learn in coming chapters. Let me brief it. There are 4 storage classes namely Automatic, Static, External and Register storage classes. Each of them has its own meaning and usage. Storage class is used to attribute certain features to a variable like its scope (local or global), where to store the variable (in memory or in register), the life time of a variable etc. It is not necessary to specify a storage class while declaring a variable. By default all variable declarations (without any storage class specified) will be assigned to automatic storage class. We will discuss more about storage class in another chapter.So our variable declaration would be like:-Data-Type Variable-name;

VARIABLESExamples:-int a;int count;char name;Two or more variables of the same data type can be declared in a single line, separating each variable names with a comma and ending the line with a semicolon.Examples:-int n,count,flag,i,j;char name,address,nick_nm;Initial values can be assigned to variables while declaring it.Examples:-int a,num,count=0,flag=10,mark=100;

VARIABLESchar name=Robert,sur_nam=Nero,mid_nam=de;Let us examine what happens when we declare a variable.int j=10;Here we have declared a variable of data type integer with name as j and initial value as 10. This declaration tells the C compiler to:-Reserve space in memory to hold the integer value.Assign the name j to that reserved memory space.Store the value 10 in this memory location.

OPERATORSThe symbols which are used to perform logical and mathematical operations are called C operators.These C operators join individual constants and variables to form expressions. Operators, functions, constants and variables are combined together to form expressions.Example : A + B * 5where,+, * - operatorsA, B - variables5 constantA + B * 5 - expression

OPERATORSTypes of C operators:C language offers many types of operators. They are,Arithmetic operatorsAssignment operatorsRelational operatorsLogical operatorsBit wise operatorsConditional operators (ternary operators)Increment/decrement operatorsSpecial operators

OPERATORS1. Arithmetic Operators: These operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus.

S.noOperatorOperation1+Addition2-Subtraction3*Multiplication4/Division5%Modulus

OPERATORSExample program for C arithmetic operators:# include int main(){ int a=40,b=20, add,sub,mul,div,mod; add = a+b; sub = a-b; mul = a*b; div = a/b; mod = a%b; printf("Addition of a, b is : %d\n", add); printf("Subtraction of a, b is : %d\n", sub); printf("Multiplication of a, b is : %d\n", mul); printf("Division of a, b is : %d\n", div);

OPERATORS printf("Modulus of a, b is : %d\n", mod); }Output:Addition of a, b is : 60Subtraction of a, b is : 20Multiplication of a, b is : 800Division of a, b is : 2Modulus of a, b is : 02. Assignment operators: The values for the variables are assigned using assignment operators.For example, if the value 10 is to be assigned for the variable sum, it can be done like below. sum = 10;

OPERATORSBelow are some of other assignment operators:

OperatorExampleExplanationSimple operator=sum = 10Value 10 is assigned to variable sumCompound assignment operator+=sum+=10This is same as sum = sum+10-=sum = 10This is same as sum = sum 10*=sum*=10This is same as sum = sum*10/+sum/=10This is same as sum = sum/10%=sum%=10This is same as sum = sum%10&=sum&=10This is same as sum = sum&10^=sum^=10This is same as sum = sum^10

OPERATORSExample program for assignment operators:# include int main(){int Total=0,i;for(i=0;ix > y=x >= yRight Shift

OPERATORSExample program for bitwise operators:#include int main(){ int m=40,n=20,AND_opr,OR_opr,XOR_opr ;AND_opr = (m&n);OR_opr = (m|n);XOR_opr = (m^n);printf("AND_opr value = %d\n",AND_opr );printf("XOR_opr value = %d\n",XOR_opr );printf("OR_opr value = %d\n",OR_opr );}

OPERATORSOutput:AND_opr value = 0XOR_opr value = 60OR_opr value = 606. Conditional operators: Conditional operators return one value if condition is true and returns other value is condition is false. This operator is also called as ternary operator. Syntax : (Condition? true_value: false_value); Example : (A > 100 ? 0 : 1); Here, if A is greater than 100, 0 is returned else 1 is returned.This is equal to if else conditional statements.

OPERATORSExample program for conditional/ternary operators:#include int main(){int x=1, y ;y = ( x ==1 ? 2 : 0 ) ;printf("x value is %d\n", x);printf("y value is %d", y);}Output:x value is 1y value is 2

OPERATORS7. Increment and decrement operators: These operators are used to either increase or decrease the value of the variable by one. Syntax : ++var_name; (or) var_name++; (or) - var_name; (or) var_name- -; Example : ++i, i++, - -i, i- -

}

OPERATORSExample program for increment operators:#include int main(){int i=1;while(i10){ printf("%d\n",i); i--;}}

OPERATORSOutput: 201918171615141312118. Special Operators:Below are some of special operators that the C language offers.

OPERATORSS.noOperatorsDescription1&This is used to get the address of the variable.Example: &a will give address of a.2*This is used as pointer to a variable.Example: * a where, * is pointer to the variable a.3Size of ()This gives the size of the variable.Example: size of (char) will give us 1.4ternaryThis is ternary operator and act exactly as if else statement.5Type cast Type cast is the concept of modifying variable from one data type to other.

CONDITIONALSConditional statements are used to execute a statement or a group of statement based on certain conditions.We will look into following conditional statements.ifif elseelse ifswitchGoto1) if conditional statement in C :Syntax for if statement in C :if(condition){Valid C Statements;}

CONDITIONALSIf the condition is true the statements inside the parenthesis { }, will be executed, else the control will be transferred to the next statement after if.#include#includevoid main(){int a,b;a=10;b=5;if(a>b){printf("a is greater");}getch();}

CONDITIONALSProgram Algorithm / Explanation :#include header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.#include is used because the C in-built function getch() comes under conio.h header files.main () function is the place where C program execution begins.Two variables a&b of type int is declared.Variable a is assigned a value of 10 and variable b with 5.A if condition is used to check whether a is greater than b. if(a>b)As a is greater than b the printf inside the if { } is executed with a message a is greater.Output :

CONDITIONALS2) if else in C :Syntax for if :if(condition){Valid C Statements;}else{Valid C Statements;}In if else if the condition is true the statements between if and else is executed. If it is false the statement after else is executed.

CONDITIONALSSample Program :if_else.c#include#includevoid main(){int a,b;printf("Enter a value for a:");scanf("%d",&a);printf("\nEnter a value for b:");scanf("%d",&b);

if(a>b){printf("\n a got greater value");}

CONDITIONALSelse{printf("\n b got greater value");}printf("\n Press any key to close the Application"); getch();}Program Algorithm / Explanation :#include header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.#include is used because the C in-built function getch() comes under conio.h header files.main () function is the place where C program execution begins.Two integer variable a and b are declared.

CONDITIONALSUser Input values are received for both a and b using scanf.An if else conditional statement is used to check whether a is greater than b.If a is greater than b, the message a got greater value is displayed using printf.If b is greater the message b got greater value is displayed.Output :

CONDITIONALSelse if in C :Syntax :if(condition){Valid C Statements;}else if(condition 1){Valid C Statements;}--

CONDITIONALSelse if(condition n){Valid C Statements;}else{Valid C Statements;}In else if, if the condition is true the statements between if and else if is executed. If it is false the condition in else if is checked and if it is true it will be executed. If none of the condition is true the statement under else is executed.else_if.c#include #include

CONDITIONALSvoid main(){int a,b;printf("Enter a value for a:");scanf("%d",&a);printf("\nEnter a value for b:");scanf("%d",&b);if(a>b){printf("\n a is greater than b");}else if(b>a){printf("\n b is greater than a");}

CONDITIONALSelse{printf("\n Both a and b are equal");}printf("\n Press any key to close the application");getch();}Program Algorithm / Explanation :#include header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.#include is used because the C in-built function getch comes under conio.h header files.main () function is the place where C program execution begins.

CONDITIONALSTwo variables a & b of type int are declared.Values for a & b are received from user through scanf.if condition is used to check whether a is greater than b. if(a>b)If the condition is true the statement between if and else if is executed.If the condition is not satisfied else if() condition is checked. Else if(b>a)If b is greater than a the statement between else if and else is executed.If both the conditions are false the statement after else is executed.

CONDITIONALSOutput :

CONDITIONALS4) Switch statement in C :Syntax :switch(variable){case 1:Valid C Statements;break;--case n:Valid C Statements;break;default:Valid C Statements;break;}

CONDITIONALSSwitch statements can also be called matching case statements. If matches the value in variable (switch(variable)) with any of the case inside, the statements under the case that matches will be executed. If none of the case is matched the statement under default will be executed.switch.c#include#includevoid main(){int a;printf("Enter a no between 1 and 5 : ");scanf("%d",&a);

CONDITIONALSswitch(a){case 1:printf("You choosed One");break;case 2:printf("You choosed Two");break;case 3:printf("You choosed Three");break;case 4:printf("You choosed Four");break;

CONDITIONALScase 5:printf("You choosed Five");break;default :printf("Wrong Choice. Enter a no between 1 and 5");break;}

getch();}Program Algorithm / Explanation :#include header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.

CONDITIONALS#include is used because the C in-built function getch() comes under conio.h header files.main () function is the place where C program execution begins.Variable a of type int is declared.scanf is used to get the value from user for variable a.variable a is included for switch case. switch(a).If the user Input was 1 the statement inside case 1: will be executed. Likewise for the rest of the cases until 5.But if the user Input is other than 1 to 5 the statement under default : will be executed.Output :

CONDITIONALS5) goto statement in C :goto is a unconditional jump statement.Syntax :goto label;so we have to use the goto carefully inside a conditional statement.goto.c#include#includevoid main(){int a,b;printf("Enter 2 nos A and B one by one : ");scanf("%d%d",&a,&b);

CONDITIONALSif(a>b){goto first;}else{goto second;}first:printf("\n A is greater..");goto g;second:printf("\n B is greater..");g:getch();}

CONDITIONALSProgram Algorithm / Explanation :#include header file is included because, the C in-built statement printf we used in this program comes under stdio.h header files.#include is used because the C in-built function getch() comes under conio.h header files.main () function is the place where C program execution begins.Two variables a & b of type int are declared.User Inputs are received for a & b using scanf.if condition is used to check whether a is greater than b. if(a>b).if it is true goto statement is used to jump to the label first : and the statement under first : is executed and then again jump is performed to get to the end of the program. goto g:if the condition is false a statement is used to jump to label second. goto second : and the statement under second : is executed.

CONDITIONALSOutput :

LOOPING Looping statements are used to execute a statement or a group of statements repeatedly until the condition is true.Here, we will look into the following looping statements.for loopwhile loopdo while1) for Loop in C :Syntax :for(variable_initialisation;condition;increment/decrement){Valid C Statements;}In for loop first the variable is initialised and checks for the condition. If the condition is true. The statement inside for loop will be executed.

LOOPNGOn the next cycle the initialised variable will be either incremented or decremented and again checks for the condition. If the condition is true, again the statement inside will be executed. This process will continue until the condition is true. Once the condition fails the control jumps out of for loop.for.c#include#includevoid main(){int i,a=0;for(i=1;i