You are on page 1of 97

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

1.INTRODUCTION
1.1 HISTORY
C was developed by Dennis Retchie in 1972 at the Bell Telephone Laboratories in .S.A. C was derived from a Language known as BCPL which was evolved at the Massachusetts Institute of Technology in the late 60s. BCPL was used to develop an operating system known as MULTICS for early multi-user time shared computers. One of the aims of BCPL was to achieve efficiency in compiled code. Thus BCPL was defined such that a translator could produce efficient machine Language code. C being a successor of BCPL has a similar philosophy. C Language has been defined so that it has the advantages of a high level language namely machine independence. At the same time it is concise, providing only the bare essentials required in a language so that a translator can translate it in to an efficient machine language code. Until 1978, C was confined to use within Bell Laboratories. In 1978, when Brian Kernighan and Ritchie published a description of the language, known as k & rc computer professionals got impressed with Cs many desirable features. By mid 1980s, popularity of C became wide spread Numerous C Compiler were written for computers of all sizes.

1.2 WHY USE C?


C (and its object oriented version, C++) is one of the most widely used third generation programming languages. Its power and flexibility ensure it is still the leading choice for almost all areas of application, especially in the software development environment. Many applications are written in C or C++, including the compilers for other programming languages. It is the language many operating systems are written in including Unix, DOS and Windows . It continues to adapt to new uses, the latest being Java, which is used for programming Internet applications. C has many strengths, it is flexible and portable, it can produce fast, compact code, it provides the programmer with objects to create and manipulate complex structures (e.g classes in C++) and low level routines to control hardware (e.g input and output ports and operating system interrupts). It is also one of the few languages to have an international standard, ANSI C.

1.3 ALGORITHMS
1. An algorithm is a description of a procedure which terminates with a result. 2. Algorithms is used or solve the problem step by step. It is the part of Software Designing. 3. An Algorithm defines as the step by step method that can be carried out for solving programming problems. An Algorithm tells Computer that how to solve the problem Systematically to get desired output.

1 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

We follow following steps to design an algorithm.

1.4 DEVELOPING ALGORITHMS


Step 1 START It represents beginning of the algorithm. Step 2 DECLARE The variables used in algorithm are declared in this step. Step 3 INPUT Here we input the values Step 4 FORMULA The required result is generated in this step. Step 5 OUTPUT It displays the output or result. Step 6 STOP It is an end of Algorithm An very simple example of an algorithm is multiplying two numbers: on first computers with limited processors, this was accomplished by a routine that in a number of loop based on the first number adds the second number. The algorithm translates a method into computer commands.

1.5 ALGORITHMIC EFFICIENCY


In computer science, efficiency is used to describe properties of an algorithm relating to how much of various types of resources it consumes. Algorithmic efficiency can be thought of as analogous to engineering productivity for a repeating or continuous process, where the goal is to reduce resource consumption, including time to completion, to some acceptable, optimal level. The two most frequently encountered and measurable metrics of an algorithm are:

speed or running timethe time it takes for an algorithm to complete, and 'space'the memory or 'non-volatile storage' used by the algorithm during its operation.

but also might apply to


transmission sizesuch as required bandwidth during normal operation or size of external memory- such as temporary disk space used to accomplish its task and perhaps even
2

Mob-8080373934

Atul Sirs Private Tuition (Engg)


Structured Programming (Sem II)

the size of required 'longterm' disk space required after its operation to record its output or maintain its required function during its required useful lifetime the performance per watt and the total energy, consumed by the chosen hardware implementation (with its system requirements, necessary auxiliary support systems including interfaces, cabling, switching, cooling and security), during its required useful lifetime.

3 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

2. C LANGUAGE
2.1 Structure of a C Program:The structure of a C program can by explained by taking an example of a C program to calculate area and perimeter of a rectangle. The program is written as follows.
/* This program prints a one-line message */ #include <stdio.h> void main() { printf("Hello World\n"); }

Comments In the above program the first line in the program starts with /* and ends with */. Any thing written between /* and */ is called a comment. /**/ its is a multiline Comment and Single line Comment is represented by // In the C Language comments are an aid to the programmer to read and understand a program. It is not a statement of the language. The compiler ignores comments. It is a good practice to include comments in a program which will help in understanding a program. PREPROCESSOR DIRECTIVE Now let us observe the line # include <stdio.h> This is called a preprocessor directive. It is written at the beginning of the program. It commands that the contents of the file stdio.h should be included in the compiled machine code at the place where # include appears. The file stdio.h contains the standard input/output routines. All preprocessor directives begin with pound sign # which must be entered in the first column. The # include line must not end with a semicolon. Only one preprocessor directive can appear in one line.

main( ) Function The next line is main( ). It defines what is known as a function in C. A C program is made up of many functions. The function main( ) is required in all C programs. It indicates the start of a C program. We will use main( ) at the beginning of all programs. Observe that main( ) is not followed by a comma or semicolon.

4 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Braces {.} Braces{..} enclose the computations carried out by main ( ). Each line in the program is a statement. Every statement is terminated by a semicolon. The statement itself can be written anywhere in a line. More than one statement can be on a line as a semicolon separates them. However it is a good practice to write one statement per line.

2.2 Declaration of Variables:


Variables: Variables are what make your programs zoom. Programming just can't get done without them. So if you haven't been introduced to variables yet, here you go. You can store values in variables. Each variable is identified by a variable name. Each variable has a variable type. Variable names start with a letter or underscore (_), followed by any number of letters, digits, or underscores. Uppercase is different from lowercase, so the names sam, Sam, and SAM specify three different variables. The variables are defined at the begining of the block.

How to Declare a Variable: A variable declaration serves three purposes: 1. It defines the name of the variable. 2. It defines the type of the variable (integer, real, character, etc.). 3. It gives the programmer a description of the variable.
int answer; /* the result of our expression */

1. 2. 3. 4.

The keyword int tells C that this variable contains an integer value. The variable name is answer. The semicolon (;) marks the end of the statement. The comment is used to define this variable for the programmer

Using a variable to store value:


#include <stdio.h> int main(void) { int salary; salary = 10000; printf("My salary is %d.", salary); return 0; }

O/P- My salary is 1000

5 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

2.1.7.Multiple declarations
#include <stdio.h> int main() { int m,y,d; m = 1; y = 2; d = 3; printf(" %d return 0; } %d %d \n",m, y, d);

C Keywords Keywords are the words whose meaning has already been explained to the C compiler. Keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. The keywords are also called Reserved words. There are 32 keywords available in C. Following is list of keywords in C. auto double break else case enum const float continue far default for do goto

if int long register return short signed

static struct typedef union unsigned void white

Interpreter Vs Compiler
Programming languages can be divided into two major categories: low level and high level. "Assembly language" and "machine language" are called low-level languages because they more than others "speak" the language the computer understands. On the other hand, C, C++, Pascal, BASIC, Visual Basic, Java, and COBOL are high-level languages because they require more manipulation by the computer, a process called compiling.

1) Compiler
A compiler is a special program that processes statements written in a particular programming language and converts them into machine language, a "binary program" or "code," that a computer processor uses. Typically, a programmer writes language statements in a language such as C, Pascal, or C++ one line at a time using a tool called an editor. The "edited" 6 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

file contains the source statements. The programmer then runs the appropriate language compiler (there may be several compilers for each language), specifying the name of the file that contains the source statements. When executing the file, the compiler first parses or analyzes all of the language statements syntactically in a sequential manner and then, in one or more successive passes, builds the output code, ensuring that statements that refer to other statements are referenced correctly in the final code. The code is linked to various libraries, which are common code sections found in many programs. The use of libraries helps keep redundant coding to a minimum. The compilation output is sometimes referred to as object code or an object module. (Note that the term "object" as used in this instance is not related to object-oriented programming. The object code as used here refers to machine code that the processor executes one instruction at a time.)

2) Interpreter
Interpreters translate code one line at time, executing each line as it is "translated," much the way a foreign language interpreter would translate a book, by translating one line at a time. Interpreters do generate binary code, but that code is never compiled into one program entity. Instead, the binary code is interpreted each and every time the program executes. Some examples of interpreted programs are BASIC, QBASIC, and Visual Basic (version 5 of which has both a compiler and interpreter). Where compiled programs can run on any computer, interpreted programs can only run on computers that also have the interpreter. Interpreters offer programmers some advantages that compilers do not. Interpreted languages are easier to learn than compiled languages, which is great for beginning programmers. An interpreter lets the programmer know immediately when and where problems exist in the code; compiled programs make the programmer wait until the program is complete.

2.2 C - Storage Classes:


A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. There are following storage classes which can be used in a C Program

auto register static extern

2.2.1 auto - Storage Class auto is the default storage class for all local variables.
{ int Count; auto int Month; }

7 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables. 2.2.2 register - Storage Class register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).
{ register int } Miles;

Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions. 2.2.3 static - Storage Class static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.
static int Count; int Road; { printf("%d\n", Road); }

static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in. static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.
void func(void); static count=10; /* Global variable - static is the default */ main() { while (count--) { func(); } }

8 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); } This will produce following result i i i i i i i i i i is is is is is is is is is is 6 and count is 9 7 and count is 8 8 and count is 7 9 and count is 6 10 and count is 5 11 and count is 4 12 and count is 3 13 and count is 2 14 and count is 1 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memoriese void as nothing. static variables are initialized to 0 automatically. Definition vs Declaration : Before proceeding, let us understand the difference between defintion and declaration of a variable or function. Definition means where a variable or function is defined in realityand actual memory is allocated for variable or function. Declaration means just giving a reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main() function. There is one more very important use for 'static'. Consider this bit of code.
char *func(void); main() { char *Text1; Text1 = func(); } char *func(void) { char Text2[10]="martin"; return(Text2); }

9 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify
static char Text[10]="martin";

The storage assigned to 'text2' will remain reserved for the duration if the program. 2.2.4 extern - Storage Class extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files. File 1: main.c
int count=5; main() { write_extern(); }

File 2: write.c
void write_extern(void); extern int count; void write_extern(void) { printf("count is %i\n", count); }

Here extern keyword is being used to declare count in another file. Now compile these two files as follows
gcc main.c write.c -o write

This fill produce write program which can be executed to produce result.

10 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

3 Concept of scalar Data Types


3.1 Data Type:
3.1.1.What is a data type: For each variable you have to attach some data type. The data type defines: 1. the amount of storage allocated to variables. 2. the values that they can accept. 3. the operations that can be performed on variables. 3.1.2.Introduction to Data Types 1. Data type determines how much storage space is allocated to variables. 2. Data type determines the permissible operations on variables. 3. The variables should be declared by specifying the data type. 1. There is a family of integer data types and floating-point data types. 2. Characters are stored internally as integers 3. Characters are interpreted according to the character set. 1. The most commonly used character set is ASCII. 2. In the ASCII character set, A is represented by the number 65.

3.1.3.C Numeric Data Types

Keyword char int short short int long unsigned char unsigned int unsigned short unsigned long float

Variable Type Character (or string) Integer Short integer Short integer Long integer Unsigned character Unsigned integer Unsigned short integer Unsigned long integer Single-precision floating-point (accurate to 7 digits)

Range -128 to 127 -32,768 to 32,767 -32,768 to 32,767 -32,768 to 32,767 -2,147,483,648 to 2,147,483,647 0 to 255 0 to 65,535 0 to 65,535 0 to 4,294,967,295 +/-3.4E10^38 to +/-3.4E10^38

11 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

double

Double-precision floating-point (accurate to 15 digits)

+/-1.7E10^308 to +/-1.7E10^308

C has really only four types of variables:


1. char 2. int 3. float 4. double

3.2 Other Data Types: 3.2.1 Bit: Each 1 or 0 is called a bit. 1. 2. 3. 4. 1. 2. 3. 4. 5. Number 1 is 01 in binary. Number 2 is 10 in binary. Number 3 is 11 in binary. Number 4 is 100 in binary. For data type char, 8 bits are allocated (1 byte = 8 bits). Using 8 bits, you can normally represent decimal numbers from 0 to 255 (0000 0000 to 1111 1111) With signed data type, the leftmost bit is the sign of the number. If the sign bit is 0, the number is positive, If it is 1, the number is negative.

1. The range of the number depends on the number of bytes allocated. 2. The range of the number also depends whether the number is signed. 3.2.2 Bits right and left shift:
#include <stdio.h> int main(void) { unsigned int original = 0xABC; unsigned int result = 0; unsigned int mask = 0xF; printf("\n original = %X", original); /* Insert first digit in result */ result |= original&mask; /* Get second digit */

12 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

original >>= 4; result <<= 4; result |= original&mask; /* Get third digit */ original >>= 4; result <<= 4; result |= original&mask; printf("\t result = %X\n", result); return 0; } O/P->original = ABC result = CBA

3.2.3 Using an enumeration type


#include <stdio.h> enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; int main() { enum months month; const char *monthName[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for ( month = JAN; month <= DEC; month++ ) { printf( "%2d%11s\n", month, monthName[ month ] ); } return 0; } O/P-> 1 January 2 February 3 March 4 April 5 May 6 June 7 July 8 August 9 September 10 October 11 November 12 December

3.2.3 Union 1. Union has members of different data types, but can hold data of only one member at a time. 2. The different members share the same memory location.

13 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

3. The total memory allocated to the union is equal to the maximum size of the member.
#include <stdio.h> union marks { float percent; char grade; }; int main ( ) { union marks student1; student1.percent = 98.5; printf( "Marks are %f address is %16lu\n", student1.percent, &student1.percent); student1.grade = 'A'; printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade); } O/P-> Marks are 98.500000 address is Grade is A address is 2293620 2293620

3.2.4 Constants Constant variables are just like normal variables in declaration but Values assigned to it will not change in Entire program life.
#include <stdio.h> main() { const int x = 20; const float PI = 3.14; printf("\nConstant values are %d and %.2f\n", x, PI); } O/P->Constant values are 20 and 3.14

3.2.5 Hexadecimal Numbers: 1. Hexadecimal numbers use base 16. 2. The characters used in hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. 3. You can print numbers in hexadecimal form by using the format "x".
#include <stdio.h> main() { int i = 65;

14 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("%x", i); }

3.2.6 Octal Numbers: Represent a number by using the octal number system. The octal number system that is, base 8. Use "%o" to print octal numbers.
#include <stdio.h> main() { int i = 65; printf("%o", i); } O/P->101

3.2.7 Register variable Register variable is for faster access. Register variable cannot be global variables.
#include <stdio.h> main() { register int i = 0; for( i=0;i<2;i++) { printf("value of i is %d\n",i); } } O/P->value of i is 0 value of i is 1

3.3 Type Cast or Conversion


3.3.1 Type Conversion 1. Type conversion occurs when the expression has data of mixed data types. 2. In type conversion, the data type is promoted from lower to higher. 3. The hierarchy of data types: double, float, long, int, short, char. Example : char c=`a`; int i=c;
15 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

3.3.2 Forced Conversion Forced conversion occurs when you are converting the value of the larger data type to the value of the smaller data type When floating points are converted to integers, truncation occurs.

#include <stdio.h> main() { double f1 = 12.23456; printf("%d \n", (int)f1); } O/P->12

3.3.3 Type Casting Type casting is used when you want to convert the value of a variable from one type to another. Type casting does not change the actual value of the variable.
#include <stdio.h> main() { double d1 = 1234.56; int i1=456; printf("the printf("the printf("the printf("the value value value value of of of of d1 d1 i1 i1 as as as as int without cast operator %d\n",d1); int with cast operator %d\n",(int)d1); double without cast operator %f\n",i1); double with cast operator %f\n",(double)i1);

i1 = 10; printf("effect i1 = 10; printf("effect i1 = 10; printf("effect i1 = 10; printf("effect } O/P-> the value the value the value the value effect of effect of effect of effect of

of multiple unary operator %f\n",(double)++i1); of multiple unary operator %f\n",(double)- ++i1); of multiple unary operator %f\n",(double)- -i1); of multiple unary operator %f\n",(double)-i1++);

of d1 as of d1 as of i1 as of i1 as multiple multiple multiple multiple

int without cast operator 1889785610 int with cast operator 1234 double without cast operator 1234.559570 double with cast operator 456.000000 unary operator 11.000000 unary operator -11.000000 unary operator 10.000000 unary operator -10.000000

16 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

3.3.4 Data type cast: from int to float


#include <stdio.h> int main(void) { int count = 110; long sum = 10L; float average = 0.0f; average = (float)sum/count; printf("\nAverage of the ten numbers entered is: %f\n", average); return 0; } O/P->Average of the ten numbers entered is: 0.090909

17 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

4 Expressing Algorithm Sequence


4.1 What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.

Arithmetic Operators Logical (or Relational) Operators Bitwise Operators Assignment Operators Misc Operators

4.1.1 Arithmetic Operators: Here are following arithmetic operators supported by C language: Assume variable A holds 10 and variable B holds 20 then:
Operator + * / Description Adds two operands Subtracts second operand from the first Multiply both operands Divide numerator by denumerator Modulus Operator and remainder of after an integer division Increment operator, increases integer value by one A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 Example

B % A will give 0

++

A++ will give 11

--

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

18 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Example:
main() { int a = 21; int b = 10; int c ; c = a + b; printf("Line c = a - b; printf("Line c = a * b; printf("Line c = a / b; printf("Line c = a % b; printf("Line c = a++; printf("Line c = a--; printf("Line } 1 - Value of c is %d\n", c ); 2 - Value of c is %d\n", c ); 3 - Value of c is %d\n", c ); 4 - Value of c is %d\n", c ); 5 - Value of c is %d\n", c ); 6 - Value of c is %d\n", c ); 7 - Value of c is %d\n", c );

O/P
Line Line Line Line Line Line Line 1 2 3 4 5 6 7 Value Value Value Value Value Value Value of of of of of of of c c c c c c c is is is is is is is 31 11 210 2 1 21 22

4.1.2 Logical (or Relational) Operators:

There are following logical operators supported by C language Assume variable A holds 10 and variable B holds 20 then:
Operator Description Checks if the value of two operands is equal or not, if yes then condition becomes true. Checks if the value of two operands is equal or not, if values are not equal then condition Example

==

(A == B) is not true.

!=

(A != B) is true.

19 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

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

>

(A > B) is not true.

<

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if (A >= B) is not true. yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if (A <= B) is true. yes then condition becomes true. Called Logical AND operator. If both the operands are non zero then then condition becomes true. Called Logical OR Operator. If any of the two operands is non zero then then condition becomes 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.

||

(A || B) is true.

!(A && B) is false.

Example:
main() { int a = 21; int b = 10; int c ;

20 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

if( a == b ) { printf("Line 1 - a is equal to b\n" ); } else { printf("Line 1 - a is not equal to b\n" ); } if ( a < b ) { printf("Line 2 - a is less than b\n" ); } else { printf("Line 2 - a is not less than b\n" ); } if ( a > b ) { printf("Line 3 - a is greater than b\n" ); } else { printf("Line 3 - a is not greater than b\n" ); } /* Lets change value of a and b */ a = 5; b = 20; if ( a <= b ) { printf("Line 4 - a is either less than or euqal to b\n" ); } if ( b >= a ) { printf("Line 5 - b is either greater than or equal to b\n" ); } if ( a && b ) { printf("Line 6 - Condition is true\n" ); } if ( a || b ) { printf("Line 7 - Condition is true\n" ); } /* Again lets change the value of a and b */ a = 0; b = 10; if ( a && b ) { printf("Line 8 - Condition is true\n" ); } else { printf("Line 8 - Condition is not true\n" ); } if ( !(a && b) ) {

21 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("Line 9 - Condition is true\n" ); } }

This will produce following result

Line Line Line Line Line Line Line Line Line

1 2 3 4 5 6 7 8 9

a is not equal to b a is not less than b a is greater than b a is either less than or euqal to b b is either greater than or equal to b Condition is true Condition is true Condition is not true Condition is true

4.1.3 Bitwise Operators: Bitwise operator works on bits and perform bit by bit operation. Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ----------------A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 There are following Bitwise operators supported by C language
Operator Description Binary AND Operator copies a bit to the result if it exists in both operands. Example

&

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

22 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Binary OR Operator copies a bit if it exists in eather operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

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

(A ^ B) will give 49 which is 0011 0001

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

<<

A << 2 will give 240 which is 1111 0000

>>

Binary Right Shift Operator. The left operands value is moved right by the number A >> 2 will give 15 which is 0000 1111 of bits specified by the right operand.

Example:
main() { unsigned int a = 60; unsigned int b = 13; int c = 0; /* 60 = 0011 1100 */ /* 13 = 0000 1101 */

c = a & b; /* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c ); c = a | b; /* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c ); c = a << 2; /* 240 = 1111 0000 */ printf("Line 5 - Value of c is %d\n", c ); c = a >> 2; /* 15 = 0000 1111 */ printf("Line 6 - Value of c is %d\n", c ); }

23 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

This will produce following result

Line Line Line Line Line Line

1 2 3 4 5 6

Value Value Value Value Value Value

of of of of of of

c c c c c c

is is is is is is

12 61 49 -61 240 15

4.1.4 Assignment Operators: There are following assignment operators supported by C language:
Operator Description Simple assignment operator, Assigns values from right side operands to left side operand Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example

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

+=

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

-=

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

*=

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

/=

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

%=

Modulus AND assignment operator, It

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

24 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

takes modulus using two operands and assign the result to left operand <<= >>= &= Left shift AND assignment operator Right shift AND assignment operator Bitwise AND assignment operator bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator C <<= 2 is same as C = C << 2 C >>= 2 is same as C = C >> 2 C &= 2 is same as C = C & 2

^=

C ^= 2 is same as C = C ^ 2

|= Example:

C |= 2 is same as C = C | 2

main() { int a = 21; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c );

c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); c &= 2;

25 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); }

This will produce following result

Line Line Line Line Line Line Line Line Line Line Line

1 - = Operator Example, Value of c = 21 2 - += Operator Example, Value of c = 42 3 - -= Operator Example, Value of c = 21 4 - *= Operator Example, Value of c = 441 5 - /= Operator Example, Value of c = 21 6 - %= Operator Example, Value of c = 11 7 - <<= Operator Example, Value of c = 44 8 - >>= Operator Example, Value of c = 11 9 - &= Operator Example, Value of c = 2 10 - ^= Operator Example, Value of c = 0 11 - |= Operator Example, Value of c = 2

4.1.5 Misc Operators There are few other operators supported by C Language.
Operator sizeof() & * Description Returns the size of an variable. Returns the address of an variable. Pointer to a variable. Example sizeof(a), where a is interger, will return 4. &a; will give actaul address of the variable. *a; will pointer to a variable. If Condition is true ? Then value X : Otherwise value Y

?:

Conditional Expression

Operators Categories: All the operators we have discussed above can be categorized into following categories:
26 Mob-8080373934

Atul Sirs Private Tuition (Engg)


Structured Programming (Sem II)

Postfix operators, which follow a single operand. Unary prefix operators, which precede a single operand. Binary operators, which take two operands and perform a variety of arithmetic and logical operations. The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression. Assignment operators, which assign a value to a variable. The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

4.1.6 Precedence of C Operators: 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.
Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND () [] -> . ++ - + - ! ~ ++ - - (type) * & sizeof */% +<< >> < <= > >= == != & Operator Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right

27 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma

^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= ,

Left to right Left to right Left to right Left to right Right to left Right to left Left to right

4.2 C - Input and Output


Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of builtin functions to read given input and feed it to the program as per requirement. Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data. 4.2.1 printf() function: This is one of the most frequently used functions in C for output. the printf function is usually of the form: printf(string,variable,variable,variable...) where the ... means you can carry on writing a list of variables separated by commas as long as you want to. The string is all-important because it specifies the type of each variable in the list and how you want it printed. The string is usually called the control string or the format string. The way that this works is that printf scans the string from left to right and prints on the screen, or any suitable output device, any characters it encounters - except when it reaches a % character. The % character is a signal that what follows it is a specification for how the next variable in the list of variables should be printed. printf uses this information to convert and format the value that was passed to the function by the variable and then moves on to process the rest of the control string and anymore variables it might specify. For example:

28 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("Hello World"); only has a control string and, as this contains no % characters it results in Hello World being displayed and doesn't need to display any variable values. The specifier %d means convert the next value to a signed decimal integer and so: printf("Total = %d",total); will print Total = and then the value passed by &total as a decimal integer.

The % Format Specifiers :


The % specifiers that you can use in ANSI C are: Usual variable type Display %c char single character %d (%i) int signed integer %e (%E) float or double exponential format %f float or double signed decimal %o int unsigned octal value %p pointer address stored in pointer %s array of char sequence of characters %u int unsigned decimal %x (%X) int unsigned hex value Try following program to understand printf() function.
#include <stdio.h> main() { int dec = 5; char str[] = "abc"; char ch = 's'; float pi = 3.14; printf("%d %s %f %c\n", dec, str, pi, } ch);

29 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

The output of the above would be:


5 abc 3.140000 c

Finally there are the control codes: \b backspace \f formfeed \n new line \r carriage return \t horizontal tab \' single quote \0 null If you include any of these in the control string then the corresponding ASCII control code is sent to the screen, or output device, which should produce the effect listed. In most cases you only need to remember \n for new line. 4.2.2 scanf() function: This is the function which can be used to to read an input from the command line. The scanf function works in much the same way as the printf. That is it has the general form: scanf(control string,variable,variable,...) In this case the control string specifies how strings of characters, usually typed on the keyboard, should be converted into values and stored in the listed variables. scanf("%d %d",&i,&j); will read in two integer values into i and j. The integer values can be typed on the same line or on different lines as long as there is at least one white space character between them. Example:
#include<stdio.h> int main() { int myvariable;

30 Mob-8080373934

Atul Sirs Private Tuition (Engg)


printf("Enter a number:"); scanf("%d",&myvariable); printf("%d",myvariable); return 0; }

Structured Programming (Sem II)

See, when we used scanf we first declared what the variables type was "%d" for int ,"%f" for float ,"%e" for a scientific notation (1e10) ,"%c" for char , "%s" for strings.

4.3 The Standard Library Functions


Some of the "commands" in C are not really "commands" at all but are functions. For example, we have been using printf and scanf to do input and output, and we have used rand to generate random numbers - all three are functions. The most common libraries and a brief description of the most useful functions they contain follows:
1. stdio.h: I/O functions: 1. getchar()- returns the next character typed on the keyboard. 2. putchar()- outputs a single character to the screen. 3. printf() -as previously described 4. scanf()- as previously described 2. string.h: String functions 1. strcat() -concatenates a copy of str2 to str1 2. strcmp()- compares two strings 3. strcpy() -copys contents of str2 to str1 3. ctype.h: Character functions 1. isdigit() -returns non-0 if arg is digit 0 to 9 2. isalpha() -returns non-0 if arg is a letter of the alphabet 3. isalnum() -returns non-0 if arg is a letter or digit 4. islower()- returns non-0 if arg is lowercase letter 5. isupper() -returns non-0 if arg is uppercase letter 4. math.h: Mathematics functions 1. acos() -returns arc cosine of arg 2. asin()- returns arc sine of arg 3. atan()- returns arc tangent of arg 4. cos()- returns cosine of arg 5. exp()- returns natural logarithim e 6. fabs()- returns absolute value of num 7. sqrt()- returns square root of num 5. time.h: Time and Date functions

31 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

1. time()- returns current calender time of system 2. difftime()- returns difference in secs between two times 3. clock() -returns number of system clock cycles since program execution 6. stdlib.h:Miscellaneous functions 1. malloc()- provides dynamic memory allocation, covered in future sections 2. rand() -as already described previously 3. srand() -used to set the starting point for rand()

4.4 Assignment statement


Once you've declared a variable you can use it, but not until it has been declared - attempts to use a variable that has not been defined will cause a compiler error. Using a variable means storing something in it. You can store a value in a variable using: name = value; For example: a=10; stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actually very useful! Who wants to store a known value like 10 in a variable so you can use it later? It is 10, always was 10 and always will be 10. What makes variables useful is that you can use them to store the result of some arithmetic. Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C would use these operations on two float variables a and b. add a+b subtract a-b multiply a*b divide a/b Note that we have used the following characters from C's character set:
32 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

+ for add - for subtract * for multiply / for divide BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation? a=10/3 The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader to find out the answer for a of type char. Two points to note from the above calculation:
1. C ignores fractions when doing integer division! 2. When doing float calculations integers will be converted into float.

33 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

5 Expressing Algorithm Iteration and Selection


5.1 Loops:
In every programming language, thus also in the C programming language, there are circumstances were you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf functions, but it is easier to use a loop. The only thing you have to do is to setup a loop that executes the same printf function ten times. There are three basic types of loops which are:

for loop while loop do while loop

5.1.1 for Loop: The for loop loops from one number to another number and increases by a specified value each time. A for loop has three parts:

The setup The exit condition for which the loop finishes The part that loops, which is the statements that are repeated

Syntax for for Loop: for(initialize counter variable ; condition ; increment/decrement the counter variable) { Statement1; ... Statement n; }

34 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Look at the example below:

#include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; }

Note: A single instruction can be placed behind the for loop without the curly brackets. Lets look at the for loop from the example: We first start by setting the variable i to 0. This is where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++). In the example we used i++ which is the same as using i = i + 1. This is called incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i--. It is also possible to use ++i or --i. The difference is is that with ++i (prefix incrementing) the one is added before the for loop tests if i < 10. With i++ (postfix incrementing) the one is added after the test i < 10. In case of a for loop this make no difference, but in while loop test it makes a difference. But before we look at a postfix and prefix increment while loop example, we first look at the while loop. 5.1.2 while Loop:
In While looping statement allows a number of lines represent until the condition is satisfied. The while loop can be used if you dont know how many times a loop must run. Syntax:

while( condition) { Statement1; ... Statement n; }


35 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Here is an example:
#include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; while ( counter < howmuch) { counter++; printf("%d\n", counter); } return 0; }

Lets take a look at the example: First you must always initialize the counter before the while loop starts ( counter = 1). Then the while loop will run if the variable counter is smaller then the variable howmuch. If the input is ten, then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside the loop (counter++). If you forget this the loop becomes infinitive. As said before (after the for loop example) it makes a difference if prefix incrementing (++i) or postfix incrementing (i++) is used with while loop. Take a look at the following postfix and prefix increment while loop example:
#include<stdio.h> int main(void) { int i; i = 0; while(i++ < 5) { printf("%d\n", i); } printf("\n"); i = 0; while(++i < 5) { printf("%d\n", i); } return 0; }

36 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

The output of the postfix and prefix increment example will look like this:
1 2 3 4 5 1 2 3 4

i++ will increment the value of i, but is using the pre-incremented value to test against < 5. Thats why we get 5 numbers. ++i will increment the value of i, but is using the incremented value to test against < 5. Thats why we get 4 numbers. 5.1.3 do-while Loop: The do while loop is almost the same as the while loop. In DO WHILE LOOP first execute the statements then it checks the condition. Syntax: The do while loop has the following form:
do { do something; } while (expression);

Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:
#include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; do { counter++; printf("%d\n", counter); } while ( counter < howmuch);

37 Mob-8080373934

Atul Sirs Private Tuition (Engg)


return 0; } Note: There is a semi-colon behind the while line.

Structured Programming (Sem II)

5.1.4 Break and continue: To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop because a condition has been met other than the loop end condition. Take a look at the following example:
#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; if ( i == 10) break; } return 0; }

In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i equals ten the while loop must stop (break). With continue; it is possible to skip the rest of the commands in the current loop and start from the top again. (the loop variable must still be incremented). Take a look at the example below:
#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to see\n"); } return 0; }

In the example above, the printf function is never called because of the continue;.
38 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

5.1.4 goto: goto is a unconditional jump statement. Syntax : goto label; so we have to use the goto carefully inside a conditional statement. Example : #include<stdio.h> #include<conio.h> void main() { int a,b; printf("Enter 2 nos A and B one by one : "); scanf("%d%d",&a,&b); if(a>b) { goto first; } else { goto second; } first: printf("\n A is greater.."); goto g; second: printf("\n B is greater.."); g: getch(); } O/P Enter 2 nos A and B one by one : 12 34 B is greater..
39 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

5.2 The if and switch Statement:


Boolean Operators
Before we can take a look at test conditions we have to know what Boolean operators are. They are called Boolean operators because they give you either true or false when you use them to test a condition. The greater than sign > for instance is a Boolean operator. In the table below you see all the Boolean operators:
== ! != > < >= <= && || Equal Not Not equal Greater than Less than Greater than or equal Less than or equal And Or

The if statement
The if statement can be used to test conditions so that we can alter the flow of a program. In other words: if a specific statement is true, execute this instruction. If not true, execute this instruction. Syntax: if(condition) { //code }
40 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

So lets take a look at an example:


#include<stdio.h> int main() { int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 ) printf("Is equal\n"); return 0; }

In the example above the user can input a number. The number is stored in the variable mynumber. Now take a look at the if statement: if the number stored in the variable mynumber is equal to ten, then print is equal on the screen. Simple, isnt it. If the number is not equal to ten, then nothing gets printed. Now take another look at the if statement: look at the placement of the semi-colon. As you can see there is no semi-colon behind the if statement. If there is just one instruction (if the statement is true), you can place it after the if statement (with an indentation). Are multiple instructions necessary then you will have to use curly brackets, like so:
if ( mynumber == 10) { printf("is equal\n"); printf("closing program\n"); }

Now we like to also print something if the if statement is not equal. We could do this by adding another if statement but there is an easier / better way. Which is using the so called else statement with the if statement.
#include<stdio.h> int main() { int mynumber; scanf("%d",&mynumber); if ( mynumber == 10 ) {

41 Mob-8080373934

Atul Sirs Private Tuition (Engg)


printf("Is equal\n"); printf("Closing program\n"); } else { printf("Not equal\n"); printf("Closing program\n"); } return 0; }

Structured Programming (Sem II)

Note: Take a look at the placement of the curly brackets and how the indentations are placed. This is all done to make reading easier and to make less mistakes in large programs.

Nested if statements
If you use an if statement in an if statement it is called nesting. Nesting if statements can make a program very complex, but sometimes there is no other way. So use it wisely. Syntax: if(condition) { //code } else if(condition) { //code } else { //code }

42 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Take a look at a nested if statement example below:


#include<stdio.h> int main() { int grade; scanf("%d",&grade); if ( grade <= 10 ) { printf("YOU DID NOT STUDY.\n"); printf("YOU FAILED ! \n"); } else { if ( grade < 60 ) { printf("YOU PASSED ! \n"); } } return 0; }

Note: Again take a look at the placing of the curly brackets and the placing of the indentations. So lets walk through the example above: If the grade is equal or below ten, you did not study. If the grade is above ten, the program will go into the else statement. In the else statement there is another if statement (this is nesting). This if statement checks the grade again. If the grade is below sixty, you must study harder. In the else statement from this if statement there is another if statement. It checks whether the grade is above or equal to sixty. If it is, you passed the test.

Multiple condition testing


It is possible to test two or more conditions at once in an if statement with the use of the AND (&&) operator. Example:
if ( a > 10 && b > 20 && c < 10 )

If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So all three conditions must be true, before something happens. With the OR ( || ) operator you can test if one of two conditions are true. Example:
if ( a = 10 || b < 20 )

43 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

If a equals ten or b is smaller then twenty then do something. So if a or b is true, something happens.

The switch statement


The switch statement is almost the same as an if statement. The switch statement can have many conditions. You start the switch statement with a condition. If one of the variable equals the condition, the instructions are executed. It is also possible to add a default. If none of the variable equals the condition the default will be executed. Syntax: switch(expression) { case condition1: //code case condition 2: //code ... case condition n: //code default: //code } See the example below:
#include<stdio.h> int main() { char myinput; printf("Which option will you choose:\n"); printf("a) Program 1 \n"); printf("b) Program 2 \n"); scanf("%c", &myinput); switch (myinput) { case 'a': printf("Run program 1\n"); break; case 'b': {

44 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)


printf("Run program 2\n"); printf("Please Wait\n"); break;

} default: printf("Invalid choice\n"); break; } return 0; }

O/P
Which option will you choose: a Run program 1

45 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

6 Function in C
6.1 Defining Function in C :
Most languages allow you to create functions of some sort. Functions are used to break up large programs into named sections. You have already been using a function which is the main function. Functions are often used when the same piece of code has to run multiple times. A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required. Function groups a number of program statements into a unit and gives it a name. This unit can be invoked from other parts of a program. A computer program cannot handle all the tasks by it self. Instead its requests other program like entities called functions in C to get its tasks done. A function is a self contained block of statements that perform a coherent task of same kind The name of the function is unique in a C Program and is Global. It means that a function can be accessed from any location within a C Program. We pass information to the function called arguments specified when the function is called. And the function either returns some value to the point it was called from or returns nothing. We can divide a long C program into small blocks which can perform a certain task. A function is a self contained block of statements that perform a coherent task of same kind.

Structure of a Function
There are two main parts of the function. The function header and the function body.
int sum(int x, int y) { int ans = 0; ans = x + y; return ans }

//holds the answer that will be returned //calculate the sum //return the answer

Function Header
In the first line of the above code
int sum(int x, int y)

It has three main parts


1. The name of the function i.e. sum 2. The parameters of the function enclosed in paranthesis 3. Return value type i.e. int 46 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Function Body
What ever is written with in { } in the above example is the body of the function.

Simple Functions
Our first example demonstrates a simple function those purpose is to print a line of 45 asterisks.The example program generates a table , and lines of asterisks are used to make the table more readable. Heres the listing for Table:
// table .cpp // demonstrates simpole function # include using namespace std; void starline( ); into main () { starline ( ); cout << "Data type Range" << endl; starline ( ); cout << "char -128 to 127 " << endl << "short -32 ,768 to 32,767"<< endl << "int system independent: << endl << " long q-2,147,483,648 to 2,147,483,647" << endl; starline ( ); return 0; } //"""""""""""""""""""""""".. //starline ( ) // function defintion void starline ( ) { for(into j=0;j<45; j++) cout << "*" ; cout << endl; } The output from the program looks like this ************************************* Data type Range ************************************* Char -128 to 127 Short -32,768 to 32,767 Into system dependent Double -2,147,483,648 to 2,147,483,647 *************************************

47 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Why we use Functions


The most important reason to use functions is to aid in the conceptual organization of a program. Another reason to use functions is to reduce program size. Any sequence of instructions that appears in program more than once is a candidate for being made into a function. The functions code is stored in only one place in memory, even though the function is executed many times in the course of the program.

Two reasons
1. Writing functions avoids rewriting the same code over and over. Suppose that there is a section of code in a program that calculates area of a triangle. If, later in the program we want to calculate the area of a different triangle we wont like to write the same instructions all over again. Instead we would prefer to jump to a section of code that calculates area and then jump back to the place from where you left off. This section of code is nothing but a function. 2. Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a program can be divided in to separate activities, and each activity placed in a different function, then each could be written and checked more or less independently. Separating the code in to modular functions also makes the pro-gram easier to design and understand.

Function Declaration
Just as you cant use a variable without first telling the compler what it is, you also cant use a funciotns without teling the compiler about it, There are two ways to do this . The approach we show here ist o declare the funtion before it is called. The other approach is to define it before its called. ; well examine that next.) in the Table program, the functions starline() is declared in the line.
Void starline ( );

The declaration tells the compiler that at some later point we plan to present a function called starline. The keyword void specifies that the function has no return value, and the empty parentheses indicate that it takes no arguments. Notice that the funtois declarations is terminated with a semicolon It is a complete statement in itself. Function declarations are also called prototypes, since they provide a model or blueprint for the function. They tell the compiler, a function that looks like this is coming up later in the program, so its all right if you see references to it before you see the function itself.

48 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Calling the Function


The function is called (or invoked) three times from main (). Each of the three calls look like this:
Starline():

This is all we need to call a function name,followed by parentheses. The syntax of the call is very similar to that of declaration, except that the return type is not used. A semicolon terminates the call. Executing the call statement causes the function to execute; that is, control is transferred to the function, the statement in the function definition are executed, and then control returns to the statement following the function call.

Function Definition
Finally, we come to the functions its self, which is referred to as the functions definition, The definition contains the actual code for the function. Heres the definition for starline( ) .
void starline ( ) { for ( intj=0, j < 45; j++ ) cout << "*" ; cout << endl; }

The definition consists of a line called the decelerator, followed by the function body , The function body is composed of the statements that make up the function, delimited by braces. The decelerator must agree with the declaration: It must use the same function name, have the same argument types in the same order( if there are arguments), and have the same return type. Notice that a semicolon does not terminate the declarator. Figure shows the syntax of the function declaration, function call, and function definition. When the function is called, control is transferred to the first statement in the functions body. The other statements in the function body are then executed, and when the closing brace is encountered, control returns to the calling program.

There are basically two types of functions


1. Library functions Ex. printf ( ), scanf ( ) etc. 2. User defined function e.g the function message mentioned above. The following point must be noted about functions (i) C program is a collection of one or more functions (ii) A function gets called when the function name is followed by a semicolon for e.g.

49 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

main ( ) { message ( ); } 3. Function is defined when function name is followed by a pair of braces in which one or more statements may be present for e.g. message ( ) { statement 1; statement2; statement 3; } 4. Any function can be called from any other function even main ( ) can be called from other functions. for e.g. main ( ) { message ( ); } message ( ) { printf ( \n Hello); main ( ); } 5. A function can be called any number of times for eg.

50 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

main () { message ( ); message ( ); } message ( ) { printf (\n Hello); } 6. The order in which the functions are defined in a program and the order in which they get called need not necessarily be same for e.g. main ( ); { message 1 ( ); message 2 ( ); } message 2 ( ) { printf (\n I am learning C); } message 1 ( ) { printf ( \n Hello ); }
51 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

7. A function can call itself such a process as called recursion. 8. A function can be called from other function, but a function cannot be defined in an-other function. These the following program code would be wrong, since Argentina is being defined inside another function main ( ). main ( ) { printf (\n I am in main); argentina ( ) { printf {\n I am in argentina); } } 9. Any C program contains at least one function. 10. If a program contains only one function, it must be main( ). 11. In a C program if there are more than one functional present then one of these func-tional must be main( ) because program execution always begins with main( ). 12. There is no limit on the number of functions that might be present in a C program. 13. Each function in a program is called in the sequence specified by the function calls in main( ) 14. After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends. Functions declaration and prototypes Any function by default returns an int value. If we desire that a function should return a value other than an int, then it is necessary to explicitly mention so in the calling functions as well as in the called function. for e.g
main ( ) { float a,b, printf ("\n Enter any number"); scanf ("\% f", &a ); b = square (a) printf ("\n square of % f is % f", a,b); } square (float X) { float y; Y = x * x; return (y); }

52 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

the sample run of this program is Enter any number 2.5 square of 2.5 is 6.000000 Here 6 is not a square of 2.5 this happened because any C function, by default, always returns an integer value. The following program segment illustrates how to make square ( ) capable of returning a float value.
main ( ) { float square ( ); float a, b; printf ("\n Enter any number "); scanf ("%f" &a); b = square (a); printf ("\n square of % f is % f, " a, b); } float square (float x) { float y; y= x *x; return ( y); }

sample run Enter any number 2.5 square of 2.5 is 6.2500000

PASSING ARGUMENTS TO FUNCTION


An argument is a piece of data (an into value, for exp) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.

PASSING CONSTANTS
As an exp, lets suppose we decide that the starline ( ) function in the last exp is too rigid. Instead of a function that always prints 45 asterisks, we want a function that will print any character any number of times Heres a program, TABLEARG, that incorporates just such a function. We use arguments to pass the character to be printed and the number of times to print it .
// tablearg. Cpp // demonstrates funciotn arguments # include < iostream> using namespace std; void repchar(char, int); //function declaration in main ( ) { repchar(" " " , 43); cout << " Data type Range" <, endl; repchar ( "=", 23); //call to function cout << " char -128 to 128" < endl

53 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

<< "short -32,768 to 32,767" < endl << " int system dependent " << endl << " double -2, 147,483,648 to 2,147,483,647" << endl; repchar("-" , 43); return 0; }//""""""""""""""""""""""""""". //repchar ( ) // funtion definiton void repchar ( char ch , int n ) { for ( into j=0; j<n; j++) //function body cout < ch; cout << endl; }

The new function is called repchar ( ), Its declaration looks like this Void repchar ( char, int); // declaration specifies data types The items in the parentheses are the data types of the argument that will be sent to repchar( ): char and int. In a function call, specific values constants in this case are inserted in the appropriate place in the parentheses: Repchar(-, 43); // function call specifies actual values This statement instructs repchar ( ) to print a line of 43 dashes. The values supplied in the call must be of the types specified in the declaration: the first argument, the - character , must be of type[ char; and the second arguments, the number 43 must be of type int. The types in the definition must also agree. The next call to repchar ( ). Repchar (= , 23); Tells it to print a line of 23 equal signs. The third call again prints 43 dashes. Heres the output form TABLEARG. """""""""""""" data type Range =============== char -128 to 127 short -32,768 to 32,767
54 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

int system dependant long -2,147,483,648to 2,147,483,647

The calling program supplies arguments such as - and 43 ,to the function. The variables used within the functions to hold the argument values are called parameters; in repchar() the are ch and n.These decelerator names ch and n, are used in the functions as they were normal variables. Placing them in the decelerators is equivalent to defining them with the statements like Char ch; Int n;l When the function is called, its parameters are automatically initialized to the values passed by the calling program.

PASSING VARIABLES
In the tablearg example the arguments were constants - 43,and so on. Lets look at an example where variables, instead of constants ,are passed as arguments. This program,VARARG,incorporates the same repchar()function as did tablearg,but let the user specify the character and the number of times it should be repeated.

//vararg.cpp //demonstrates variable arguments # include <iostream> using namespace std; void repchar(char,int); int main() { char chin; int nin; cout<<"enter a character:"; cin>>nin; cout<<"enter a number of times to repeat it:"; cin>>nin; repchar (chin,nin); return 0; } //""""""""""""""""""""""""""" //repchar () //function definition void repchar(char ch,int n) {

55 Mob-8080373934

Atul Sirs Private Tuition (Engg)


for(int j=0,j<n;j++) cout<<ch; cout<<end1; }

Structured Programming (Sem II)

Here is some sample interaction with vararg Enter a character:+ Enter number of times to repeat it:20 ++++++++++++++++ Here chin nd nin in main ()are used as arguments to repchar(): rephar()(chin,nin); // function call The data types of variables used as arguments must match those specified in the function declaration and definition, just as they must for constant. That is chin must be a char and nin must be an int.

RETURNING VALUES FROM FUNCTIONS


When a function completes its execution, it can return a single value to the calling program. Usually this return value consists of an answer to the problem the function has solved. The next example demonstrates a function that returns a weight in kg after being given a weight in ponds.
//convert.cpp //demonstrates return values, converts a pound to kg #include <iostream> using namespace std; float lbstokg(float); int main() { float lbs,kgs; cout<<"enter your weight in pounds:"; cin>>lbs; kgs=lbstokg(lbs); cout<<"your weight in kg is "<<kgs<<end1; return 0; } //""""""""""""""""".. //lbstokg() //converts pounds to kg float lbstokg(float pounds) { float kg=0.453592*pounds;

56 Mob-8080373934

Atul Sirs Private Tuition (Engg)


return kg; }

Structured Programming (Sem II)

When a function returns a value. The data type of this value must be specified. The function declaration does this by placing the data types, float in this case, before the function name in the declaration and the definition. Functions in earlier program examples returned no value, so the return type was void. In the above function lbstokg() returns type float, so the declaration is
Float lbstokg(float);

The first float specifies the return type. The float in parentheses s specifies that an argument to be passed to lbstokg() is also of type float.

CALL BY VALUE
In the preceding examples we have seen that whenever we called a function we have always passed the values of variables to the called function. Such function calls are called calls by value by this what it meant is that on calling a function we are passing values of variables to it. The example of call by value are shown below ;
sum = calsum (a, b, c); f = factr (a);

In this method the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual argument in the calling function. The following program illustrates this:
main ( ) { int a = 10, b=20; swapy (a,b); printf ("\na = % d b = % d", a,b); } swapy (int x, int y) { int t; t = x; x = y; y = t; printf ( "\n x = % d y = % d" , x, y); }

The output of the above program would be; x = 20 y = 10 a =10 b =20

CALL BY REFERENCE
In the second method the addresses of actual arguments in the calling function are copied in to formal arguments of the called function. This means that using these addresses we would have an

57 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

access to the actual arguments and hence we would be able to manipulate them the following program illustrates this.
main ( ) { int a = 10, b =20, swapv (&a, &b); printf ("\n a = %d b= %d", a, b); } swapr (int **, int * y) { int t; t = *x *x = *y; *y = t; }

The output of the above program would be a = 20 b =10

More on Function:
In this C programming language tutorial we will talk some more about functions. We will take a look at command-line parameters and function prototypes.

Command-line parameters
In some cases you want to give a parameter at the start of a program. For example:
# myprogram -i

The program myprogram will start and something extra will be done because of the commandline parameter -i (What it will do is up to you, this is just an example). Now lets make a program that will print the words that are typed behind the program at execution time. (Compile the program with the name myprogram). Here is the example:
#include<stdio.h> int main(int argc, char *argv[]) { int x; printf("%d\n",argc); for (x=0; x < argc; x++) printf("%s\n",argv[x]); return 0;

58 Mob-8080373934

Atul Sirs Private Tuition (Engg)


}

Structured Programming (Sem II)

After compiling the program myprogram start it as follows:


# myprogram aa bb cc dd

In this code, the main program accepts two parameters, argc and argv. The argv parameter is an array of pointers to a string that contains the parameters entered when the program was invoked at command line. (Pointers will be explained in a later tutorial, for now it is enough to know that it points to an address in memory where the parameters are stored). The argc integer contains a count of the number of parameters. (In this case four). First the program will print the number of parameters given when the program was invoked (stored in argc). This number will be used in a for loop. In this case it will print four times. The second printf statement will print the parameters given when the program was invoked, one by one. Try it! Command-line parameters can be used for many things.

Function prototypes
A function prototype declares the function name, its parameters, and its return type to the rest of the program. This is done before a function is declared. (In most cases at the beginning of a program). To understand why function prototypes are useful, try the following program:
#include<stdio.h> void main() { printf("%d\n",Add(3)); /* <- There is the error ! */ } int Add(int a, int b) { return a + b; }

Note: just one parameter when the function is called. (Not a typo). The example above will be compiled on many of the compilers. They just give some warning, because the function Add() needs two parameters as input, not one. The result of this program cannot be foreseen. It works because many C compilers do not check for parameters matching either in type or count. The result is that you will spend a lot of time debugging programs, because you made a mistake of passing on to many or too few parameters to a function.
59 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

To solve this problem you can make use of function prototypes. If you use prototypes, C checks the types and count of the parameter list. Try the next example:
#include<stdio.h> int Add (int,int); /* function prototype for Add */ void main() { printf("%d\n",add(3)); /* <- There is the error ! */ } int Add(int a, int b) { return a + b; }

When you try to compile this program, the compiler will flag an error on the printf statement. So in the future use function prototypes for every function you declare. It will save you a lot of time!

Recursive Function:
1. A recursive function is a function which calls itself. 2. The speed of a recursive program is slower because of stack overheads. (This attribute is evident if you run above C program.) 3. A recursive function must have recursive conditions, terminating conditions, and recursive expressions.

Calculating factorial value using recursion


To understand how recursion works lets have another popular example of recursion. In this example we will calculate the factorial of n numbers. The factorial of n numbers is expressed as a series of repetitive multiplication as shown below: Factorial of n = n(n-1)(n-2)1. Example : Factiorial of 5 = 5x4x3x2x1 =120
? 60 Mob-8080373934

Atul Sirs Private Tuition (Engg)


#include<stdio.h> #include<conio.h> int factorial(int); int factorial (int i) { int f; if(i==1) return 1; else f = i* factorial (i-1); return f; }

Structured Programming (Sem II)

void main() { int x; clrscr(); printf("Enter any number to calculate factorial :"); scanf("%d",&x); printf("\nFactorial : %d", factorial (x)); getch(); }

So from line no. 6 14 is a user defined recursive function factorial that calculates factorial of any given number. This function accepts integer type argument/parameter and return integer value.

Lets see how line no. 12 exactly works. Suppose value of i=5, since i is not equal to 1, the statement: f = i* factorial (i-1); will be executed with i=5 i.e.
61 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

f = 5* factorial (5-1); will be evaluated. As you can see this statement again calls factorial function with value i-1 which will return value: 4*factorial(4-1); This recursive calling continues until value of i is equal to 1 and when i is equal to 1 it returns 1 and execution of this function stops. We can review the series of recursive call as follow: f = 5* factorial (5-1); f = 5*4* factorial (4-1); f = 5*4*3* factorial (3-1); f = 5*4*3*2* factorial (2-1); f = 5*4*3*2*1; f = 120;

62 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

7 Additional C Data Types


7.1 Array:

What is an Array in C Language?


An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name. An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a string, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we cant have an array of 10 numbers, of which 5 are ints and 5 are floats.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Declaration of an Array
Arrays must be declared before they can be used in the program. Standard array declaration is as
type variable_name[lengthofarray];

Here type specifies the variable type of the element which is going to be stored in the array. In C programmin language we can declare the array of any basic standard type which C language supports. For example
double height[10]; float width[20]; int min[9]; char name[20];

In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C Language treats the name of the array as if it were a pointer to the first element This is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accesed any where from with in the program. So
m=height[0];

variable m will have the value of first item of array height. The program below will declare an array of five integers and print all the elements of the array.

63 Mob-8080373934

Atul Sirs Private Tuition (Engg)


int myArray [5] = {1,2,3,4,5}; /* To print all the elements of the array for (int i=0;i<5;i++){ printf("%d", myArray[i]); }

Structured Programming (Sem II)

Initializing Arrays
Initializing of array is very simple in c programming. The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name. Here is an example which declares and initializes an array of five elements of type int. Array can also be initialized after declaration. Look at the following C code which demonstrate the declaration and initialization of an array.
int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement int studentAge[4]; studentAge[0]=14; studentAge[1]=13; studentAge[2]=15; studentAge[3]=16;

Performing operations on Arrays


Here is a program that will demonstrate the simple operations of the array.
#include <stdio.h> void oneWay(void); void anotherWay(void); int main(void) { printf("\noneWay:\n"); oneWay(); printf("\nantherWay:\n"); anotherWay(); } /*Array initialized with aggregate */ void oneWay(void) { int vect[10] = {1,2,3,4,5,6,7,8,9,0}; int i; for (i=0; i<10; i++){ printf("i = %2d vect[i] = %2d\n", i, vect[i]); } } /*Array initialized with loop */ void anotherWay(void) { int vect[10]; int i; for (i=0; i<10; i++) vect[i] = i+1; for (i=0; i<10; i++) printf("i = %2d vect[i] = %2d\n", i, vect[i]); }

64 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

/* The output of oneWay: i = 0 vect[i] i = 1 vect[i] i = 2 vect[i] i = 3 vect[i] i = 4 vect[i] i = 5 vect[i] i = 6 vect[i] i = 7 vect[i] i = 8 vect[i] i = 9 vect[i] antherWay: i = 0 vect[i] i = 1 vect[i] i = 2 vect[i] i = 3 vect[i] i = 4 vect[i] i = 5 vect[i] i = 6 vect[i] i = 7 vect[i] i = 8 vect[i] i = 9 vect[i] */

this program is = = = = = = = = = = = = = = = = = = = = 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 10

Copy one array into another


There is no such statement in C language which can directly copy an array into another array. So we have to copy each item seperately into another array.
#include <stdio.h> int main() { int iMarks[4]; short newMarks[4]; iMarks[0]=78; iMarks[1]=64; iMarks[2]=66; iMarks[3]=74; for(i=0; i<4; i++) newMarks[i]=iMarks[i]; for(j=0; j<4; j++) printf("%d\n", newMarks[j]); return 0; }

To summarize, arrays are provides a simple mechanism where more than one elements of same type are to be used. We can maintain, manipulate and store multiple elements of same type in one array variable and access them through index.

65 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Multidimensional Arrays
In C Language one can have arrays of any dimensions. To understand the concept of multidimensional arrays let us consider the following 4 X 5 matrix Column numbers (j) 11 3 5 -9 5 6 -8 7 -8 9 2 12 10 13 -10 4

0 Row 1 number (i) 2 3

-6 24 45 5

Let us assume the name of matrix is x To access a particular element from the array we have to use two subscripts on for row number and other for column number the notation is of the form X [i] [j] where i stands for row subscripts and j stands for column subscripts. Thus X [0] [0] refers to 10, X [2] [1] refers to 16 and so on In short multi dimensional arrays are defined more or less in the same manner as single dimensional arrays, except that for subscripts you require two squire two square brackets. We will restrict our decision to two dimensional arrays. Below given are some typical two-dimensional array definitions
float table [50] [50]; char line [24] [40];

The first example defines tables as a floating point array having 50 rows and 50 columns. the number of elements will be 2500 (50 X50). The second declaration example establishes an array line of type character with 24 rows and 40 columns. The number of elements will be (24 X 40) 1920 consider the following two dimensional array definition int values [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 11, 12, };
Values [0] [0] = 1 Values [0] [1] = 2 Values [0] [2] = 3 Values [0] [3] = 4 Values [1] [0] = 5 Values [1] [1] = 6 Values [1] [2] = 7 Values [1] [3] = 8 Values [2] [0] = 9 Values [2] [1] = 10 Values [2] [2] = 11 Values [2] [3] = 12

Here the first subscript stands for the row number and second one for column number. First subscript ranges from 0 to 2 and there are altogether 3 rows second one ranges from 0 to 3 and there are altogether 4 columns. Alternatively the above definition can be defined and initialised as
int values [3] [4] = { { 1, 2, 3, 4

66 Mob-8080373934

Atul Sirs Private Tuition (Engg)


} { 5, 6, 7, 8 } { 9, 10, 11, 12 } };

Structured Programming (Sem II)

Here the values in first pair of braces are initialised to elements of first row, the values of second pair of inner braces are assigned to second row and so on. Note that outer pair of curly braces is required. If there are two few values within a pair of braces the remaining elements will be assigned as zeros. Here is a sample program that stores roll numbers and marks obtained by a student side by side in matrix
main ( ) { int stud [4] [2]; int i, j; for (i =0; i < =3; i ++) { printf ("\n Enter roll no. and marks"); scanf ("%d%d", &stud [i] [0], &stud [i] [1] ); } for (i = 0; i < = 3; i ++) printf ("\n %d %d", stud [i] [0], stud [i] [1]); }

The above example illustrates how a two dimensional array can be read and how the values stored in the array can be displayed on screen. 7.2 Structures And Union:

STRUCTURE
A structure is a convenient tool for handling a group of logically related data items. Structure help to organize complex data is a more meaningful way. It is powerful concept that we may after need to use in our program Design. A structure is combination of different data types using the & operator, the beginning address of structure can be determined. This is variable is of type structure, then & variable represent the starting address of that variable.

STRUCTURE DEFINITION
A structure definition creates a format that may be used to declare structure variables consider the following example.
Struct book-bank

67 Mob-8080373934

Atul Sirs Private Tuition (Engg)


{ Char title [20]; Char author [15]; int pages; float price; };

Structured Programming (Sem II)

Here keyword Struct hold the details of four fields these fields are title, author, pages, and price, these fields are called structure elements. Each element may belong to different types of data. Here book-bank is the name of the structure and is called the structure tag. It simply describes as shown below. Struct book-bank Title array of 20 charecters Author array of 15 charecters Pages integer Price float The general format of a structure definition is as follows
struct teg_name{ data_type member 1; data_type member 2; - - - - - - - - - - - - - - - }

ARRAY OF STRUCTURES
Each element of the array itself is a structure see the following example shown below. Here we want to store data of 5 persons for this purpose, we would be required to use 5 different structure variables, from sample1 to sample 5. To have 5 separate variable will be inconvenient.
#include < stdio.h> main() { str uct person { char name [25]; char age; }; struct person sample[5]; int index; char into[8]; for( index = 0; index <5; index ++)

68 Mob-8080373934

Atul Sirs Private Tuition (Engg)


{ print("Enter name;"); gets(sample [index]. name); printf("%Age;"); gets(info); sample [index]. age = atoi (info); } for (index = 0; index <5; index++) { printf("name = %5\n", sample [index].name); printf("Age = %d \n", sample [index].age); getch( ); } }

Structured Programming (Sem II)

The structure type person is having 2 elements: Name an array of 25 characters and character type variable age

USING THE STATEMENT


Str uct person sample[5]; we are declaring a 5 element array of structures. Here, each element of sample is a separate structure of type person. We, then defined 2 variables into index and an array of 8 characters, info. Here, the first loop executes 5 times, with the value of index varying from 0 to 4. The first printf statement displays. Enter name gets( ) function waits for the input string. For the first time this name you enter will go to sample[0]. name. The second printf display age the number you type is will be 5 stored as character type, because the member age is declared as character type. The function atoi( ) converts this into an integer. atoi stands for alpha to integer. This will be store in sample[0] age. The second for loop in responsible for printing the information stored in the array of structures.

STRUCTURES WITHIN STRUCTURES


Structure with in a structure means nesting of structures. Let us consider the following structure defined to store information about the salary of employees.
Str uct salary { char name[20]; char department[10]; int basic_pay; int dearness_allowance; int city_allowance; } employee;

This structure defines name, department, basic pay and 3 kinds of allowance. we can group all the items related to allowance together and declare them under a substructure are shown below:
struct salary { char name [20];

69 Mob-8080373934

Atul Sirs Private Tuition (Engg)


char department[10]; str uct { int dearness; int hous_rent; int city; } allowance; } employee;

Structured Programming (Sem II)

The salary structure contains a member named allowance which itself is a structure with 3 members. The members contained in the inner, structure namely dearness, hous_rent, and city can be referred to as :
employee allowance. dearness employee. allowance. hous_rent employee. allowance. city

An inner-most member in a nested structure can be accessed by chaining all the concerned. Structure variables (from outer-most to inner-most) with the member using dot operator. The following being invalid.
employee. allowance (actual member is missing) employee. hous_rent (inner structure variable is missing) Passing a Structure as a whole to a Function

UNIONS
Unions, like structure contain members, whose individual data types may vary. These is major distinction between them in terms of storage .In structures each member has its own storage location, where as all the members of a union use the same location. Like str uctures, a union can be declared using the keyword union is follows: union item{ int m; float x; char c; } code; This declares a variable code of type union them. The union contains them members, each with a different date type. However, we can use only one of them at a time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size. The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union. In the declaration above, the member x requires 4 bytes which is the largest among the members. The above figure shown how all the three variables share the same address, this assumes that a float variable requires 4 bytes of storage. To access a union member, we can use the same syntax that we as for structure members, that is,
70 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

code. m code. x code. c are all valid Member variables, we should make sure that we can accessing the member whose value is currently storage. For example code. m = 565; code. x = 783.65; printf(%d, code. m); would produce erroroneous output. # include <stdio.h> main( ){ union { int one; char two; } val; val. one = 300; printf(val. one = %d \n, val. one); printf(val. two = %d \n, val. two); } The format of union is similar to structure, with the only difference in the keyword used. The above example, we have 2 members int one and char two we have then initialised the member ?one? to 300. Here we have initilised only one member of the union. Using two printf statements, then we are displaying the individual members of the union val as: val. one = 300 val. two = 44 As we have not initialised the char variable two, the second printf statement will give a random value of 44. 7.3 Pointers:

What Are Pointers?


The simple variables are used to store the literal values. Whenever a variable is declared in a program it is having same memory location in the storage device. The memory location is called address of that variable. Hence there are some values which do not hold the literal values but stores the address (memory address) of any other variable. Such variables are called pointers (The pointers in 'C' language increase the efficiency of program to a large extent. Efficiency of program to a large extent. Although they are difficult to use but it is a very powerful tool. While managing the memory. Pointers are used for many reasons like :-

71 Mob-8080373934

Atul Sirs Private Tuition (Engg)


Structured Programming (Sem II)

Pointers reduce the length and complex city of program. They increase the processing speed. They save the memory to a very large extent. A pointer enables to access any variable whether it may be outside the function i.e. a direct control over a variable can be made using pointers.

To declare a pointer you must put a * in front of its name. Here is an example of how to declare a pointer to an integer and an untyped pointer: Code:
int main() { int *p; void *up; return 0; }

You can put the address of an integer into a pointer to an integer by using the & operator to get the integer's address. Code:
int main() { int i; int *p; i = 5; p = &i; return 0; }

You can access the value of the integer that is being pointed to by dereferencing the pointer. The * is used to dereference a pointer. Changing the value pointed to by the integer will change the value of the integer. Code:
int main() { int i,j; int *p; i = 5; p = &i; j = *p; //j = i *p = 7; //i = 7 return 0; }

How the pointers are initialized and define how variable can be accessed through pointer (Arithmetic)? The pointer variables are declare by using the pointer notation (astric,*). They are also associated with a data type which will represent the type of data to which that particular pointer
72 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

is pointing. Here pointer variable is different from simple variables in the sense that they cannot store some literal value but will store the address of any particular memory location. Hence it the memory location has to be stored in the pointer variable then such process is called pointer initialization. The pointer initialization when done then it should be kept in the mind that the pointer only that memory location on which the same data type item is stored to which the pointer variable can point. Example :int main() { Int *a,b, *d; Float c, *e; A=&b; D=&c; C=&c; }

The first statement will assign the address of 'b' variable memory location to the pointer 'a' pointer 'a' is pointing to an integer type memory location and 'b' is an integer variable. In second statement the pointer variable is invalid, since 'd' is an integer pointer and 'c' is a float type variable. Hence integer type pointer cannot store the float type data address. The third statement is valid since a float type pointer is pointing to a float type variable. A Pointer type variable is generally used to access the value of the variable to which pointer is pointing. This can be done by using the indirection operation (*- content operator). When the * is placed in front of a pointer, it will be result in the content of that variable to which it is pointing. But since the pointer variable is not having its own content hence it will access the content of that variable to which it is pointing. Hence a value of a variable can be accessed without calling that variable, through its pointer. How the pointers can be used with an array and how the pointers pointing to arrays are initialized? array is a collection of multiple data item which are represented by using a single identifier. Since a single identifier representing all the data items will have generally a continuous allocation in arrays there is one base address to which all the contiguous memory location are attached. These memory location are having then difference in addresses and their addresses are continuous in manner. A pointer variable is incremented by using an increment operator then its address value is not increased by 1 but it will be increased by a complete address this type of incrementation is called pointer incrementation and the length the which pointer is incrementing is called scalar factor.

73 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Since the array is having a base address and all the memory location is continuous in manner and they store the data item of some type and the scalar factor can be used in the pointers. Hence if a pointer variable is made pointing to the base address of the any array then all successive element of that array can be access by incrementing the pointer variable till the end of the array.

Example :
int main() { Int a [10], *p; P=&a[0]; [0] P=& a[10] [10] }

This will assign the base address of array 'a' in the pointer variable p. Now if the value of the second index has to be accessed then the pointer p is incremented and now it is pointing to the next index to the base address. This can be done by using increment operator like p++.

7.4 File Handling in C The file I/O functions and types in the C language are straightforward and easy to understand. To make use of these functions and types you have to include the stdio library. (Like we already did in most of the tutorials). The file I/O functions in the stdio library are:

fopen opens a text file. fclose closes a text file. feof detects end-of-file marker in a file. fscanf reads formatted input from a file. fprintf prints formatted output to a file. fgets reads a string from a file. fputs prints a string to a file. fgetc reads a character from a file. fputc prints a character to a file.

File I/O: opening a text file


The fopen library function is used to open a text file. You also have to use a specified mode when you open a file. The three most common modes used are read (r), write (w), and append (a). Take a look at an example:
#include<stdio.h> int main()

74 Mob-8080373934

Atul Sirs Private Tuition (Engg)


{ FILE *ptr_file; int x; ptr_file =fopen("output.txt", "w"); if (!ptr_file) return 1; for (x=1; x<=10; x++) fprintf(ptr_file,"%d\n", x); fclose(ptr_file); return } 0;

Structured Programming (Sem II)

So lets take a look at the example:

ptr_file =fopen(output, w);


The fopen statement opens a file output.txt in the write (w) mode. If the file does not exist it will be created. But you must be careful! If the file exists, it will be destroyed and a new file is created instead. The fopen command returns a pointer to the file, which is stored in the variable ptr_file. If the file cannot be opened (for some reason) the variable ptr_file will contain NULL.

if (!ptr_file)
The if statement after de fopen, will check if the fopen was successful. If the fopen was not successful, the program will return a one. (Indicating that something has gone wrong).

for (x=1; x<=10; x++)


This for loop will count to ten, starting from one.

fprintf(ptr_file,%d\n, x);
The fprintf statement should look very familiar to you. It can be almost used in the same way as printf. The only new thing is that it uses the file pointer as its first parameter.

fclose(ptr_file);
The fclose statement will close the file. This command must be given, especially when you are writing files. So dont forget it. You have to be careful that you dont type close instead of fclose, because the close function exists. But the close function does not close the files correctly. (If there are a lot of files open but not closed properly, the program will eventually run out of file handles and/or memory space and crash.)
75 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

File I/O: reading a text file


If you want to read a file you have to open it for reading in the read (r) mode. Then the fgets library functions can be used to read the contents of the file. (It is also possible to make use of the library function fscanf. But you have to be sure that the file is perfectly formatted or fscanf will not handle it correctly). Lets take a look at an example:
#include<stdio.h> int main() { FILE *ptr_file; char buf[1000]; ptr_file =fopen("input.txt","r"); if (!ptr_file) return 1; while (fgets(buf,1000, ptr_file)!=NULL) printf("%s",buf); fclose(ptr_file); return 0; }

Note:The printf statement does not have the new-line (\n) in the format string. This is not necessary because the library function fgets adds the \n to the end of each line it reads. A file input.txt is opened for reading using the function fopen en the mode read (r). The library function fgets will read each line (with a maximum of 1000 characters per line.) If the end-of-file (EOF) is reached the fgets function will return a NULL value. Each line will be printed on stdout (normally your screen) until the EOF is reached. The file is then closed and the program will end. 7.5 String and String Library Functions: A string in the C language is simply an array of characters. Strings must have a NULL or \0 character after the last character to show where the string ends. A string can be declared as a character array or with a string pointer. First we take a look at a character array example:
char mystr[20];

As you can see the character array is declared in the same way as a normal array. This array can hold only 19 characters, because we must leave room for the NULL character. Take a look at this example:

76 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

#include<stdio.h> int main() { char mystring[20]; mystring[0] mystring[1] mystring[2] mystring[3] mystring[4] mystring[5] mystring[6] = = = = = = = 'H'; 'E'; 'L'; 'L'; 'O'; '\n'; '\0';

printf("%s", mystring); return 0; }

Note: %s is used to print a string. (The 0 without the will in most cases also work). String pointers are declared as a pointer to a char. When there is a value assigned to the string pointer the NULL is put at the end automatically. Take a look at this example:
#include<stdio.h> int main() { char *ptr_mystring; ptr_mystring = "HELLO"; printf("%s\n", ptr_mystring); return 0; }

It is not possible to read, with scanf, a string with a string pointer. You have to use a character array and a pointer. See this example:
#include<stdio.h> int main() { char my_array[10]; char *ptr_section2; printf("Type hello and enter\n"); scanf("%s", &my_array); ptr_section2 = my_array;

77 Mob-8080373934

Atul Sirs Private Tuition (Engg)


printf("%s\n", ptr_section2); return 0; }

Structured Programming (Sem II)

string.h or strings.h
The C language provides no explicit support for strings in the language itself. The stringhandling functions are implemented in libraries. String I/O operations are implemented in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions are implemented in <string.h>, or on some systems in <strings.h>. The string library (string.h or strings.h) has some useful functions for working with strings, like strcpy, strcat, strcmp, strlen, strcoll, etc. We will take a look at some of these string operations. Important: Dont forget to include the library string.h (or on some systems strings.h) if you want to use one of these library functions.

strcpy
This library function is used to copy a string and can be used like this: strcpy(destination, source). (It is not possible in C to do this: string1 = string2). Take a look at the following example:
str_one = "abc"; str_two = "def"; strcpy(str_one , str_two); // str_one becomes "def"

Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

strcmp
This library function is used to compare two strings and can be used like this: strcmp(str1, str2).

If the first string is greater than the second string a number greater than null is returned. If the first string is less than the second string a number less than null is returned. If the first and the second string are equal a null is returned.

Take look at an example:

printf("Enter you name: "); scanf("%s", name); if( strcmp( name, "jane" ) == 0 )

78 Mob-8080373934

Atul Sirs Private Tuition (Engg)


printf("Hello, jane!\n");

Structured Programming (Sem II)

Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

strcat
This library function concatenates a string onto the end of the other string. The result is returned. Take a look at the example:
printf("Enter you age: "); scanf("%s", age); result = strcat( age, " years old." ) == 0 ) printf("You are %s\n", result);

Note: strcat() will not perform any boundary checking, and thus there is a risk of overrunning the strings.

strlen
This library function returns the length of a string. (All characters before the null termination.) Take a look at the example:
name = "jane"; result = strlen(name); //Will return size of four.

memcmp
This library function compares the first count characters of buffer1 and buffer2. The function is used like this: memcmp(buffer1,buffer2). The return values are as follows:

If buffer1 is greater than buffer2 a number greater than null is returned. If buffer1 is less than buffer2 a number less than null is returned. If buffer1 and buffer2 are equal a null is returned.

Note: There are also library functions: memcpy, memset and memchr.

79 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

8 Sample Programs
Program 1: Check the given number is armstrong number or not using c program Those numbers which sum of the cube of its digits is equal to that number are known as Armstrong numbers. For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153 Other Armstrong numbers: 370,371,407 etc.

#include<stdio.h> int main(){ int num,r,sum=0,temp; printf("Enter a number: "); scanf("%d",&num); temp=num; while(num!=0){ r=num%10; num=num/10; sum=sum+(r*r*r); } if(sum==temp) printf("%d is an Armstrong number",temp); else printf("%d is not an Armstrong number",temp); return 0; } Sample output: Enter a number: 153 153 is an Armstrong number
Program 2: Check given number is prime number or not using c program A natural number greater than one has not any other divisors except 1 and itself. In other word we can say which has only two divisors 1 and number itself. For example: 5 Their divisors are 1 and 5. Note: 2 is only even prime number.

80 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

#include<stdio.h> int main(){ int num,i,count=0; printf("Enter a number: "); scanf("%d",&num); for(i=2;i<=num/2;i++){ if(num%i==0){ count++; break; } } if(count==0 && num!= 1) printf("%d is a prime number",num); else printf("%d is not a prime number",num); return 0; } Sample output: Enter a number: 5 5 is a prime number
Program 3: Write a c program to check given string is palindrome number or not . A string is called palindrome if it symmetric. In other word a string is called palindrome if string remains same if its characters are reversed. For example: asdsa If we will reverse it will remain same i.e. asdsa

#include<string.h> #include<stdio.h> int main(){ char *str,*rev; int i,j; printf("\nEnter a string:"); scanf("%s",str); for(i=strlen(str)-1,j=0;i>=0;i--,j++) rev[j]=str[i]; rev[j]='\0'; if(strcmp(rev,str)) printf("\nThe string is not a palindrome"); else
81 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("\nThe string is a palindrome"); return 0; }


Program 4: TO FIND FIBONACCI SERIES USING C PROGRAM . We assume first two Fibonacci are 0 and 1 A series of numbers in which each sequent number is sum of its two previous numbers is known as Fibonacci series and each numbers are called Fibonacci numbers. So Fibonacci numbers is

0 , 1 ,1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 #include<stdio.h> int main(){ int k,r; long int i=0l,j=1,f; //Taking maximum numbers form user printf("Enter the number range:"); scanf("%d",&r);

...

printf("FIBONACCI SERIES: "); printf("%ld %ld",i,j); //printing firts two values. for(k=2;k<r;k++){ f=i+j; i=j; j=f; printf(" %ld",j); } return 0; } Sample output: Enter the number range: 15 FIBONACCI SERIES: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Program 5: TO FIND FACTORIAL OF A NUMBER USING C PROGRAM Factorial of number is defined as: Factorial (n) = 1*2*3 * n For example: Factorial of 5 = 1*2*3*4*5 = 120 Note: Factorial of zero = 1
82 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

#include<stdio.h> int main(){ int i=1,f=1,num; printf("Enter a number: "); scanf("%d",&num); while(i<=num){ f=f*i; i++; } printf("Factorial of %d is: %d",num,f); return 0; } Sample output: Enter a number: 5 Factorial of 5 is: 120
Program 6: Reverse any number using c program .

#include<stdio.h> int main(){ int num,r,reverse=0; printf("Enter any number: "); scanf("%d",&num); while(num){ r=num%10; reverse=reverse*10+r; num=num/10; } printf("Reversed of number: %d",reverse); return 0; } Sample output: Enter any number: 12 Reversed of number: 21
83 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Program 7: C program for swapping of two numbers

#include<stdio.h> void swap(int *,int *); int main(){ int a,b; printf("Enter any two integers: "); scanf("%d%d",&a,&b); printf("Before swapping: a = %d, b=%d",a,b); swap(&a,&b); printf("\nAfter swapping: a = %d, b=%d",a,b); return 0; } void swap(int *a,int *b){ int *temp; temp = a; *a=*b; *b=*temp; } Sample output: Enter any two integers: 3 6 Before swapping: a = 3, b=6 After swapping: a = 6, b=6
Program 8: SWAP TWO VARIABLES WITHOUT USING THIRD USING C PROGRAM VARIABLE

#include<stdio.h> int main(){ int a=5,b=10; //process one a=b+a;


84 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

b=a-b; a=a-b; printf("a= %d //process two a=5;b=10; a=a+b-(b=a); printf("\na= %d //process three a=5;b=10; a=a^b; b=a^b; a=b^a; printf("\na= %d //process four a=5;b=10; a=b-~a-1; b=a+~b+1; a=a+~b+1; printf("\na= %d

b=

%d",a,b);

b=

%d",a,b);

b=

%d",a,b);

b=

%d",a,b);

//process five a=5,b=10; a=b+a,b=a-b,a=a-b; printf("\na= %d b= return 0; }

%d",a,b);

Program 9: Write a c program to find out L.C.M. of two numbers.

#include<stdio.h> int lcm(int,int); int main(){

int a,b,l;
85 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("Enter any two positive integers "); scanf("%d%d",&a,&b); if(a>b) l = lcm(a,b); else l = lcm(b,a); printf("LCM of two integers is %d",l); return 0; } int lcm(int a,int b){ int temp = a; while(1){ if(temp % b == 0 && temp % a == 0) break; temp++; } return temp; }
Program 10: Find g.c.d of two number using c program Logic for writing program: It is clear that any number is not divisible by greater than number itself. In case of more than one numbers, a possible maximum number which can divide all of the numbers must be minimum of all of that numbers. For example: 10, 20, and 30 Min (10, 20, 30) =10 can divide all there numbers.

#include<stdio.h> int main(){ int x,y=-1; printf("Insert numbers. To exit insert zero: ");
86 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

while(1){ scanf("%d",&x); if(x<1) break; else if(y==-1) y=x; else if (x<y) y=gcd(x,y); else y=gcd(y,x); } printf("GCD is %d",y); return 0; } int gcd(int x,int y){ int i; for(i=x;i>=1;i--){ if(x%i==0&&y%i==0){ break; } } return i; }

Program 11: C program to convert digits to words.

#include<stdio.h> int main(){ int number,i=0,j,digit; char * word[1000]; printf("Enter any integer: "); scanf("%d",&number); while(number){
87 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

digit = number %10; number = number /10; switch(digit){ case 0: word[i++] case 1: word[i++] case 2: word[i++] case 3: word[i++] case 4: word[i++] case 5: word[i++] case 6: word[i++] case 7: word[i++] case 8: word[i++] case 9: word[i++] } } for(j=i-1;j>=0;j--){ printf("%s ",word[j]); } return 0; } Sample output: Enter any integer: 23451208 two three four five one two zero eight = = = = = = = = = = "zero"; break; "one"; break; "two"; break; "three"; break; "four"; break; "five"; break; "six"; break; "seven"; break; "eight"; break; "nine"; break;

Program 12: CONCATENATION OF TWO STRINGS USING C PROGRAM

#include<stdio.h> int main(){ int i=0,j=0; char str1[20],str2[20]; puts("Enter first string"); gets(str1); puts("Enter second string");
88 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

gets(str2); printf("Before concatenation the strings are\n"); puts(str1); puts(str2); while(str1[i]!='\0'){ i++; } while(str2[j]!='\0'){ str1[i++]=str2[j++]; } str1[i]='\0'; printf("After concatenation the strings are\n"); puts(str1); return 0; }

Program 13: How to compare two strings in c without using strcmp

#include<stdio.h> int stringCompare(char[],char[]); int main(){ char str1[100],str2[100]; int compare; printf("Enter first string: "); scanf("%s",str1); printf("Enter second string: "); scanf("%s",str2); compare = stringCompare(str1,str2); if(compare == 1) printf("Both strings are equal."); else printf("Both strings are not equal"); return 0;
89 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

} int stringCompare(char str1[],char str2[]){ int i=0,flag=0; while(str1[i]!='\0' && str2[i]!='\0'){ if(str1[i]!=str2[i]){ flag=1; break; } i++; } if (flag==0 && str1[i]=='\0' && str2[i]=='\0') return 1; else return 0; } Sample output: Enter first string: Structured Programming Enter second string: Structured Programming Both strings are equal.
Program 14: CONVERSION FROM UPPERCASE TO LOWER CASE USING C PROGRAM

#include<stdio.h> #include<string.h> int main(){ char str[20]; int i; printf("Enter any string->"); scanf("%s",str); printf("The string is->%s",str); for(i=0;i<=strlen(str);i++){ if(str[i]>=65&&str[i]<=90) str[i]=str[i]+32; } printf("\nThe string in lower case is->%s",str); return 0;
90 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Algorithm:
ASCII value of 'A' is 65 while 'a' is 97. Difference between them is 97 65 = 32 So if we will add 32 in the ASCII value of 'A' then it will be 'a' and if will we subtract 32 in ASCII value of 'a' it will be 'A'. It is true for all alphabets. In general rule: Upper case character = Lower case character 32 Lower case character = Upper case character + 32 Program 15: ADDITION OF TWO MATRICES USING C PROGRAM

#include<stdio.h> int main(){ int a[3][3],b[3][3],c[3][3],i,j; printf("Enter the First matrix->"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&a[i][j]); printf("\nEnter the Second matrix->"); for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&b[i][j]); printf("\nThe First matrix is\n"); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) printf("%d\t",a[i][j]); } printf("\nThe Second matrix is\n"); for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) printf("%d\t",b[i][j]); } for(i=0;i<3;i++) for(j=0;j<3;j++) c[i][j]=a[i][j]+b[i][j]; printf("\nThe Addition of two matrix is\n"); for(i=0;i<3;i++){ printf("\n");
91 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

for(j=0;j<3;j++) printf("%d\t",c[i][j]); } return 0; }


Program 16: MULTIPLICATION OF TWO MATRICES USING C PROGRAM

#include<stdio.h> int main(){ int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p; printf("\nEnter the row and column of first matrix"); scanf("%d %d",&m,&n); printf("\nEnter the row and column of second matrix"); scanf("%d %d",&o,&p); if(n!=o){ printf("Matrix mutiplication is not possible"); printf("\nColumn of first matrix must be same as row of second matrix"); } else{ printf("\nEnter the First matrix->"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("\nEnter the Second matrix->"); for(i=0;i<o;i++) for(j=0;j<p;j++) scanf("%d",&b[i][j]); printf("\nThe First matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<n;j++){ printf("%d\t",a[i][j]); } } printf("\nThe Second matrix is\n"); for(i=0;i<o;i++){ printf("\n"); for(j=0;j<p;j++){
92 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("%d\t",b[i][j]); } } for(i=0;i<m;i++) for(j=0;j<p;j++) c[i][j]=0; for(i=0;i<m;i++){ //row of first matrix for(j=0;j<p;j++){ //column of second matrix sum=0; for(k=0;k<n;k++) sum=sum+a[i][k]*b[k][j]; c[i][j]=sum; } } } printf("\nThe multiplication of two matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<p;j++){ printf("%d\t",c[i][j]); } } return 0; }
Program 16: C program to find transpose of given matrix

#include<stdio.h> int main(){ int a[10][10],b[10][10],i,j,k=0,m,n; printf("\nEnter the row and column of matrix"); scanf("%d %d",&m,&n); printf("\nEnter the First matrix->"); for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); printf("\nThe matrix is\n"); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<m;j++){
93 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

printf("%d\t",a[i][j]); } } for(i=0;i<m;i++) for(j=0;j<n;j++) b[i][j]=0; for(i=0;i<m;i++){ for(j=0;j<n;j++){ b[i][j]=a[j][i]; printf("\n%d",b[i][j]); } } printf("\n\nTraspose of a matrix is -> "); for(i=0;i<m;i++){ printf("\n"); for(j=0;j<m;j++){ printf("%d\t",b[i][j]); } } return 0; }

Program 18: FIND OUT LARGEST NUMBER IN AN ARRAY USING C PROGRAM

#include<stdio.h> int main(){ int a[50],size,i,big; printf("\nEnter the size of the array: "); scanf("%d",&size); printf("\nEnter %d elements in to the array: , size); for(i=0;i<size;i++) scanf("%d",&a[i]); big=a[0]; for(i=1;i<size;i++){ if(big<a[i]) big=a[i]; } printf("\nBiggest: %d",big); return 0;
94 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

}
Program 19: BUBBLE SORT USING C PROGRAM

#include<stdio.h> int main(){ int s,temp,i,j,a[20]; printf("Enter total numbers of elements: "); scanf("%d",&s); printf("Enter %d elements: ",s); for(i=0;i<s;i++) scanf("%d",&a[i]); //Bubble sorting algorithm for(i=s-2;i>=0;i--){ for(j=0;j<=i;j++){ if(a[j]>a[j+1]){ temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("After sorting: "); for(i=0;i<s;i++) printf(" %d",a[i]); return 0; } Output: Enter total numbers of elements: 5 Enter 5 elements: 6 2 0 11 9 After sorting: 0 2 6 9 11

95 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

Program 20: Write a c program to find out the sum of series 1^2 + 2^2 + . + n^2.

#include<stdio.h> int main(){ int n,i; int sum=0; printf("Enter the n i.e. max values of series: "); scanf("%d",&n); sum = (n * (n + 1) * (2 * n + 1 )) / 6; printf("Sum of the series : "); for(i =1;i<=n;i++){ if (i != n) printf("%d^2 + ",i); else printf("%d^2 = %d ",i,sum); } return 0; } Sample output: Enter the n i.e. max values of series: 5 Sum of the series: 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55
Program 21: FIND GCD OF A NUMBER USING RECURSION IN C PROGRAM

#include<stdio.h> int main(){ int n1,n2,gcd; printf("\nEnter two numbers: "); scanf("%d %d",&n1,&n2); gcd=findgcd(n1,n2); printf("\nGCD of %d and %d is: %d",n1,n2,gcd); return 0; } int findgcd(int x,int y){
96 Mob-8080373934

Atul Sirs Private Tuition (Engg)

Structured Programming (Sem II)

while(x!=y){ if(x>y) return findgcd(x-y,y); else return findgcd(x,y-x); } return x; }


Program 22: CREATE A FILE AND STORE DATA IN IT IN C PROGRAM

#include<stdio.h> int main(){ FILE *fp; char ch; fp=fopen("file.txt","w"); printf("\nEnter data to be stored in to the file:"); while((ch=getchar())!=EOF) putc(ch,fp); fclose(fp); return 0; }

97 Mob-8080373934

You might also like