c language notes_latest

56
1 C Language Notes C is a general purpose high level language that was originally developed by Dennis M. Ritchie to develop the Unix operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. 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. 1. Easy to learn 2. Structured language 3. It produces efficient programs. 4. It can handle low-level activities. 5. It can be compiled on a variety of computer platforms. Facts about C C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970 The 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 softwar's have been implemented using C. Today's most popular Linux OS and RBDMS MySQL have been written in C. 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 Data Bases Language Interpreters Utilities C Hello World Example A C program basically consists of the following parts: Preprocessor Commands Functions Variables Statements & Expressions Comments Let us look at a simple code that would print the words "Hello World":

Upload: navdeep-negi

Post on 21-Jul-2016

29 views

Category:

Documents


1 download

DESCRIPTION

Notes on C Langguage

TRANSCRIPT

Page 1: C Language Notes_latest

1

C Language Notes

C is a general purpose high level language that was originally developed by Dennis M. Ritchie to develop the Unix operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.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.

1. Easy to learn2. Structured language3. It produces efficient programs.4. It can handle low-level activities.5. 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 1970The 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 softwar's have been implemented using C.Today's most popular Linux OS and RBDMS MySQL have been written in C.

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 Data Bases Language Interpreters Utilities

C Hello World ExampleA C program basically consists of the following parts:Preprocessor CommandsFunctionsVariablesStatements & ExpressionsCommentsLet us look at a simple code that would print the words "Hello World":

#include <stdio.h>

void main(){ /* my first program in C */ printf("Hello, World! \n"); getch();}Let us look various parts of the above program:

Page 2: C Language Notes_latest

2

The first line of the program #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation.The next line int main() is the main function where program execution begins.The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen.

TOKENS IN C

A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens:printf("Hello, World! \n");

1. The individual tokens are:printf("Hello, World! \n");

2. Semicolons ;In C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.For example, following are two different statements:printf("Hello, World! \n");return 0;

3. CommentsComments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below:/* my first program in C */You can not have comments with in comments and they do not occur within a string or character literals.Identifiers

4. Identifier : A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).

C does not allow punctuation characters such as @, $, and % within identifiers. C is a case sensitiveprogramming language. Thus Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers:mohd zara abc move_name a_123myname50 _temp j a23b9 retVal

KeywordsThe following list shows the reserved words in C. These reserved words may not be used as constant or variable or any other identifier names.auto else long switch

break enum register typedef

case extern return union

char float short unsigned

const for signed void

continue goto sizeof volatile

default if static while

do int struct _Packed

double  Total 32 keywords are there in c language 

Page 3: C Language Notes_latest

Data Types

Primary (Primitive) Data types For ex int , float char etc

Secondary ( Non primitive Data Types)For ex. Array ,structure, union etc

3

Whitespace in C

A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it.Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:int age;There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statementfruit = apples + oranges; // get the total fruit

Data Types : In the C programming language, data types refers to a system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.Data types are of two types

1. Primary (Primitive ) Data types - Defined by c language2. Secondary ( Non primitive Data Types) - Defined by user

The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section where as other types will be covered in the upcoming chapters.Integer TypesFollowing table gives you detail about standard integer types with its storage sizes and value ranges:

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

Page 4: C Language Notes_latest

4

#include <stdio.h>#include <limits.h>

int main(){ printf("Storage size for int : %d \n", sizeof(int)); return 0;}When you compile and execute the above program it produces following result on Linux:Storage size for int : 4Floating-Point TypesFollowing table gives you detail about standard float-point types with storage sizes and value ranges and their precision:Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Variable :A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a

specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. , there will be following basic variable types:Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.C programming language also allows to define various other type of variables which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union etc. For this chapter, let us study only basic variable types.

Variable Declaration in C

All variables must be declared before we use them in C program, although certain declarations can be made implicitly by content. A declaration specifies a type, and contains a list of one or more variables of that type as follows:type variable_list;

int i, j, k;char c, ch;float f, salary;double d;

Constants: The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.The constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer literalsAn integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

Page 5: C Language Notes_latest

5

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.Here are some examples of integer literals:212 /* Legal */215u /* Legal */0xFeeL /* Legal */078 /* Illegal: 8 is not an octal digit */032UU /* Illegal: cannot repeat a suffix */

Floating-point literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.Here are some examples of floating-point literals:3.14159 /* Legal */314159E-5L /* Legal */510E /* Illegal: incomplete exponent */210f /* Illegal: no decimal or exponent */.e55 /* Illegal: missing integer or fraction */

Character constants

Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of char type.A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').There are certain characters in C when they are proceeded by a back slash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here you have a list of some of such escape sequence codes:Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

Following is the example to show few escape sequence characters:#include <stdio.h>

Page 6: C Language Notes_latest

6

int main(){ printf("Hello\tWorld\n\n");

return 0;}When the above code is compiled and executed, it produces following result:Hello World

String literalsString literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.You can break a long lines into multiple lines using string literals and separating them using whitespaces.Here are some examples of string literals. All the three forms are identical strings."hello, dear"

Defining Constants

There are two simple ways in C to define constants:Using #define preprocessor.Using const keyword.The #define Preprocessor

Following is the form to use #define preprocessor to define a constant:#define identifier valueFollowing example explains it in detail:#include <stdio.h>

#define LENGTH 10 #define WIDTH 5#define NEWLINE '\n'

int main(){

int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE);

return 0;}When the above code is compiled and executed, it produces following result:value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows:const type variable = value;Following example explains it in detail:#include <stdio.h>

int main(){ const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE);

Page 7: C Language Notes_latest

7

return 0;}When the above code is compiled and executed, it produces following result:value of area : 50

Operators in C

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides following type of operators:

1. Arithmetic Operators2. Relational Operators3. Logical Operators4. Bitwise Operators5. Assignment Operators6. Misc Operators

Arithmetic OperatorsFollowing table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:Show ExamplesOperator Description Example

+ Adds two operandsA + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give 200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer division

B % A will give 0

++ Increment operator increases integer value by one A++ will give 11

-- Decrement operator decreases integer value by one A-- will give 9

Relational OperatorsFollowing table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:

Show ExamplesOperator Description Example

== Checks if the value of two operands is equal or not, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the (A < B)

Page 8: C Language Notes_latest

8

value of right operand, if yes then condition becomes true. is true.

>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Logical OperatorsFollowing table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0 then:Show ExamplesOperator Description Example

&& Called Logical AND operator. If both the operands are non zero then condition becomes true.

(A && B) is false.

|| Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.

(A || B) is true.

!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true.

Bitwise OperatorsBitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:p q p & q p | q p ^ q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1Assume if A = 60; and B = 13; Now in binary format they will be as follows:A = 0011 1100B = 0000 1101-----------------A&B = 0000 1100A|B = 0011 1101A^B = 0011 0001~A  = 1100 0011The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13 then:Show ExamplesOperator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in either operand.

(A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which

Page 9: C Language Notes_latest

9

is 0011 0001

~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A ) will give -60 which is 1100 0011

<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 0000 1111

Assignment OperatorsThere are following assignment operators supported by C language:Show ExamplesOperator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C

+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

<<= Left shift AND assignment operator

C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator

C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is

Page 10: C Language Notes_latest

10

same as C = C & 2

^= bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternaryThere are few other important operators including sizeof and ? : supported by C Language.Show ExamplesOperator Description Example

sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 4.

& Returns the address of an variable.&a; will give actual address of the variable.

* Pointer to a variable. *a; will pointer to a variable.

? : Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.Show ExamplesCategory  Operator  Associativity 

Postfix  () [] -> . ++ - -   Left to right 

Unary  + - ! ~ ++ - - (type)* & sizeof  Right to left 

Multiplicative   * / %  Left to right 

Additive   + -  Left to right 

Shift   << >>  Left to right 

Relational   < <= > >=  Left to right 

Equality   == !=  Left to right 

Bitwise AND  &  Left to right 

Bitwise XOR  ^  Left to right 

Bitwise OR  |  Left to right 

Logical AND  &&  Left to right 

Logical OR  ||  Left to right 

Conditional  ?:  Right to left 

Page 11: C Language Notes_latest

11

Assignment  = += -= *= /= %=>>= <<= &= ^= |=  Right to left 

Comma  ,  Left to right 

Page 12: C Language Notes_latest

12

Typecasting

Typecasting is a way to convert a variable from one data type to another data type. For example if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows:(type_name) expressionConsider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:#include <stdio.h>

main(){ int sum = 17, count = 5; double mean;

mean = (double) sum / count; printf("Value of mean : %f\n", mean );

}When the above code is compiled and executed, it produces the following result:Value of mean : 3.400000It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary.Integer PromotionInteger promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int:#include <stdio.h>

main(){ int i = 17; char c = 'c'; /* ascii value is 99 */ int sum;

sum = i + c; printf("Value of sum : %d\n", sum );

}When the above code is compiled and executed, it produces the following result:Value of sum : 116Here value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before performing actual addition operation.Usual Arithmetic ConversionThe usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy:

Page 13: C Language Notes_latest

13

The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and ||. Let us take following example to understand the concept:#include <stdio.h>

main(){ int i = 17; char c = 'c'; /* ascii value is 99 */ float sum;

sum = i + c; printf("Value of sum : %f\n", sum );

}When the above code is compiled and executed, it produces the following result:Value of sum : 116.000000Here it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic conversion applies and compiler convert i and c into float and add them yielding a float result.

DECISION MAKING

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria.

These statements are called as 'Decision Making Statements' or 'Conditional Statements.'

Followings are the different conditional statements used in C.

Page 14: C Language Notes_latest

14

1. If Statement 2. If-Else Statement 3. Nested If-Else Statement 4. Switch Case

1. If Statement :

This is a conditional statement used in C to check condition or to control the flow of execution of statements. This is also called as 'decision making statement or control statement.' The execution of a whole program is done in one direction only.

Syntax:

if(condition){

statements;//instructions will executed if condition is true}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then program skips the braces. If there are more than 1 (one) statements in if statement then use { } braces else it is not necessary to use.

#include <stdio.h>#include <conio.h>void main(){

int a;a=5;clrscr();if(a>4)

printf("\nValue of A is greater than 4 !");if(a==4)

printf("\n\n Value of A is 4 !");getch();

}

2. If-Else Statement:

This is also one of the most useful conditional statement used in C to check conditions.

Syntax:

if(condition){

true statements;}else{

false statements;

Page 15: C Language Notes_latest

15

}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and executes the block of statements associated with it. If it returns false, then it executes the else part of a program.

#include <stdio.h>#include <conio.h>void main(){

int no;clrscr();printf("\n Enter Number :");scanf("%d",&no);if(no%2==0)

printf("\n\n Number is even !");else

printf("\n\n Number is odd !");getch();

}

3. Nested If-Else Statement :

It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute.

Syntax:

if(condition){

if(condition){

statements;}else{

statements;}

}else{

statements;}

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the braces and again checks the next condition. If it is true then it executes the block of statements associated with it else executes else part.

Program :

Page 16: C Language Notes_latest

16

/* Program to demonstrate nested if-else statement.

Creation Date : 09 Nov 2010 02:51:18 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int no;clrscr();printf("\n Enter Number :");scanf("%d",&no);if(no>0){

printf("\n\n Number is greater than 0 !");}else{

if(no==0){

printf("\n\n It is 0 !");}else{

printf("Number is less than 0 !");}

}getch();

}

4. Switch case Statement :

This is a multiple or multiway brancing decision making statement.

When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.

Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.

Syntax:

switch(expression){

case expr1:statements;break;

case expr2:statements;

Page 17: C Language Notes_latest

17

break;

        ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '         ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '

case exprn:statements;break;

default:statements;

}

In above syntax, switch, case, break are keywords.

expr1, expr2 are known as 'case labels.'

Statements inside case expression need not to be closed in braces.

Break statement causes an exit from switch statement.

Default case is optional case. When neither any match found, it executes.

Program :

/* Program to demonstrate switch case statement.

Creation Date : 09 Nov 2010 03:03:57 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int no;clrscr();printf("\n Enter any number from 1 to 3 :");scanf("%d",&no);switch(no){

case 1:printf("\n\n It is 1 !");break;

case 2:printf("\n\n It is 2 !");break;

case 3:printf("\n\n It is 3 !");break;

default:printf("\n\n Invalid number !");

}getch();

}

Page 18: C Language Notes_latest

18

Looping Statements / Iterative Statements :

'A loop' is a part of code of a program which is executed repeatedly.

A loop is used using condition. The repetition is done until condition becomes condition true.

A loop declaration and execution can be done in following ways.

o Check condition to start a loopo Initialize loop with declaring a variable.o Executing statements inside loop.o Increment or decrement of value of a variable.

* Types of looping statements :Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.

Entry controlled loop Exit controlled loop

1. Entry controlled loop :

In such type of loop, the test condition is checked first before the loop is executed.

Some common examples of this looping statements are :

o while loop o for loop

2. Exit controlled loop :

In such type of loop, the loop is executed first. Then condition is checked after block of statements are executed. The loop executed atleat one time compulsarily.

Some common example of this looping statement is :

o do-while loop

While loop :

This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.

Syntax:

while(condition){

statements;increment/decrement;

}

Page 19: C Language Notes_latest

19

In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.

Program :

/* Program to demonstrate while loop.

Creation Date : 09 Nov 2010 03:45:01 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int a;clrscr();a=1;while(a<=5){

printf("\n TechnoExam");a+=1 // i.e. a = a + 1

}getch();

}

For loop :

This is an entry controlled looping statement.

In this loop structure, more than one variable can be initilized. One of the most important feature of this loop is that the three actions can be taken at a time like variable initilisation, condition checking and increment/decrement. The for loop can be more concise and flexible than that of while and do-while loops.

Syntax:

for(initialisation; test-condition; incre/decre){

statements;}

In above syntax, the given three expressions are seperated by ';' (Semicolon)

Features :

o More conciseo Easy to useo Highly flexibleo More than one variable can be initilized.

Page 20: C Language Notes_latest

20

o More than one increments can be applied.o More than two conditions can be used.

Program :

/* Program to demonstrate for loop.

Creation Date : 09 Nov 2010 02:52:31 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int a;clrscr();for(i=0; i<5; i++){

printf("\n\t TechnoExam"); // 5 times}getch();

}

Do-While loop :

This is an exit controlled looping statement.

Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.

Syntax:

do{

statements;(increment/decrement);

}while(condition);

In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.

Note: The while statement should be terminated with ; (semicolon).

Program :

/* Program to demonstrate do while loop.

Creation Date : 09 Nov 2010 03:21:01 AM

Page 21: C Language Notes_latest

21

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int a;clrscr();a=1;do{

printf("\n\t TechnoExam"); // 5 timesa+=1; // i.e. a = a + 1

}while(a<=5);a=6;do{

printf("\n\n\t Technowell"); // 1 timea+=1; // i.e. a = a + 1

}while(a<=5);getch();

}

Break Statement :

Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.

When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.

Syntax :

break;

Figure :

Program :

/* Program to demonstrate break statement.

Creation Date : 09 Nov 2010 05:32:33 PM

Author : www.technoexam.com [Technowell, Sangli] */

Page 22: C Language Notes_latest

22

#include <stdio.h>#include <conio.h>void main(){

int i;clrscr();for(i=1; ; i++){

if(i>5)break;printf("%d",i); // 5 times only

}getch();

}

Continue Statement :

Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this anomaly.

The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. It causes the loop to be continued with next iteration after skipping statements in between. Continue statement simply skipps statements and continues next iteration.

Syntax :

continue;

Figure :

Program :

/* Program to demonstrate continue statement.

Creation Date : 09 Nov 2010 07:44:43 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int i;

Page 23: C Language Notes_latest

23

clrscr();for(i=1; i<=10; i++){

if(i==6)continue;printf("\n\t %d",i); // 6 is omitted

}getch();

}

Goto Statement :

It is a well known as 'jumping statement.' It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop.

When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used.

Syntax :

goto [expr];

Figure :

Program :

/* Program to demonstrate goto statement.

Creation Date : 09 Nov 2010 08:14:00 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int i=1, j;clrscr();

Page 24: C Language Notes_latest

24

while(i<=3){

for(j=1; j<=3; j++){

printf(" * ");if(j==2)goto stop;

}i = i + 1;

}stop:

printf("\n\n Exited !");getch();

}

Array :

Array is a collection of homogenous data stored under unique name. The values in an array is called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.

Array is also called as 'subscripted variable.'

Types of an Array :

1. One / Single Dimensional Array 2. Two Dimensional Array

Single / One Dimensional Array :

The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'

Syntax:

<data-type> <array_name> [size];

Example:

int a[3] = {2, 3, 5};char ch[20] = "TechnoExam" ;float stax[3] = {5003.23, 1940.32, 123.20} ;

Total Size (in Bytes):

total size = length of array * size of data type

In above example, a is an array of type integer which has storage size of 3 elements. The total size would be 3 * 2 = 6 bytes.

* Memory Allocation :

Page 25: C Language Notes_latest

25

Fig : Memory allocation for one dimensional array

Program :

/* Program to demonstrate one dimensional array.

Creation Date : 10 Nov 2010 11:07:49 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

int a[3], i;;clrscr();printf("\n\t Enter three numbers : ");for(i=0; i<3; i++){

scanf("%d", &a[i]); // read array}printf("\n\n\t Numbers are : ");for(i=0; i<3; i++){

printf("\t %d", a[i]); // print array}getch();

}

Output :

Enter three numbers : 9 4 6

Numbers are : 9 4 6_

Features :

o Array size should be positive number only.o String array always terminates with null character ('\0').o Array elements are countered from 0 to n-1.o Useful for multiple reading of elements (numbers).

Page 26: C Language Notes_latest

26

Disadvantages :

o There is no easy method to initialize large number of array elements.o It is difficult to initialize selected elements.

:

Two Dimensional Array :

The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array specially used to represent data in a matrix form.

The following syntax is used to represent two dimensional array.

Syntax:

<data-type> <array_nm> [row_subscript][column-subscript];

Example:

int a[3][3];

In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total size would be 3 * 3 * 2 = 18 bytes.

It is also called as 'multidimensional array.'

* Memory Allocation :

Fig : Memory allocation for two dimensional array

Program :

/* Program to demonstrate two dimensional array.

Creation Date : 10 Nov 2010 02:01:09 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main()

Page 27: C Language Notes_latest

27

{int a[3][3], i, j;clrscr();printf("\n\t Enter matrix of 3*3 : ");for(i=0; i<3; i++){

for(j=0; j<3; j++){scanf("%d",&a[i][j]); //read 3*3 array}

}printf("\n\t Matrix is : \n");for(i=0; i<3; i++){

for(j=0; j<3; j++){printf("\t %d",a[i][j]); //print 3*3 array}

printf("\n");}getch();

}

Output :

Enter matrix of 3*3 : 3 4 5 6 7 2 1 2 3

Matrix is :3 4 56 7 21 2 3_

Limitations of two dimensional array :

o We cannot delete any element from an array.o If we dont know that how many elements have to be stored in a memory in advance, then there will be memory

wastage if large array size is specified.

Page 28: C Language Notes_latest

28

String Handling in C :String :A string is a collection of characters. Strings are always enlosed in double quotes as "string_constant".Strings are used in string handling operations such as, Counting the length of a string. Comparing two strings. Copying one string to another. Converting lower case string to upper case. Converting upper case string to lower case. Joining two strings. Reversing string.Declaration :The string can be declared as follow :Syntax:

char string_name[size];

Example:

char name[50];

String Structure :When compiler assigns string to character array then it automatically suppliesnull character ('\0') at the end of string. Thus, size of string = original length of string + 1.

char name[7];name = "TECHNO"

Read Strings :To read a string, we can use scanf() function with format specifier %s.

char name[50];scanf("%s",name);

The above format allows to accept only string which does not have any blank space, tab, new line, form feed, carriage return.Write Strings :To write a string, we can use printf() function with format specifier %s.

char name[50];scanf("%s",name);printf("%s",name);

Page 29: C Language Notes_latest

29

STRING HANDLING FUNCTIONSFunction Name Description

strlen - Returns the length of a string.strlwr - Returns upper case letter to lower case.strupr - Returns lower case letter to upper case.strcat - Concatenates two string.strcmp - Compares two strings.strrev - Returns length of a string.strcpy - Copies a string from source to destination.

1. STRCPY

char *strcpy (char *dest, char *src);

Description:

The strcpy function copies characters from src to dest up to and including the terminating null character.

Return Value

The strcpy function returns dest.

Example

#include <stdio.h>

int main() { char input_str[20]; char *output_str;

strcpy(input_str, "Hello"); printf("input_str: %s\n", input_str);

output_str = strcpy(input_str, "World");

printf("input_str: %s\n", input_str); printf("output_str: %s\n", output_str);

return 0;}

It will proiduce following result:

2. strncpy functionchar *strncpy (char *dest, char *src, int n);

Description:

The strcpy function copies n characters from src to dest up to and including the terminating null character if

Page 30: C Language Notes_latest

30

length of src is less than n.

Return Value

The strncpy function returns dest.Example

#include <stdio.h>

int main() { char input_str[20]; char *output_str;

strncpy(input_str, "Hello", 20); printf("input_str: %s\n", input_str);

/* Reset string */ memset(input_str, '\0', sizeof( input_str ));

strncpy(input_str, "Hello", 2); printf("input_str: %s\n", input_str);

/* Reset string */ memset(input_str, '\0', sizeof( input_str )); output_str = strncpy(input_str, "World", 3);

printf("input_str: %s\n", input_str); printf("output_str: %s\n", output_str);

return 0;}

3. strcmp functionint strcmp(char *string1, char *string2);

Description:

The strcmp function compares the contents of string1 and string2 and returns a value indicating their relationship.

Return Value

if Return value if < 0 then it indicates string1 is less than string2 if Return value if > 0 then it indicates string2 is less than string1 if Return value if = 0 then it indicates string1 is equal to string1

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

Page 31: C Language Notes_latest

31

strcpy(string1, "Helloooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

strcpy(string1, "Hellooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strcmp( string1, string2));

return 0;}

4. C - strncmp functionint strncmp(char *string1, char *string2, int n);

Description:

The strncmp function compares first n characters of string1 and string2 and returns a value indicating their relationship.

Return Value

if Return value if < 0 then it indicates string1 is less than string2 if Return value if > 0 then it indicates string2 is less than string1 if Return value if = 0 then it indicates string1 is equal to string1

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 4));

strcpy(string1, "Helloooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 10));

strcpy(string1, "Hellooo"); strcpy(string2, "Hellooo"); printf("Return Value is : %d\n", strncmp( string1, string2, 20));

return 0;}

5. strlen functionint strlen(char *src );

Description:

The strlen function calculates the length, in bytes, of src. This calculation does not include the null terminating

Page 32: C Language Notes_latest

32

character.

Return Value

The strlen function returns the length of src.

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo");

printf("Length of string1 : %d\n", strlen( string1 )); printf("Length of string2 : %d\n", strlen( string2 ));

return 0;}

6. strcat functionchar *strcat(char *dest, const char *src);

Description:

The strcat function concatenates or appends src to dest. All characters from src are copied including the terminating null character.

Return Value

The strcat function returns dest.

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo");

printf("Returned String : %s\n", strcat( string1, string2 )); printf("Concatenated String : %s\n", string1 );

return 0;}

Page 33: C Language Notes_latest

33

7. strncat function

char *strncat(char *dest, const char *src, int n);

Description:

The strncat function concatenates or appends first n characters from src to dest. All characters from src are copied including the terminating null character.

Return Value

The strncat function returns dest.

Example

#include <stdio.h>

int main() { char string1[20]; char string2[20];

strcpy(string1, "Hello"); strcpy(string2, "Hellooo");

printf("Returned String : %s\n", strncat( string1, string2, 4 )); printf("Concatenated String : %s\n", string1 );

return 0;}

8. strchr functionchar *strchr(char *string, int c);

Description:

The strchr function searches string for the first occurrence of c. The null character terminating string is included in the search.

Return Value

The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found.

Example

#include <stdio.h>

int main() { char *s; char buf [] = "This is a test";

s = strchr (buf, 't');

if (s != NULL) printf ("found a 't' at %s\n", s);

return 0;

Page 34: C Language Notes_latest

34

Functions in C :The function is a self contained block of statements which performs a coherent task of a same kind.C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call fuction whenever we want to process that functions statements.

Advantages : It is easy to use. Debugging is more suitable for programs. It reduces the size of a program. It is easy to understand the actual logic of a program. Highly suited in case of large programs. By using functions in a program, it is possible to construct modular and structured programs.

Types of functions :There are 2(two) types of functions as:1. Built in Functions2. User Defined Functions

1. Built in Functions :

These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g. scanf() printf() strcpy strlwr strcmp strlen strcat

1. User Defined Functions :

The functions which are created by user for program are known as 'User defined functions'.Syntax:

void main(){

// Function prototype<return_type><function_name>([<argu_list>]);

// Function Call<function_name>([<arguments>]);

}// Function definition<return_type><function_name>([<argu_list>]);{

<function_body>;}

Types of functions

S.no Returntype Argument Function Protoype with example1 NO NO void sum()2 NO YES void sum(int a)3 YES NO int sum()4 YES YES int sum(int a, intb)

Page 35: C Language Notes_latest

35

Function Call by Passing Value :When a function is called by passing value of variables then that function is known as 'function call by passing values.'Syntax:

// Declarationvoid <function_name>(<data_type><var_nm>);

// Calls<function_name>(<var_nm>);

// Definitionvoid <function_name>(<data_type><var_nm>);{

<function_body>;- - - - - - - -;

}Program :

/* Program to demonstrate function call by passing value.

Creation Date : 24 Nov 2010 12:08:26 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

void printno(int a){

printf("\n Number is : %d", a);}void main(){

int no;void printno(int);clrscr();printf("\n Enter Number : ");scanf("%d", &no);printno(no);getch();

}

Output :

Enter Number : 21

Number is : 21_

Call by Value whenever we called a function and passed something to it we have always passed the ‘values’ of variables to the called function. Such function calls are called ‘calls by value’. By this what we mean is, on calling a function we are passing values of variables to it. The examples of call by value are shown below: sum = calsum ( a, b, c ) ; f = factr ( a ) ;

Page 36: C Language Notes_latest

36

Call by Reference: in call by reference instead of passing the value of a variable, we pass the location number (also called address) of the variable to a function? (we will do it in pointers)

Recursion:

Recursion is a process in which a function calls itself A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.

example of recursion. to calculate the factorial value of an integer.

main( ) { int a, fact ; printf ( "\nEnter any number " ) ; scanf ( "%d", &a ) ; fact = factorial ( a ) ; printf ( "Factorial value = %d", fact ) ; } factorial ( int x ) { int f = 1, i ; for ( i = x ; i >= 1 ; i-- ) f = f * i ; return ( f ) ; }

And here is the output... Enter any number 3

Factorial value = 6

Pointer :Pointer is a variable which holds the memory address of another variable. Pointers are represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.Syntax:

<data_type> *pointer_name;

In above syntax, * = variable pointer_name is a pointer variable. pointer_name requires memory location pointer_name points to a variable of type data type.How to Use ?

int *tot;

Illustration :

int tot = 95;

Figure :

In above example, the statement instructs the system to find out a location for integer variable quantity and puts the values 95 in that memory location.

Page 37: C Language Notes_latest

37

* Features of Pointer :

* Pointer variable should have prefix '*'.* Combination of data types is not allowed.* Pointers are more effective and useful in handling arrays.* It can also be used to return multiple values from a funtion using function arguments.* It supports dynamic memory management.* It reduces complexity and length of a program.* It helps to improve execution speed that results in reducing program execution time.

Program :

/* Program to demonstrate pointer.

Creation Date : 10 Nov 2010 11:41:20 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

void main(){

int a=10;int *ptr;clrscr();ptr = &a;printf("\n\t Value of a : %d", a);scanf("\n\n\t Value of pointer ptr : %d", *ptr);printf("\n\n\t Address of pointer ptr : %d", ptr);getch();

}

Output :

Value of a : 10

Value of pointer ptr : 10

Address of pointer ptr : -12_

Page 38: C Language Notes_latest

38

Pointer arithmetic

Pointers can be added and subtracted. However pointer arithmetic is quite meaningless unless performed on arrays. Addition and subtraction are mainly for moving forward and backward in an array.

Note: you have to be very careful NOT to exceed the array elements when you use arithmetic; otherwise you will get horrible errors such as “access violation”. This error is caused because your code is trying to access a memory location which is registered to another program.

Operator Result

++ Goes to the next memory location that the pointer is pointing to.

-- Goes to the previous memory location that the pointer is pointing to.

-= or - Subtracts value from pointer.

+= or + Adding to the pointer

Pointers and functions

Pointers can be used with functions. The main use of pointers is ‘call by reference’ functions. Call by reference function is a type of function that has pointer/s (reference) as parameters to that function. All calculation of that function will be directly performed on referred variables.

Sample Code1. #include <stdio.h>2. void DoubleIt(int *num)3. {4.         *num*=2; 5. }6. int main()7. { 8.         int number=2; 9.                 DoubleIt(&number);10.                         printf("%d",number);11. return 0; 12. }

Description of ‘code 3’: in line 1 we are declaring ‘DoubleIt’ function, in line 4, the variable number is declared and initialized to 2. In line 5, the function DoubleIt is called.

Pointer to Arrays

Array identifier is a pointer itself. Therefore & notation shouldn’t be used with arrays. The example of this can be found at code 3. When working with arrays and pointers always remember the following:

Never use & for pointer variable pointing to an array. When passing array to function you don’t need * for your declaration. Be VERY CAREFUL not to exceed number of elements your array holds when using pointer arithmetic to avoid errors.

Page 39: C Language Notes_latest

39

Pointers and Structures

Pointers and structures is broad topic and it can be very complex to include it all in one single tutorial. However pointers and structures are great combinations; linked lists, stacks, queues and etc are all developed using pointers and structures in advanced systems.

Example:

Number Structure

Sample Code

1. #include <stdio.h>2.  3. struct details {4. int num;5. };6.  7. int main()8. { 9.         10. struct details MainDetails;11. struct details *structptr;12. structptr=&MainDetails;13. structptr->num=20; 14. printf("n%d",MainDetails.num);15.  16.  17. return 0; 18. }

Figure 4. code 4 result

Description of ‘code 4’: in line 1-3 we are declaring ‘details’ structure, in line 4, the variable Maindetails is declared.in line 6, pointer is set to point to MainDetails. In line 7, 20 is assigned to MainDetails.num through structptr->num.

Pointer to Pointer

Pointers can point to other pointers; there is no limit whatsoever on how many ‘pointer to pointer’ links you can have in your program. It is entirely up to you and your programming skills to decide how far you can go before you get confused with the links. Here we will only look at simple pointer to pointer link. Pointing to pointer can be done exactly in the same way as normal pointer. Diagram below can help you understand pointer to pointer relationship.

Diagram 2. Simple pointer to pointer relationship

Code for diagram 2:

Page 40: C Language Notes_latest

40

Char *ptrA;Char x=’b’;Char *ptrb;ptrb=&x;ptrA=&ptrb;

ptrA gives 100, *ptrA gives 101 , ptrb is 101 ,*ptrb gives b, **ptrA gives bcomment: **ptrA means ‘value stored at memory location of value stored in memory location stored at PtrA’

Structure :Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.The variables which are declared inside the structure are called as 'members of structure'.Syntax:

struct structure_nm{

<data-type> element 1;<data-type> element 2;- - - - - - - - - - -- - - - - - - - - - -<data-type> element n;

}struct_var;

Example :

struct emp_info{

char emp_id[10];char nm[100];float sal;

}emp;

Note :

1. Structure is always terminated with semicolon (;).2. Structure name as emp_info can be later used to declare structure variables of its type in a program.

* INSTANCES OF STRUCTURE :Instances of structure can be created in two ways as,Instance 1:

struct emp_info{

char emp_id[10];char nm[100];float sal;

}emp;

Instance 2:

Page 41: C Language Notes_latest

41

struct emp_info{

char emp_id[10];char nm[100];float sal;

};struct emp_info emp;In above example, emp_info is a simple structure which consists of stucture members as Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).* ACEESSING STRUCTURE MEMBERS :Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'.structure_var.member;

Program :

/* Program to demonstrate structure.

Creation Date : 23 Nov 2010 02:41:01 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

struct comp_info{

char nm[100];char addr[100];

}info;

void main(){

clrscr();printf("\n Enter Company Name : ");gets(info.nm);printf("\n Enter Address : ");gets(info.addr);printf("\n\n Company Name : %s",info.nm);printf("\n\n Address : %s",info.addr);getch();

}

Output :

Enter Company Name : TechnoExam, Technowell Web Solutions Enter Address : Sangli, Maharashtra, INDIA Company Name : TechnoExam, Technowell Web Solutions Address : Sangli, Maharashtra, INDIA_

Array in Structures :Sometimes, it is necessary to use structure members with array.

Page 42: C Language Notes_latest

42

Program :

/* Program to demonstrate array in structures.

Creation Date : 23 Nov 2010 06:07:11 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

struct result{

int rno, mrks[5];char nm;

}res;

void main(){

int i,total;clrscr();total = 0;printf("\n\t Enter Roll Number : ");scanf("%d",&res.rno);printf("\n\t Enter Marks of 3 Subjects : ");for(i=0;i<3;i++){

scanf("%d",&res.mrks[i]);total = total + res.mrks[i];

}printf("\n\n\t Roll Number : %d",res.rno);printf("\n\n\t Marks are :");for(i=0;i<3;i++){

printf(" %d",res.mrks[i]);}printf("\n\n\t Total is : %d",total);getch();

}

Structure With Array :We can create structures with array for ease of operations in case of getting multiple same fields.Program :

/* Program to demonstrate Structure With Array.

Creation Date : 23 Nov 2010 06:49:00 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

struct emp_info{

int emp_id;char nm[50];

}emp[2];

void main(){

int i;clrscr();for(i=0;i<2;i++){

printf("\n\n\t Enter Employee ID : ");

Page 43: C Language Notes_latest

43

scanf("%d",&emp[i].emp_id);printf("\n\n\t Employee Name : ");scanf("%s",emp[i].nm);

}for(i=0;i<2;i++){ printf("\n\t Employee ID : %d",emp[i].emp_id); printf("\n\t Employee Name : %s",emp[i].nm);}getch();

}

Structures within Structures (Nested Structures) :Structures can be used as structures within structures. It is also called as 'nesting of structures'.Syntax:

struct structure_nm{

<data-type> element 1;<data-type> element 2;- - - - - - - - - - -- - - - - - - - - - -<data-type> element n;

struct structure_nm{

<data-type> element 1;<data-type> element 2;- - - - - - - - - - -- - - - - - - - - - -<data-type> element n;

}inner_struct_var;}outer_struct_var;

Example :

struct stud_Res{

int rno;char nm[50];char std[10];

struct stud_subj{

char subjnm[30];int marks;

}subj;}result;In above example, the structure stud_Res consists of stud_subj which itself is a structure with two members. Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner structure.' The members which are inside the inner structure can be accessed as follow :result.subj.subjnmresult.subj.marksProgram :

/* Program to demonstrate nested structures.

Creation Date : 23 Nov 2010 04:04:01 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

struct stud_Res{

Page 44: C Language Notes_latest

44

int rno;char std[10];struct stud_Marks{

char subj_nm[30];int subj_mark;

}marks;}result;

void main(){

clrscr();printf("\n\t Enter Roll Number : ");scanf("%d",&result.rno);printf("\n\t Enter Standard : ");scanf("%s",result.std);printf("\n\t Enter Subject Code : ");scanf("%s",result.marks.subj_nm);printf("\n\t Enter Marks : ");scanf("%d",&result.marks.subj_mark);printf("\n\n\t Roll Number : %d",result.rno);printf("\n\n\t Standard : %s",result.std);printf("\nSubject Code : %s",result.marks.subj_nm);printf("\n\n\t Marks : %d",result.marks.subj_mark);getch();

}Union :Union is user defined data type used to stored data under unique variable name at single memory location.Union is similar to that of stucture. Syntax of union is similar to stucture. But the major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.To declare union data type, 'union' keyword is used.Union holds value for one data type which requires larger storage among their members.Syntax:

union union_name{

<data-type> element 1;<data-type> element 2;<data-type> element 3;

}union_variable;

Example:

union techno{

int comp_id;char nm;float sal;

}tch;

In above example, it declares tch variable of type union. The union contains three members as data type of int, char, float. We can use only one of them at a time.* MEMORY ALLOCATION :

Fig : Memory allocation for union

To access union members, we can use the following syntax.tch.comp_idtch.nmtch.sal

Page 45: C Language Notes_latest

45

Program :

/* Program to demonstrate union.

Creation Date : 10 Nov 2010 09:24:09 PM

Author :www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

union techno{

int id;char nm[50];

}tch;

void main(){

clrscr();printf("\n\t Enter developer id : ");scanf("%d", &tch.id);printf("\n\n\t Enter developer name : ");scanf("%s", tch.nm);printf("\n\n Developer ID : %d", tch.id);//Garbage printf("\n\n Developed By : %s", tch.nm);getch();

}

Storage Class :'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a varible can be used. Storage class defines the the scope and lifetime of a variable.From the point view of C compiler, a variable name identifies physical location from a computer where varaible is stored. There are two memory locations in a computer system where variables are stored as : Memory and CPU Registers.Functions of storage class :To detemine the location of a variable where it is stored ?Set initial value of a variable or if not specified then setting it to default value.Defining scope of a variable.To determine the life of a variable.Types of Storage Classes :Storage classes are categorised in 4 (four) types as,

Automatic Storage Class Register Storage Class Static Storage Class External Storage Class

Automatic Storage Class :o Keyword : autoo Storage Location : Main memoryo Initial Value : Garbage Valueo Life : Control remains in a block where it is defined.o Scope : Local to the block in which variable is declared.Syntax :

auto [data_type] [variable_name];

Example :

auto int a;

Page 46: C Language Notes_latest

46

Program :/* Program to demonstrate automatic storage class.

Creation Date : 06 Nov 2010 11:05:11 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>void main(){

auto int i=10;clrscr();{

auto int i=20;printf("\n\t %d",i);

}printf("\n\n\t %d",i);getch();

}

Register Storage Class :o Keyword : registero Storage Location : CPU Registero Initial Value : Garbageo Life : Local to the block in which variable is declared.o Scope : Local to the block.Syntax :

register [data_type] [variable_name];

Example :

register int a;

When the calculations are done in CPU, then the value of variables are transferred from main memory to CPU. Calculations are done and the final result is sent back to main memory. This leads to slowing down of processes.Register variables occur in CPU and value of that register variable is stored in a register within that CPU. Thus, it increases the resultant speed of operations. There is no waste of time, getting variables from memory and sending it to back again.It is not applicable for arrays, structures or pointers.It cannot not used with static or external storage class.Unary and address of (&) cannot be used with these variables as explicitly or implicitly.

Program :/* Program to demonstrate register storage class.

Creation Date : 09 Nov 2010 11:50:55 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

void main(){

register int i=10;clrscr();{

register int i=20;printf("\n\t %d",i);

}printf("\n\n\t %d",i);getch();

}

Page 47: C Language Notes_latest

47

Static Storage Class :o Keyword : statico Storage Location : Main memoryo Initial Value : Zero and can be initialize once only.o Life : depends on function calls and the whole application or program.o Scope : Local to the block.Syntax :

static [data_type] [variable_name];

Example :

static int a;

There are two types of static variables as : 

a) Local Static Variableb) Global Static VariableStatic storage class can be used only if we want the value of a variable to persist between different function calls.

Program :/* Program to demonstrate static storage class.

Creation Date : 10 Nov 2010 00:14:22 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

void main(){

int i;void incre(void);clrscr();for (i=0; i<3; i++)incre();getch();

}

void incre(void){

int avar=1;static int svar=1;avar++;svar++;printf("\n\n Automatic variable value : %d",avar);printf("\t Static variable value : %d",svar);

}External Storage Class :

o Keyword : externo Storage Location : Main memoryo Initial Value : Zeroo Life : Until the program ends.o Scope : Global to the program.Syntax :

extern [data_type] [variable_name];

Example :

extern int a;

The variable access time is very fast as compared to other storage classes. But few registers are available for user programs.

Page 48: C Language Notes_latest

48

The variables of this class can be referred to as 'global or external variables.' They are declared outside the functions and can be invoked at anywhere in a program.

Program :/* Program to demonstrate external storage class.

Creation Date : 06 Nov 2010 11:15:04 PM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>#include <conio.h>

extern int i=10;void main(){

int i=20;void show(void);clrscr();printf("\n\t %d",i);show();getch();

}void show(void){

printf("\n\n\t %d",i);}