the computer book _where you can learn more__ c - programming.pdf

58
10/26/2014 The Computer Book |where you can learn more|: C - programming http://finesbook.blogspot.in/2012/06/c-programming.html 1/58 The Computer Book |where you can learn more| SATURDAY, JUNE 16, 2012 C - programming Search C - programming C-programming language C is a programming language developed by denis ritchie in 1972. It was official language of Bells labs. All the programming language broadly categorized into two; high level language and low level language. C stands in between HLL and LLL. It is capable of developing strong programs, viruses and almost all parts of operating system like recoded UNIX in 1973 and linex in 1991. Features of C 1. General purpose language. 2. It is high level assembly language. 3. It is modular and structural concept as debugging, testing and maintenance are easy. 4. It is machine independent also. 5. It is a free form language. 6. Introduction of incremental/decrement operator. 7. It has low level(bit wise) programming available Advantages and disadvantages of C Advantages · It is machine independent programming language. · It is easy to used and implement. · It is the mother of all the modern programming language. Disadvantages · There is no runtime checking. · On larges programs. It is hard to fix errors · It does not support modern programming methodologies oriented programming language. Header file A file that is defined to be included at the begging of a program in c language that contains the definitions of data types, variables and functions in the program is called header file. The entire header file has the extension {.h} some of the frequent use header files are stdio.h, conio.h, math.h, string.h ctype.h etc. Identifiers Identifiers are the name given to various program elements such as constants. Variables, function names and arrays etc. every element in the program has its own distinct name. Keyword The basic building block of program statement is called keywords. All the keywords are basically the sequence of characters that have one or fixed meaning these keywords not used as variable name Auto Break Case Char Const Bhuwan Bhandari Follow 6 View my complete profile ABOUT ME 2012 (17) June (17) System Developm ent Life Cycle C Programmi rigs (Nested Loop) Course in detail for grade XII (Computer Science) C - programmi ng Report Writing for Project: Software BLOG ARCHIVE 0 More Next Blog» Create Blog Sign In

Upload: prafull

Post on 23-Dec-2015

46 views

Category:

Documents


4 download

TRANSCRIPT

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 1/58

The Computer Book |where you can learn more|

SATURDAY, JUNE 16, 2012

C - programming

Search

C - programmingC-programming languageC is a programming language developed by denis ritchie in 1972. It was official language of Bellslabs. All the programming language broadly categorized into two; high level language and low levellanguage. C stands in between HLL and LLL. It is capable of developing strong programs, virusesand almost all parts of operating system like recoded UNIX in 1973 and linex in 1991.

Features of C1. General purpose language.2. It is high level assembly language.3. It is modular and structural concept as debugging, testing and maintenance are easy.4. It is machine independent also.5. It is a free form language.6. Introduction of incremental/decrement operator.7. It has low level(bit wise) programming available

Advantages and disadvantages of CAdvantages

· It is machine independent programming language.· It is easy to used and implement.· It is the mother of all the modern programming language.

Disadvantages· There is no runtime checking.· On larges programs. It is hard to fix errors· It does not support modern programming methodologies oriented programming language.

Header fileA file that is defined to be included at the begging of a program in c language that contains thedefinitions of data types, variables and functions in the program is called header file. The entireheader file has the extension {.h} some of the frequent use header files are stdio.h, conio.h, math.h,string.h ctype.h etc.

IdentifiersIdentifiers are the name given to various program elements such as constants. Variables, functionnames and arrays etc. every element in the program has its own distinct name.

KeywordThe basic building block of program statement is called keywords. All the keywords are basicallythe sequence of characters that have one or fixed meaning these keywords not used as variablename

AutoBreakCaseCharConst

BhuwanBhandari

Follow 6

View my completeprofile

ABOUT ME

▼ 2012 (17)

▼ June (17)System

Development LifeCycle

CProgrammirigs(NestedLoop)

Course indetail forgrade XII(ComputerScience)

C -programming

ReportWriting forProject:

Software

BLOG ARCHIVE

0 More Next Blog» Create Blog Sign In

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 2/58

ContinueDefaultDo doubleEleEnumExtemFloatForGotoIfIntLongRegisterReturnShortSignedSizeofStaticStructSwitchTypedofUnionUnsignedVoidVolatileWhile

Variable and constantThe variable or literal is like as container contain value. The value of contents can be changedduring program execution but constant is a data which remains constant during program life cycle

Types of variable.1. Static variable: Any variable which is declared by using keyword static is called static variable.

The value of static variable is remain fixed for the other function but may change within samefunction boundary.2. Global variable: Any variable which is declared before main function is called global variable

this variable can be accessed from any member functions.3. Local variable: any variable which is declared within the function is called local variable. This

type of variable can be accessed within the same member function only.

Datatype in cA set of data that specifies the possible ranges of values in a program and stored in memory arecalled data types. Data types are used to define variables before use it. There are two types of datatype

1. Primary date types: the basic fundamental of data having unit feature on c programming iscalled primary data types. The example of primary data types are

1. Void type : void >> 0 byte2. Character Type : Chare >> 1 byte3. Number type : Int >> 2 byte, Float, Long >> 4 byte, Double >> 8 byte

The OperatorsOperators are special type of symbols or characters used to manipulate all type of dta used incomputer system. For example 5 +10 where + sign is an operator.

Types of Operators.1. Arithmetic operator:

Arithmetic or mathematic operator are used for mathematical manipulation. Formathematical manipulation, numerical data are used. Some mathematical operators are

Engineering Practicle

8. SoftwareCostEstimation

7. SoftwareQualityandQualityAssurance

Chapter 6.Verification andValidation

Chapter 5.Implementation andMaintenance

Chapter 4.SoftwareDesign

Chapter 3.SoftwareRequirements

Chapter 2.ProjectManagement

Chapter 1.Introduction toSoftwareEngineering

SoftwareEngineering syllabus(Diploma)

COMPUTERNETWORK

HOWSHOULDREAD ABOOKBETTER?

Home

PAGES

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 3/58

a.+ -> Addition or Unary plusb. - -> Subtractionc. * -> multiplicationd. / -> Divisione.% -> Modulo Division.

2. Relational Operator : The relational operators are used to compare two or more quantity.

Operators Meaning== Is equal to!= is not equal to< Less than<= Less than and equal to> Greater than

>= Greater than and equal to3. Logical operator:

it is used to combine two or more relational operators. It makes decision building block withrelational operator.

Operator Symbol ExampleAND && exp1 && exp2 OR || exp1 || exp2NOT ! !expl

4. Ternary operator: The ternary operator is C’s only ternary operator, meaning that it takes three operands. Itssyntax is exp1 ? exp2: exp3;

If exp 1 evaluates to true (that is, nonzero), the entire expression evaluates to the value of exp2. Ifexp1evaluates to false (that is, zero), the entire expression evaluates as the value of exp3. Forexample, the following statement assigns the value 1 to x if y is true and assigns 100 to x if y isfalse:x= y ? 1: 100;Likewise, to make z equal to the larger of x and y, you could write z= (x>y) ? x : y;Perhaps you’ve noticed that the conditional operator functions somewhat like an if statement. Thepreceding statement could also be written like this:if(x>y)z = x;elsez = y;The ternary operator can’t be used in all situations in place of an if...else construction, but theconditional operator is more concise. The ternary operator can also be used in places you can’t usean if statement, such as inside a single printf() statement:printf("The larger value is %d",((x >y)?x:y));

5. Comma operator:It permits two different expression to appear in situation where only one expression would ordinarilybe used.Example: {int a, b, c;c=(a= 10,b=20,a+b);print f("c = %d", c);}

StatementAny line written in a ‘c’ editor that normally terminates by a semicolon ‘;‘ is called statement.Examples:int a, b, c, d= 55; float rate;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 4/58

char n; etc.The different types of statements are:

a) Null statement:If you place a semicolon by itself on a line, you create a null statement--a statement that doesn’tperform any action. This is perfectly legal in C. Example:;- Null statement

b) Expression statement:An expression statement is a constant, variable or combination of constant and variable. This canalso include a function call. An expression statement consists of any valid C expression andfollowed by a semicolon.Examples:

a=b; -Expression statement c=a+b; - Expression statement

greater (a,b,c); -Function call

c) Compound statement:A compound statement, also called a block, is a group of two or more C statements within a pair ofbraces ({ and}). Unlike an expression statement, a compound statement does not end with asemicolon.Example:{ printf("Hello, "); printf("sathi!");}

In C, a block can be used anywhere a single statement can be used. Many examples of this appearthroughout this book. Note that the enclosing braces can be positioned in different ways.

d) Control statement:Control statements are used to create special program features, such as logical tests, loops andbranches. Examples:i) if(a>b)printf("A is greater");elseprintf("B is greater");ii) while

Comments And Escape SequencesAns: Comments are the statements that are used for user aid. Such statements are ignored by thecompiler. A comment is denoted by/ *……………. */ For multi statementsAnything written between this is ignored by the compiler// For single statementEscape sequence: These are the characters not printed when used but provide various functions.Escape sequences are always started with a backslash' \'. Commonly used escape sequences are:Character Escape sequencebell (alert) \abackspace \bhorizontal tab \tnew line \ncarriage return \rquotation mark \"backslash \\null \0 etc.

Symbolic constants: A symbolic constant allows a name to appear in place of numeric constant, character constant or astring. symbolic constants are usually defined at the beginning of the program. Symbolic constants

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 5/58

may appear later in the program in place of numeric constants, character constant and so on. Atthe time of compiling each occurrence of a symbolic constant get replaced by its correspondingcharacter sequence. Examples:#defineAND &&# define Pi 3.1412 # define True 1# define friend "Susan" etc.

Library functions: Many functions of C is carried out by library functions. These functions perform file access,mathematical computation graphics, memory management data conversion etc. A typical set oflibrary functions will include a large number of functions that are common to most C compilers.Examples : sqrt ( ), to lower ( ), to upper, abs ( ) etc.c) Header files: By placing thern required library function declaration in special source file is calledheader file.Or•Header files contain definitions of funètions and variables which can be incorporated into any Cprogram by using the pre-processor #include statement.Standard header files are provided witheach compiler, and cover a range of areas:string handling, mathematics, data conversion, printingand reading of variables, etc.•To use any of the standard functions, the appropriate header file should be included.This is done atthe beginning of the C source file. For example, to use the function printf() in a program, the line#include <stdio.h> should be at the beginning of the source file, because the declaration for printf()is found in the file stdio.h. All header files have the extension ii#include <string.h>#include <math.h>#incilude "mylib.h"

The use of angle brackets < > informs the compiler to search the compiler’s includedirectories for the specified file. The use of the double quotes" " around the filenameinforms the compiler to start tbe search in the current directory for the specified file.

Some commonly used header files are:stdio.h, conio.h, process.h, math.h, ctype.h, string.h, stdlib.h etc.

Data TypesData types are used to declare the variable name in C language. C supports different types of data,each of which may be represnted differently within the computer’s memory. There are the variousdata types and these are: Data type Data sub_ type Bytes Format Range Signed . character character 1 %c - 128 to 127 Unsigned character 1 %c 0 to 255

Numeric Short signed 2 %d -32768 to 32767

int Short Unsigned 2 %d Oto 65535 int Long signed int 4 %Id —2147483648 to 2147483647 Long unsigned int 4 %id 0 to 4294967295 Float 4 % f 3.4E—38 to 3.4E+38 Double 8 % if 1.7E—308 to 1.7E+308 Long double 10 %lf 3.4E-4932 to 3.4E + 4932

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 6/58

BranchingBranching is based on decision making. If the decision is satisfied, then it can perform the task,otherwise it executes the line next toit.The various branching statements are:(a) if ……………….else(b) if ……….else if ………………..else(c) switch. …. .case

Syntax of if,if..else and if..else if..else statement are:->The if Statementif(expression)statement];If expression is true, statement1 is executed. If expression is not true,statement1 is ignored.->The if..else Statementif(expression)statement1;elsestatement2;If expression is true, statement I is executed; otherwise, statement2 is executed.->The if..else if..else Statementif(expressionl)statement1;else if(expression2)statement2;elsestatement3;If the first expression, expression!, is true, statement] is executed before the program continueswith the next_statement, If the first expression is not true, the second expression, expression2, ischecked. If the first expression is not true, and the second is true, statement2 is executed. If bothexpressions are false, statement3 is executed. Only one of the three statements is executed at atime.

LoopingLooping is a process which allows the data to be repeated unless or until some condition has beensatisfied. The various looping statements are:(a) for(b) while(c) do whileSyntax of while,for and do while statement are:a) forsyntax>for (exp1; exp2; exp3){ statement1; ………………….

}where,exp1 = Initial expressionexp2=Conditional expressionexp3=Increment or decrementWhen a for statement is encountered during progrars execution, the following events occur:1. The expression, exp1 is evaluated. exp1 is usually ai assignment statement that sets a variableto a particular valuer2. The expression, exp2, i.e. condition is evaluated, condition i typically a relational expression.3. If exp2, i.e.condition evaluates to false (that is, as zero), th for statement terminates, andexecution passes to the fir statement following statement.4. If exp2, i.e. condition evaluates to true (that is, as nonzero the C statement(s) in statement areexecuted.5. The exp3, i.e. increment or decrement is evaluated an execu.tion returns to step 2.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 7/58

B) Whilesyntax>while (condition){ statement 1; …………….}When program execution reaches a while statement, the following events occur:

1. The expression condition is evaluated.2. If condition evaluates to false (that is, zero), the while statement terminates, and executionpasses to the first statement following statement.3. If condition evaluates to true (that is, nonzero), the C statement(s) in statement are executed.4. Execution returns to step 1.

C) Do Whilesyntax: do{statement 1; statement 2; ……………….

} while (condition);When program execution reaches a do...while statement, thefollowing events occur:1. The statements in statement are executed.2. condition is evaluated. If it’s true, execution returns to step 1. If it’s false, the loop terminates

Infinite LoopA loop that has no stopping or never ending condition is called an infinite loop. Example:

for(; ;) while(1){ } { }

Break: The "break" statement is used to terminate the control from the loop.It is normally used inswitch-case statement,the break statement must be used if not the control will be transferred to thesubsequent case condition also. Example:#include<stdio.h>#include<conio.h>void main( ){ int a =1; while (a < 20) {

a = a + 1; if (a%3= =O) break; printf ("%d",a); } getch();}

Continue: The "continue" statement skips the rest of execution of the loop. Example:#include<stdio.h>

#include<conio.h>

Result:2

Result:2 4 5 7 8 10

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 8/58

void main(){ int a =1; while (a < 10) { a=a+ 1; if (a%3==0) continue; printf (‘%d",a); }getch();{Differentiate between ‘for and ‘while’ statements.

For Whilea) The for statement executes the

initial expression first. It thenchecks the condition, If thecondition is true, the statementsexecute. Once the statements arecompleted, the incrementexpression or decrement isevaluated. The for statement thenrechecks the condition andcontinues to loop until the conditionis false.

It allows repeated execution of a statementor block of statements as long as thecondition remains true (nonzero). If thecondition is not true when the whilecommand is first executed, thestatement(s) is never executed.

b)syntax>for (exp1; exp2; exp3){ statement1; ……………..}where,exp1 = Initial expressionexp2=Conditional expressionexp3=Increment or decrement

syntax>while (condition){ statement1; ……………….}

Example:Displaying 1 to 10 numbers# include <stdio.h># include <conio.h>void main ( ){ int a; for (a = 1; a <= 10; +÷a) printf("%d\t", a); getch( )}

Example: Displaying 1 to10 numbers include <stdio.h># include <conio.h>void main (){ int a; a= 1; while (a <= 10) { printf("%d\t", a); a=a+1; }getch();}

Differentiate between ‘while’ and ‘do while’ statements. [HSEB-2061,2062]Ans: Differentiation between while and do while statements:

While Do while

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 9/58

a) It allows repeated execution ofa statement or block ofstatements as long as thecondition remains true(nonzero). If thecondition isnot true when the whilecommand is first executed, thestatement(s) is never executed.

The do while statement executes a body ofinstruction at least one time and more if anexpression remains true.

a) syntax: while (condition){ statement 1; statement 2; ………………}

syntax: do{ statement 1; statement 2; ………………} while (condition)

Example: A program forprinting 1 to 10 nos.

# include<stdio.h># include<conio.h>void main (){ int a; a= 1; while (a <= 10) { printf("%d\t", a); a = a + 1; }getch( ) ;}

Example: A program forprinting 1 to 10 nos.# include<stdio.h>#include<conio.h>void main (){ int a= 1; do { printf("%d\t", a); a=a+1; } while (a <=10); getch( ) ;}

Differentiate between local and global variables.Differentiation between local and_global_variables:

Local variable Global variable

a)It is the way to declare thevariable. A variable is declared within ablock is called a local variable to that block.

b)Example:void main (){inta= 10;// local to//main

A variable declared outside ablock that is available to other black of theprogram is called a global variable.

Example:int a = 10; // global variablesvoidmain(){int a=6;

switch case statementSyntax:switch (variable_name){ case value 1 …………………. break; case value2: ……………………. break; case value3: ………………..

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 10/58

break; default: ……………………}example : int a; printf("Enter number of day:"): scanf("%d",&a); switch (a){case 1: printf ("Sunday"); break;case 2: printf ("Monday"); break;case 3: printf("Tuesday"); break;case 4: printf("Wednesday"); break;case 5: printf’Thursday"); break;case 6: priritf("Friday"); break;case 7: printf("Saturday"): break default: printf ("nor the value"); exit(O);}and an example of "goto" statement.The goto statement is used to alter the normal sequence of t program execution by transferringcontrol to some other parts the program.syntax> goto / identifier;Example: A program for finding odd or even numbers by usii GOTO statement.# include <stdio.h># include <conio.h>void main ( ){ int n; char ch; x : clrscr ( ); printf("Enter any number ="); scanf("%d", & n); if (n% 2 = =0) printf ("Even number"); else printf ("Odd number"); printf("Do you want to continue (Y/N) = "); scanf("%c", ch); if(ch = = ‘Y’ // ch = 'y') goto x; getch();}

Getchar And Putchar Function With Limitation

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 11/58

Getchar: It returns only one character at a time from a standard input device. The getchar acceptall type of characters even space, tab, blank, return. This function has the limitation, i.e. this isn’tused for numeric operations and also not used for looping.Example:# include<stdio.h>#include<conio.h>void main (){ char C; c = getchar (); printf("\n input character = %c", c); getch();}

Putchar: It transmits a single character to a standard output device. This function accepts all typesof characters even space, tab, blank. This function has also the limitation, that isn’t used fornumeric operation and not displaying for loops.Example:# include <stdio.h>#include<conio.h>void main ( ){ char ch; printf("Enter any letter:- "); ch = getchar (); printf ("output"); putchar (ch); getch();}

Format SpecifierFormat specifiers are characters starting with % sign and followedwith a character. It identifies the data type that is being processed.It is also known as "conversion specifier".Some of character specifications used with format specifiers are: Character Meaning % First character — (minus sign) Used for left justification. w Used for specifying width of field. • (dot) Used for specifying decimal part. p Used for specifying precision. List of format specifiers symbol. Data type Format specifier symbol used Integer %d Unsigned integer % u Octal % o Hexadecimal % x Float % f Float (scientific or exponential) %e character %c string %s

Example:main (){ int r; float a; r 2; a = 12.562, 01547; printf ("%d", r); // prints 2 at initial position of screen printf ("%l0d’, r); // prints 2 leaving 10 spaces. Righ justified.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 12/58

printf ("%-d", r); // prints 2 left justified printf("%f",a); // prints 12.56201547 printf("%10.2f",a); //prints 12.56 leaving 10 spaces printf("%e"a); // prints l.256201c + 01 printf ("%15.2e",a) //prints 1.25e + 01 leaving 15 space Right justified.

}

Nested LoopA loop inside the loop is called nested loop.

Write a program to calculate area and circumference of a circle1. Where radius of a circle is in puted and define pi as constant.#include<stdio.h>#include<conio.h>#define pi 3.14void main(){

int r; float a,c; printf("Enter value of radius="); scanf("%d" ,&r);

a=pi*r*r; c=2*pi*r;

printf("Area=%.2f\n" ,a); printf("\nCircumsatances=%.2f",c); getch();}2. Write a program that read principle, time and rate to calculate simple interest and totalamount.#include<stdio.h>#include<conio.h>void main(){ int p,t; float r,si,ta; printf("Enter Principle="); scanf("%d" ,&p); printf("Enter time="); scanf("%d" ,&t); printf("Enter rate="); scanf("%f’,&r);

si=(p*t*r)/100 ta=si+p;

printf("Simple Interest=%.3fn" ,si); printf("\nTotal Amount=%.3f" ,ta); getch();}

3. Write a program to convert temperature in Fahrenheit (F) into centigrade (c). [F = 1.8 c +321#include<stdio.h>#include<conio.h>void main (){ Int f;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 13/58

float C; printf ("\n enter temp in fahrenheit ="); scanf (‘%d’, & f); c=(f-32)/1.8; printf ("Result = %.2f", c); getch ();}

4. Write a program to supply length and breadth of a rectangle. Find out area and perimeter.#include <stdio.h>#include <conio.h>void main ( ){ int l, b, a, p; printf ("Enter breadth & length ="); scanf ("%d%d", &b, &l); a = l*b; p=2*(l+b); printf ("Area of a rectangle = %d\n", a); printf ("Perimeter of a rectangle = %d\n", p); getch ( );}

5. Write a program that accepts an integer and checks whether it is divisible by 3 and 5 ornot.#include<stdio.h>#inciucie<conio.h>void main(){ int a; printf("Enter an integer="); scanf("%d",&a); if(a%3= = 0 && a%5= =0) printf ("Divisible by 3 and 5."); else printf("Not divisible by 3 and 5"); getch();}6. Write a C program to read any number and check whether th entered number is divisibleby 5 but not by 11. [HSEB 2065]

7. Write a program to enter any year and check whether the entered year is leap or not.#include<stdjoh>#include<conjo.h>void main (){ int year; printf ("Enter year = ‘); scanf("%d", & year); if(year% 400 = = 0 || year % 100! = 0 && year% 4 = = 0) printf ("Leap year"); else

printf ("Not a leap year ="); getch();}

8. Write a program that asks cost of price(CP) and selling price(SP) and determine whether

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 14/58

there is gain or loss. [HSEB-2066}#include<stdio.h>#include<conio.h>void main(){ int CP,SP,loss,gamn; printf("Enter value of CP and SP:"): scanf("%d%d", &CP,&Sp); if(SP>CP) {

gain=SP-CP;printf("GamnRs%d",gain);

} else {

loss=CP-SP;printf("Loss Rs%d" loss);

}getch();}9. Write a program of NTC to enter number of calls and find out total, vat (10% of total),telecom service charge (10% of total + tsc) and total amount. The rate of total is given below:Number of callsnumber of call <=175otherwise, number of call is more than 175#include<stdio.h>#include<conio.h>void main(){ int noc; float total, vat, tsc, tarnt; printf ("Enter total number of calls ="); scanf ("%d", &noc); if(noc <=175) {

total = 200;tsc = total * 101100;vat = (total + tsc)* 10/100;tamt total + vat + tsc;printf ("Total amount = %f", tamt);

} else {

total = 200 + (nec — 175)*2;tsc = total * 10/100;vat = (total + tsc) * 10/100;taint = total + vat + tsc;printf ("Total amount = %f’, tamt);

}getch( );}

10. Write a program to enter any three numbers and find out the middle number.

11. Write a menu driven program which has the following option1 .Perimeter of circle2.Perimeter of rectangle3.Perimeter of triangle #include <conio.h>#include <stdio.h>

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 15/58

void main(){ int choice; printf("Enter choice 1 for perimeter of circle\n"); printf("Enter choice 2 for perimeter of rectangle\n"); printf("Enter choice 3 for perimeter of triangle\n"); printf("Enter your choice:\n"); scanf("%d",&choice); switch(choice) {case 1: {

float rad, per;printf("\nEnter the radius of circle");scanf("%f’ ,&rad);per=(2*22*rad)17;printf("\nThe perimeter of circle is: %f",per);break;

}case 2: {

int b,l,per;printf("\nEnter the breadth of rectangle:\t"); scanf("%d" ,&b);printf ("\nEnter the length of rectangle:\t");scanf("%d" ,& l);per = 2 *(l+b)printf ("\nEnter the perimeter of rectangle is:\d" , per);break;

}case 3: {

int a,b,c,per;print("\nEnter the sides of the triangle\n");printf("\nEnter the first side:\t");scan("%d",&a);prinf("\nEnter the second side:\t");scasf(" %d", &b);printf("\nEnter the third side:\t");per=a+b+c;prinrf("\nThe perimeter of triangle is: %d",per);break;

}default {

print("wrong choice") ; }getch();return 0;}

12. Write a program to find sum of 1 to 100 numbers.#include <stdio.h>#include<conio.h>void main(){ Int d n, sum = 0; for (n = 1; n < = 100; ++n)

{sum = sum + n;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 16/58

printf ("sum =%d", sum);}

getch ( );}

12. Write a ‘C’ program to print all from A to Z13. Write a program to compute factorial for a given number i where n is a non-negativeinteger,[n!=1*2*34 (n1)*n].14. Write a program to print the series 1,5,9,13 upto 10th terms.

15. Write a C program to read any number and entered number is palindrome or not.#include<stdio.h>#include<conio.h>void main({ int n,num,rev=0,r; printf("Enter any number"); scanf("%d",&num); n=num; while(num!=0){

r=num% 10;rev=rev *10+r;num=num/10;

} if(n==num)

printf("The entered number is palindrome"); else

printf("The entered number is not palindrome");getch();}

16. Write a program to display Fibonacci series upto 10 terms. ie.g.0112358#include<stdio.h>#include<conio.h>void main(){ int a, b, c, j; printf ("\n the series’); a = 0; b = 1; printf ("%d \t%d\t", a, b); for(j = 0;j <10;j+ +) {

C = a + b;printf ("%d\t", c);a = b; b = C;

} getch ();}

17. Write a program to input an integer number and checks whether it is prime or not.[HSEB-2066]18. Write a program to print multiplication table of first 10 natural number.

(Nested Loop)19. Write a program to print multiplication table of first 10 natural number.#include<stdio.h>#include<conio.h>

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 17/58

void main(){ int i,j,c; for(i= 1 ;i<= 1 0;++i) {

for(i= 1 ;j<=10;++j){C=i*j;printf(%d*%d=%d\t",i,j,c);

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

20. Write a program to display factorial number of first 10 natural number. #include<stdio.n>#lnclude<conlo.n>void main(){int i,j,ffor(i=1;i<=10;÷+i) {

f=i*j;for(j=i;j>O;--j) {

f=f*jprintf( %d=%d\n ,i,f);

} }getch();}

21. Write a program to display prime number upto 500 numbers.#include<stdio.h>#include<conio.h>void main(){ int i,j; for(i=2;i<=500;++i) { for(j=2;j<=i;++j) { if(i%j==0) break; } } if(i==j) printf( "%d\t",i);getch();}

22. Write a program to generate the following:12 23 3 34 4 4 45 5 5 5 5#include<stdio.h>#include<conio.h>

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 18/58

void main(){ int i,j; for(i=1;j<=5;++i) { for(j=1;j<=i;++j) { printf("%d",i); } printf("\n"); } getch(); }23. Write a program to display the following series:12 23 3 34 4 4 45 5 5 5 5#include <stdio.h>#include <conio.h>voidmain(){int n,a,j;for(a=1;a<=5;a++) { for (j= 0; j < = 5-a ; j+ +) { printf (" ") for(j=1;j<=a;j++) { printf ("%d ", a); printf ( "\n" ); } }getch ();}

24. Write a program to generate the following:112123123412345#include<stdio.h> #include<conio.h>void main(){ int i,j; for(i=1 ;i<=5;++i) { for(j= 1 ;j<=i;++j) { printf("%d" ,j); } printf("\n"); }getch();}

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 19/58

25. Write a C Program to display the following:555554444333221#include<stdio.h>#include<conio.h>void main(){ int i,j; for(i=5;i>=0;--i) { for(j= 1 ;j<=i;++j) { printf( "%d" ,i); } printf"(\n"); }getch();}

26. Write a program to display the following table:10 20 30 4020 30 40 5030 40 50 604050 60 70#include<stdio.h> #include<conio.h>void main(){ int i,j; for(i=0;i<=4;++i) { for(j= 1 ;j.<=4;++j) {

printf("%d\t",(i+j)* 10);}

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

27. Write a C program to display the pyramid of numbers for a given number. 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 1 2 3 4 5 6 5 4 3 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1#include<stdio.h>#include<conio.h>void main(){ int n,a,j,k; printf("Enter a number to form a pyramid:"); scanf("%d",&n); printf("\n\t\n\t"); for (a = 1; a < =n; a ++)

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 20/58

{ for(j = 1;j<=n-a;j ++) { printf (" "); for (k=1 ;k<=a;k++) { printf ("%d", k); for (k=a-1 ;k>0;k--) { printf("%d ", k); printf ("\n\t\t"); } } }getch ();}28. Write a program to display the following series12345 678 9 1011 12 13 14 15 [i.e.Floyd’s Theorem]#include<stdio.h>#include<conio.h>void main(){int i,j=l,k;for(i= 1 ;i<=5;++i) { for(k =1 ;k<=i;j++,k++) { printf("%dt",j); } printf("\n");}getch();}

Or,#include<stdio.h>#include<conio.h> void main(){int i,j,sum=0;for(i=1 ;i<5;++i) { for(j=0;j<i;++j) { sum=sum+1; printf("%d\t",sum); }printf("\n");}getch();}

ArrayAn array can be defined as a set of finite number of homogeneous elements or data items. It

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 21/58

means an array can contain one type of data only, either all integers ,all characters, all floatingpoint etc. The individual data items are represented by their corresponding array elements(i.e. firstdata item is represented by first array element, second data item is represented by second arrayelement and so on). The individual array elements are distinguished from one another by the valuethat is assigned to a subscript.

Declaring of an arrayint a[5];Where int specifies data type of elements array, "a" is the name of array and number specifiedinside the square brackets is number of elements an array can stores.Followings are some of the concept to be remembered about arrays:a) The individual element of an array can be accessed by specifying name of array, followed byindex or subscript inside square brackets. Example: int 45];b) The first element of array has index zero[0].It means first element and last element will bespecified as a[0] and a[4] respectively.c) The elements of array always be stored in consecutive memory locations.d) The size of array is given by (Upperbound-lowerbound)+1(4-0)+ 1 =5.where O=lowerbound and 4=upperbound.e) Arrays can be read or written through loop.If we read a one- dimensional array, it requires oneloop for reading and writing.If we are reading or writing two-dimensional array it would require two loops. Sirnilarly array of ndimension would require n loops.There are two types of array and these are(a) One-dimensional array(b) Two- dimensional array(a) One dimensional array: It consists only either rows or columns.syntax> data _ type array_name [expression];e.g. int marks [500];char sentence [100];float percentage [8]; etc.(b) Two dimensional array: It consists both rows and columns. syntax> data — type array name[expression 1] [expression2];e.g.int matrix [5] [5];char name [10] [30]; etc.

1. Differentiate between one-dimensional and two-dimensional array.Differentiation between one-dimensional and multi-dimensional array:

One-Dimensional array Two-dimensional arraya)Only one subscript is used inone-dimensional array

Two subscript is used in two-dimensional array.

b) Syntax>data_type array_name [subscript];Examples:char name[20];int marks[5]; etcHere, subscript is used to denote either rowsor columns.

Syntax>data_type array_name [subscript 1][subsc ript2];Examples:int marks[100][5];int matrix[5][5]; etc. Here, subscriptl is used todenotes rows and subscript2 denotes columns.

c) Only one loop statement is used to createor retrieve array elements,

Two looping statements are used to create orretrieve array elements, i.e. first loop for rowsand second loop for columns.

d) Example: Display name & age of a student.#include <stdio.h>#include <conio.h>void main (){ char name [20]; int age;

Example: Display elements of a matrix:#include <stdio.h>#include <conio.h>void main (){ int matrixa[2] [2],i,j;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 22/58

printf ("Enter name:"); gets (name); printf ("Enter age \n"); scanf("%d", &age); printf ("\n Name :%s", name); printf ("Age:%d", age); getch();}

printf("Enter elements of a matrix:"): for(i=0;i<2;++i) { for(j=0;j<2;++j) scanf("%d",&matrixa[i] [ii); }//Displaying data for(i=0;i<2;++i) { for(j=0;j<2;++j)

printf("%d\t",matrixa[i] [j]); printf("\n") ; } Getch();}

String FunctionA string is a group of characters of any length. The string enclosed within double quotation marks isknown as a literal. For example, "Hello" is literal. We can use such strings in our programs todisplay various kinds of messages on the screen. The strings can be stored and manipulated asarray of characters in C and C++. The last character in a string is always ‘\0’, a null character. Forexample, the string "PROGRAM" can be stored in an array as 0 1 2 3 4 5 6 7

P R O G R A M \0

items

The string requires total 8 locations of array item: seven for the alphabets in the string PROGRAMand one for the null character. The array item can be declared as:char item[8];Other examples of array declarations are:int x[25];char name [20];float sal[15];Array declarations that include the assignment of initial values areint x[5] = { 56, 42, 90, 65, 55 }; x[0] x[1] x[2] x[3] x[4]or char text[6] = { "today"};

chartext[6] ={

‘t’ ‘o’ ‘d’ ‘a’ ‘y’ ‘\0’ };

Text[0]

Text[1]

Text[2]

Text[3]

Text[4]

Text[5]

Text

intA[4][3] = { 5, 2, 7,3, 9, 6,1, 7, 89, 2, 3};

int list[5][10] = { "Ram","Shyam","Han","Gopal","Rampayri" };

Differences Between Array And Unions With Syntax.Differentiation between structure and unions:

Array UnionArray is the collection ofdata items which will havethe same name.

Union is a collection ofheterogeneous data types

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 23/58

Each element has specificmemory space

Each element has no specificmemory space but spaceallocated for largest elementis isutilized by other sized element.

Keyword is not required todeclare array,

Keyword is required to declareunion

Array has its type and these are:(i) one dimensional array(ii) multi dimensional array

Union has no type

The syntax of array:(i) One dimensional array:data_type array_name [sizeof array];It consists only rows or columnsi.e. char name [20];(ii) Two-dimensional array:data_type array_name[expl] [exp2];e.g. char name [5] [25];It contains rows & columns.

Syntax of union:union user_defined_name{ data_type member 1; data_type member2; ……………. data_type membern;} union user_defined_name van, var2 e.g struct student { char name [20]; int age; };union student one;

Example : Display name & age:#include <stdio.h> #include <conio.h>void main (){ char name [20]; int age; pnintf ("Enter name:"); gets (name); printf ("Enter age \n"); scanf ("%d", &age); printf ("\n Name :%s", name); printf("Age:%d", age); getch () ;}

Example: Display name & age:#include <stdio.h> #include <conio.h>void main (){ union student { char name [20]; int age; } one; printf ("Enter name :\n"); scanf ("%s", one.name); printf ("\n Enter age:"); scanf ("%d", &one.age); printf ("\n Name : %s",one.name); printf ("Age :%d", one.age); getch();}

1. Write a program to display the following numbers.3,56,76,5,90#include <stdio.h> #include <conio.h>void main (){ int i,num[5]={ 3,56,76,5,90}; printf("List of number\n"); for(i=0;i<4;++i) printf("%d" ,num[i]);getch();

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 24/58

}

Write a C program to read age of 100 person from keyboard,display it in proper format.#include<stdio.h>#include<conio.h>void main (){int i,num[100];//Giving input from keyboardfor(i=0;i<lOO;++i){ printf( Enter age of 100 persons: ") scanf ("%d",&num[i]);}//Displaying age of 100 personsprintf("List of number\n");for(i=0;i<100;++i) printf("%d" ,num[i]);getch():}

3. Write a C program to read 10 numbers and print them in reverse order#include<stdio.h>#include<conio.h>void main(){int num[10],i;for(i=0;i<O;i++) { printf( Enter a number: ); scanf("%d",&num[i]); } printf("The number in reverse order are:"); for(i=9;i>0;i--) printf("%d\n\t\t\t\t",num[i]); getch();}

4. Write a program to store ten different constant variables in any array and print out thegreatest number. [HSEB-2064]#include <stdio.h>#include <conio.h>void main (){ int a[10]={100,1,23,43,56,21,80,54,67,2}; int i, large; large= a [0]; for(i=0;i<10;i++) { if (large < a [i]) large = a[i]; } printf ("\n largest no = %d", large); getch ();}5. Write a ‘C’ program to read salaries of 200 employees and count the number of employeesgetting salary between 5000-10000. [HSEB-2062]#include <stdio.h>#include <conio.h >void main ()

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 25/58

{ int count = 0, salary [200], i; // Reading salary of 200 employees for (i= 0; i< 200; i++) { printf (" Enter salary :" ); scanf ("%d", & salary [i]); } //counting number of employees getting salary between //5000 - 10000 for (i = 0; i < 200; i ++) { if (salary [i]> 5000 && salary [i] < 10000) count + +; } printf ("Total number of employees getting salaries between 500-10000 = %d", count); getch();}

The marks obtained by a student in a 7 different subjects are entered through the keyboard.The student gets a division as per the following rules:Percentage greater or equal to 60 First divisionPercentage between 45 and 59 Second divisionPercentage between 35 and 44 Third divisionPercentage less than 35 FailWrite a program using C language to process result of all’ students based on specificationstated above.#include <stdio.h>#include <conio.h>void main (){ char name [20]; int i; float x [7], per, total = 0; printf ("Enter name ="); scanf ("%s", name); for (i= 0; i< 7; i++) { printf ("Enter mark of a subject ="); scanf ("%f", &x [i]); total = total + x [i]; } printf ("\n\n"); per = total/7; printf ("Name %s\n", name); printf ("Total = % f\n", total); printf ("Percentage = %fn", per); if (per>60) printf ("First division\n"); else if (per> = 45) printf ("Second division\n"); else if (per> = 35) printf ("Third division"); else printf ("Fail\n");getch ();

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 26/58

}

7. Write a program using C language to read the age of 100 persons and count number ofpersons in the age group between 50 and 60. Use "For" and "Continue" statements. [HSEB2061]#include <stdio.h> #include <conio.h>void main (){ int age [100]; int i, count 0; //Reading the age of 100 persons for(i=0;i<100;i++) {

printf ("Enter age of a person :");scanf("%d", & age [i]);

} //Comparing age group between 50 & 60 for (i= 0, i< 100; i++) { if (age [i] > = 50 && age {i] <= 6O) count + +; continue; } printf ("Total number of persons in the age group between 50 and 60 are: %d", count); getch();}

8. Write a program to find whether the given number is palindrome or not.#include <stdio.h>#include <conio.h>void main (){ int a[10],num,i=0,result=O,n; printf("Enter the number:"); scanf("%d",&n); num=n; while(num!=0) { result=result* 10; a[i]=num%10; num=num/ 10; result=result+a[i]; ++i; } if(result==n) printf("The number is palindrome"); getch();}

9. Write a ‘C’ program to input ‘n’ numbers and find out the greatest and smallest number.[HSEB 2O62]

#include <stdio.h> #include <conio.h>void main (){ int n, i, max, a[100], min; printf ("How many nos ?"); scanf ("%d", &n);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 27/58

//Reading numbers for(i=0;i<n;i++) { printf ("Enter numbers :"); scanf("%d", &a [i]); } // Finding the greatest and smallest number. max=a[O]; min=a[0]; for(i=0;i<n;i++) { if (a [i] > max) max = a[i]; else if( a[i]<min) min = a[i]; } printf ("The greatest number %d\n", max); printf ("The smallest number = %d", min); getch ();}

10. Write a program, which reads marks of N students in an array and add a grace of 10marks to every element of the array.#include<stdio.h>#include<conio.h>void main(){ int n,i,mark[ 10] ,sum[1 0]; printf("Enter how many students:"); scanf("%d" ,&n); printf("\n\n"); for(i=0;i<n;i++) { printf("Enter mark:"); scanf("%d",&mark[i]); sum [i]=mark[i] + 10; } printf("\n\n"); for(i=0;i<n;i++) printf("The mark of studit after adding a grace 0f 10 marks:%d\n",sum [i]);getch();}

11. Write a program to enter ‘n’ numbers into one dimensional array and sort and displaythem in ascending order.[HSEB-2065]#include <stdio.h>#include <conio.h>#define MAX 500void main (){ int a [MAX], i, j, n, temp; printf ("How many numbers ?"); scanf ("%d", &n); for(i=0;i<n;i++) { printf ("Enter numbers ="); scanf ("%d",& a [i]); } for(i=0;i<n;i++) { for (j = i+1; j < n; j ++)

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 28/58

{ if(a [i]> a [i]) { temp = a[i]; a[i]=a[j]; a [j] = temp; } } } printf (‘Sorted array\n"); for(i=0;i<n;i++) { printf ("%d\t", a[i]); } getch();}

12. Write a program to read a set of ‘n’ numbers from the standard input device and to sortthem in descending order.

13. Write a C program that reads name and mark of 10 different students and prints them intabular format.

14. Write a program to input names of ‘n’ number of students and sort them in alphabeticalorder. [HSEB-2062]#include <stdio.h>#include <conio.h>#include <string.h>void main (){ char name [100] [100], temp[100]; int i, j, n; printf ("Enter number of students ="); scanf("%d’, &n); for(i=0;i<n;i++) { printf ("Enter name :"); scanf (‘%s", name [ii); fflush (stdin); } for(i=0;i<n;i++) { for (j = + l;j <n;j + { if(strcmpi (name [i], name [j]) > 0)

{ strcpy(temp, name [i]);

strcpy (hame [i], name [j]); strcpy (name [j], temp); } }

} for(I =0;I < n;I ++) { printf ("%s\n", name [1]); } getch ( );} 15. Write a C program to read anme and address of 5 different students,sort them inalphabetical order.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 29/58

#include<stdio.h> #include<conio.h> #includecstring.h> void main( ){ char name[5] [80] ,add[5] [80] ,temp[80,temp 1 [80]; int i,j;

printf("enter name and age:"); for(i=0;i<5 ;i++) scanf("%s%s" ,name[i] ,add [i]);for(i=0;i<5 ;i++){for(j=i+1 ;j<5;j++) if(strcmp (name [i] ,name [3]) >0){ strcpy(temp,name[i]); strcpy(name [i] ,name[j]); strcpy(name [j] ,temp);

strcpy(temp 1 ,add[i]) strcpy(add[i],add[j]); strcpy(add [j] ,temp 1);}}printf("The result\n"); for(i=0;i<5 ;i÷+) printf("%s\t%s\n" ,name[i] ,add[i]);

getch();}

16. Write a C program to read elements of any two matrices and sum of them. Or,Write a program to add two matrices. [HSEB 2065]#include <stdio.h> #include <conio.h>void main (){ int a[5][5], b[5][5], c[5] [5], i, j; Printf ("Enter the elements of matrix A = "); for (i= 0; i< 5; i+ +) { for (j= 0; j< 5; j+ +) { scanf("%d",&a[i][j]); } }printf ("Enter elements of matrix B ="); for (i= 0; i< 5; i+ +) { for (j= 0; j< 5; j+ +) { scanf("%d",&b[i][j]); } } for (i= 0; i< 5; i+ +) { for (j= 0; j< 5; j+ +)

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 30/58

{ c[i][j] = a[i][j] +b[i][j]; } } for (i= 0; i< 5; i+ +) { for (j= 0; j< 5; j+ +) { printf("%d\t",c[i][j]); } }getch();}

17. Write a program to find row sum and column sum of a matrix

18. Write a program to obtain transpose of a 3X3 matrix. Ans: #include <stdio.h>

19. Write a program to read a set of numbers from keyboard and to sort out the given array ofelements in ascending order using a function.

21. Read the maximum and minimum temperature of 7 days of Kathmandu Valley andcreates a function to calculate minimum and maximum temperature, also find the averagetemperature.

22. Write a program to enter 10 different number in array variable and check whether theentered number is prime or not usin function.#include <stdio.h>#include <conio.h> #include <process.h> void check (int n);void main (){ int n[10], i; for (i=0;i< 10;i++) { printf ("Enter 10 different numbers :"); scanf("%d", &n [i]); check (n [i]); } getch(); } void check (int n) { int i; for (i = 2; i < = n/2; i ++) {

if (n % i = = 0) { printf ("Not prime"); exit (0); } printf ("\n Prime number");

} }23. Write a program to enter a string and count total number of alphabet "A" occured in thestring.#include <stdio.h> #include <conio.h>void main (){

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 31/58

char sen [50]; int count = 0; printf ("Enter a sentence:"); gets (sen); for (i = 0; sen [i] ! = ‘\O’, i ++)

{ if(sen [i] = = ‘A’ && sen [i] = = ‘a’) count=Count+ 1;}

printf ("Total no. of alphabet of occurred in a sentence : %d" count); getch();}24. Write a program to read a line and replace space by ".

25. Write a program to input a message from keyboard and displaythe menu.1. Print message length in terms of characters2. Print the message in re’’erse order3. Print the message in capital letters4. Copy the message from one location of screen to another location5. Check the palindrome6. Exit#include <stdio.h>#include <conio.h>#include <string.h>#include <process.h>void main (){ char str [40], dest [40], dest2 [40]; int choice, l; printf ("Main menu"); printf ("1. Print message length \n"); printf ("2. Print message in reverse order \n"); printf ("3. Print the message in capital letters \n"); printf ("4. Copy the message from one location to another\n"); printf ("5. Check the palindrome \n"); printf ("6. Exit \n\n"); printf ("Enter your choice (1/2/3/4/5/6):"); scanf ("%d", & choice); switch (choice) {case 1:

printS ("Enter a string\n"); gets (str);l= strien (str);printf ("Length of message = %d", 1); break;

case 2printf ("Enter a string \n");gets (str);printf ("String in reverse order \n");printf ("%s", strrev (str));break;

case 3:printf ("Enter a string \n"); gets (str);printf ("%s", strupr (str));break;

case 4printf ("Enter a string \n");

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 32/58

gets (str);strcpy (dest, str);printf ("copied string : %s", str);break;

case 5printf ("Enter a string :");gets (str);strcpy (dest, str);strcpy (dest2, strrev (dest)); if (strcmp (str, dest2) = = 0)

printf ("Palindrome \n");else

printf ("Not palindrome"); brealqcase 6:

exit (0);default:

printf ("You aren’t allowed to type otheis\n");exit (0);

} getch();}

27. Write a menu drIven program which has the following options:1. Reverse order2. Ascending order3. Descending order#include <stdio.h>#include <conio.h> #include <process.h> void main (){ Int i, num [10], ch, temp; printf ("Enter 10 numbers \n"); for (i= 0; i< 10, i++) scanf("%d", & num [i]);

printf ("Main menu printf("l. Reverse order \n"); printf ("2. Ascending order \n"); printf ("3. Descending order \n"); printf ("4. Exit \n"); printf ("Enter your choice (1/2/3/4):".); scanf ("%d", & ch); switch (ch) { case 1 for(i = 9; i >= 0; i——)

printf (" % d\t", num [i]); break;

case 2: for (i= 0; i < = 9; i ++) { for(j=i+1;j<9;j++) {

if(num [i] > num [j]) {

temp = num [i];num [i] = num [j];num [j] = temp;}

}

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 33/58

printf("%d\t", num [i]); }

break; case 3: for(i=0;i<9;i++) { for(j=i+1;j<9;i++) {

if (num [1] <num [i]){ temp = num [i];

num [i] = num [j]; num [j] = temp;

}}printf ("%d \t’, num [i]);

}break;

case 4: exit(0); default:

printf (\n Not allowed to type other’);exit (0);

}getch();}28. Write a program to read 10 different names and age into an array and sort them inascending order by age and print sorted list.#include<stdio.h>#include<conio.h>#include<string.h> void main (){ char name [10] [30], name1 [30]; int age [10],i, j, temp; for(i=0;i< 10;i++)

{printf ("Enter name \n") scanf ("%s", name[10]);printf ("Enter age \n");scanf("%d", &age [i]);}

for(i=0;i< 10;i++){ for(j=i+1;j < 10;j ++) { if (age [i] > age [j]) { temp = age [i];

age [i] = age [j]; age [j] = temp;strcpy (name1, name [i]); strcpy (name [i], name[j]); strcpy (name [j],name1);}

}}print1 (" \n Name \ t \tAge \n"); for(i=O;i< 10;i-q-+)printf(" % s t \t %d\n", name [i], age [i]);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 34/58

getch ();}

29. Write a program that reads a line and count the number of letters, vowels, consonants,words and blank spaces present in the line.

30. Write a program which will ask the user to input a single character and then a string andwill count the occurrence of that character in that string.

31. Write a program that reads a string and prints the string in1. UPPER CASE2. Sentence case3. Title Case4. toGGLE cASE

32. Write a program that will print all the rotations of a word typed into it. [e.g. space, paces,acesp, cespa, espac]

33. Develop a program that will read and store the details of a list of students in tabularformat and produce the following outputlists:1. Alphabetical list of names, roll number and marks obtained.2. List sorted on roll numbers.3. List sorted on marks.

34. Write a program that reads the name, roll number and marks in5 different subjects of 10 students, and prints name, roll and total marks obtained by eachstudent in tabular form.#include<stdio.h> #include<conio.h>void main ()int i,j,roll[10],total[1 0] ,mark[10] [5];char name [10] [20];for (i =0; i < 10; i++){ printf ("Enter name :"); scanf ("%s \n", name[i]); printf ("Enter roll number :\n"); scanf ("%d", &roll[i]); printf ("Enter marks in 10 different subjects :"); total [i]=0; for(j0;j<5;j++) { scanf ("%d’, &mark[i] [i]); total [i] = total [i] + mark[i] [i]; }}printf ("\n Name \t Roll number \t Total \n");printf ("-------------------------------------------");for (i = 0; i < 10; i++)printf("% s t % d \ t% d\n", name [i], roll [i], total [i]);

getch();}

35. Write a program to display the following patters:HH HE E ELLLL

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 35/58

0000w w w w w

#include<stdio.h>#include<conio.h>void main(){ char str[]="HELLOW"; int i,j; for(i=O;i<=6;i++) { for(j=0;j<i;j++) { printf("%c" ,str[il); } printf(’\n"); }getchO;}

FunctionA function groups a number of statements into a unit and gives it a name. Then the unit can beinvoked from some other parts of the program. We can avoid rewriting of a group of codes bydefining them within a function block and use them by simply calling the function name.Advantages of function:(a) Easy to write a correct small function.(b) Easy to read, write and debug function.(c) Easier to maintains or modify such function.(d) Small function tend to be self documenting and highly readable.(e) It can be called any number of times in any place with different parameters.

Modular ProgrammingWhen a program becomes very large and complex, it becomes very difficult task for theprogrammer to design, test and debug such a program. Therefore, a long program can be dividedinto a smaller programs called modules. As the modules can be designed, tested and debuggedseparately, the task of programmer becomes easy and convenient. The division of a long programinto a smaller programs (or modules) is called modular programming.Advantages of Modular Programming(a) It is easier to design, test and debug a single modules as compared to an entire program.(b) Usually, a module of general nature is prepared so that it can be used elsewhere.Disadvantages of Modular Programming(a) Since separate modules map repeat certain functions, the modular programming often need

extra time and memory.

Why modular style ProgrammingThere are many good reasons to program in a modular style:— Don’t have to repeat the same block of code many times in• your code. Make that code block

a function and call it when needed.— Function portability: useful functions can be used in a number of programs.— Supports the top-down technique for devising a program algorithm. Make an outline and

hierarchy of the steps needed to solve your problem and create a function for each step.— Easy to debug. Get one function working well then move on to the others.— Easy to modify and expand. Just add more functions to extend program capability— For a large programming project, you will code only a small fraction of the program.— Make program self-documenting and readable.

Function declaration: It specifies function name, argument types and return value. Alerts coniputer (and programmer)that function j is coming up later.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 36/58

Examples: void display();int sum (int, int, int);etc.

Function call : It is also a component of the function and causes the function to be executed.Examples: display ();result = sum(a, b, c);etc.

Function definition : The function itself contains the lines of code that constitute the function.Examples: void display(){for(int i=O;i<9;i+-i-)printf ("+");}

int sum(int x, int y, jot z){res = x÷ y + z;return res;}

Function parameter :The parameter specified in function call are known as actual parameter and the parameter specifiedin function declaration are known as formal parameterExample: res = sum(a, b, c);Here a, b, c are actual parameter int sum (jot x, int y, jot z)Here x, y z are formal parameter.

Function return: Function can be organized into two type.(a) Function that do not have a return type i.e. void function.(b) Function that do have a return value (i.e. return (res);)

RecursionRecursion is a process of a function calling itself again and again until some condition has beensatisfied. Using recursion, two condition must be satisfied.(a) The program must be written in a recursive form.(b) The problem statement must include a stopping condition. If not, computer will hang.Example: To calculate factorial using recursion#include <stdio.h>#include <conio.h>int factorial (int);void main (){Int n;printf ("Enter a number =");scanf ("%d", &n); printf ("Factorial no = %d, factorial (n)); getch ();}int factorial (int n){if(n < = I)return 1.;elsereturn (n * factorial (n - 1));}

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 37/58

Call by value:value of actual argument parameter is copied into the formal parameter of the function.Example:{Int a= 5, b = 10;fun (a, b); printf("a = %d,b = %d",a, b);getch();void fun (int x, int y){x=x+ 100;y=y+ 100;}Call by reference: Definition address of actual argument parameter i assigned to the formal argument parameter.Example:#include <stdio.h>#include <conio.h>void fun (int *, int *); void main (){intt a = 5, b = 10; fun (&a, &b);printf ("a = %d, b = %d", a,b);getch();}void fun (int x, int *y){*x = *x +100;*y= *y + 100;}

1)Write a program to calculate the area and circumference of a circle using a function whereradius of circle is input by user and define ‘pie’ as constant.#include <stdio.h>#include <conio.h> #define pie 3.14void findarea (int);void findcircum (int); void main (){int r;printf ("Enter the value of radius ="); scanf ("%d", &r);findarea (r);findcircum (r);getch();}void findarea (int r){float a;a = pie * r * r;printf ("Area of a circle = %f", a);}

void findcircum (int r){float C;c = 2*pie * r;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 38/58

printf ("\n circumference of a circle = %f",c);}

2) Write a program to print all even numbers from 2-40 using nonreturnable function.#include<stdio.h>#include<conio.h>void print_even ();void main (){printf ("Here are even numbers from 2 to 40"); print_even ();printf ("You got the result");getch ();}void print_even (){Int a;for (a = 2;a<=40;a+2)printf ("%d\n" a);}

3) Write a program to find multiplication table of any number using function.#include<stdio.h>#include<conio.h>void numbers(int);void main(){int n; printf("Enter sny number=");scanf("%d",&n); numbers(n);getch();}

void numbers(int n){int x,m;for(x= 1 ;x<z 1 0;++x)m=n*x;printf("%d x %d=%d\n",n,x,m);}

4) Write a program to calculate the factorial number of any number entered through thekeyboard by using returnable function.#include <stdio.h> #include <conio.h>long int factorial (int); void main (){int n; long int fact;printf ("Enter a number =");scanf ("%d", &n); fact = factorial (n);printf ("Factorial number of %d = %ld", n, fact);getch ();}long int factorial (int n){long int fact= 1;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 39/58

for (inti= 1;i<n;i÷÷)fact = fact *i;return fact;}

5) Write a function power (a, b), to calculate the value of a raised to b.#include <stdio.h>#include <conio.h>int powl (int x, int y)void main (){int x, y;pow1;printf (‘Enter two numbers =");scanf ("%d %d", &x, &y); powl = power (x, y); printf("\n %d to the power %d = %d", x, y, powl);getch();}int powl (int x, int y){int i;long p= 1; for(i= 1;i<=y;i++)p = p * x;return p;}

6) A digit positive integer is entered through the keyboard, write a function to calculate sumof digis of number.(a) Without using recursion.(b) Using recursion.#include <stdio.h>#include <conio.h>int wsum (int); jut rsum (int); void main (){jut s, rs;Int n;printf ("Enter number =");scanf ("%d", &n); s = wsum (n);printf ("Sum of digits without recursion = %d\n",s); rs = rsum (n);printf ("Sum of digits using recursion = %d\n", rs); getch();}int wsum (int n){Int r, sum 0;while (n> 0) { r= n%10; }sum = sum + r; n = n/10;return sum;}int rsum (int n){

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 40/58

int r, sum = 0; if(n! = 0) { r=n%10; sum = r + rsum (n/l0); }return sum;}

Write a program to print 10 positive integers and their factorials. [HSEB-2062]#include <stdio.h>#inclucle <conio.h>long int factorial (int);void main (){jut ,num[10],i; long int fact; printf ("Enter any 10 numbers ="); for(i=0;i< 10;i++){printf ("Enter numbers\n");scanf ("%d", &num [i]); fact = factorial (num [1]);printf ("Factorial no. of %d is %ld", num [i], fact);}getch();}long int factorial (long int n){long int fact= 1;int i;for(i=O;i<n;i++)

fact = fact *i;return fact;}Write a c program to find sum of ‘n’ numbers which is divisibi by 5 using function.#include<stdio.h> #include<conio.h>int sum(int);void main (){int x, y;printf ("Enter two numbers ="); scanf ("%d", &x); y=sum(x);printf("sum=%d" ,y);getch();}Int sum(int x){int i,s=O;for (i =1; i<=x; i++){if(i%5==0)s=s+i;}return s;}7) Write a program to read 100 different number from users, store them in an array, passesthe array through function and, find maximum number among them.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 41/58

#includecstdio.h>#include<conio.h>int numbers(int no[100], int n);void main (){int n,no[100],i;printf ("Enter the value of n =\n");scanf (‘%d", &n);for (i = 1; i<n; i++){printf ("Enter numbers : \n"); scanf("%d’,&no[i]);printf("Maximum number=%d",numbers(no,n));}getch();}int numbers(int no[100],int n){int max=0;for (int i=1;i<n;i++){if(no[i]> max) max=no [i];}return max;}

Structure A structure is a collection of one or more variables grouped under a single name for easymanipulation. The variables in a structure, unlike those in an array, can be of different variabletypes. A structure can contain any of C’s data types, including arrays and other structures. Each3variable within a structure is called a member of the structure.Declaration of a structuree.g. struct student{char name [20]; int class; int age;};struct date char month[2]; char day[2]; char year[4];} current_date;struct student a; In the above example,struct => keywordstudent => structure data type name name[20] ,class and age =>Member name a=>declaring structure variableThe data members are accessed by structure variables with followed by a. (period sign), called dotoperator.

Differentiate between array and structure with examples. [HSEB-2O66]Array Structure

1 Array is the collection of data itemswhich will have the same name.

It is a kind of user define data type which canstore the data of various type such ascharacter, integer etc.

2 The individual array elements aredistinguished from one another byvalue that is assigned to a subscriptor index

Structure is not represented by index orsubscript.

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 42/58

3 Array has its type and theseare:(i) one dimensional array(ii) multi dimensionalArray

Structure has no type

4 The syntax of array:(i) One dimensional array:datatype array_name [size of array];It consists only rows or columnsi.e. char name [201;(ii) Multi-dimensional array:data_type array_name [exp 1] [exp2];e.g. char name [5] [25]; It containsrows and columns.

Syntax of structure:struct user_defined_name data_type member1; data_type member2;daa_type membern;struct user_defined_name van, var2 e.g. struct studentchar name [20]; int age;struct studentone;

Example : Display name & age:#include <stdio.h> #include <conio.h>void main ()char name [20]; int age;printf ("Enter name:");gets (name); printf ("Enter age \n");scanf ("%d", &age); printf("\n Name :%s", name);printf ("Age:%d", age);getch();}

Example : Display nameage:#include <stdio.h> #include <conio.h>void main (){struct student{char name [20]; int age; one;printf ("Enter name"); scanf ("%s", one.name); printf ("\n Enter age:");scanf ("%d", &one.age);printf ("\n Name : %s", one. name);printf ("Age :%d", one.age); getch();}

Differences between structure and union .[HSEB-2065]Structure Union

1 It is a kind of user defined data typewhich can store the data of varioustype such as character, integer etc.

Union is a collection of hetrogeneous datatypes

2 Each element has specific memoryspace and takes more memoryspace than union.

Each element has no specificmemory space but spaceallocated for largest elements isutilized by other sized element.

3 Keyword,i.e.struct isrequired to declare structure,

Keyword ,i.e.union is required to declare union

Programming1) Write a program to read roll number,name and age of a studentand display it in proper format.#include<stdio.h>#include<conio .h>struct student{

int rollno;char name[20];int age;

}a;void main(){

printf("Enter roll number:"):scanf("%d",&a.rollno);printf("Enter nape:"):scanf("%s",a.name);printf("Ent’er age:"):

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 43/58

scanf("%d", &a.age);print f("%d\t %s\t %d",a. rollno,a.name,a.age);getch();

}2) Write a program to enter name,address and age of 5 different persons,print it in tabular

format.#include<stdio.h> #include<conio.h>struct student{char name[20];char add[20]; int age;}a[5];void main(){int i; for(i=0;i<5;++i){printf("Enter name:"); scanf("%s",a[i] .narne); fflush(stdin); printf(’ Enter address:");scanf("%s" ,a[ij .add); printf("Enter age:");scanf("%d",&a[i] .age);printf("\n\n");printf("Name\tAddress\tAge\n");printf("for(i=0;i<5;++i)printf(" %s\t %s\t %d\n",a[iJ .name,a[i] .add,a[ij .age); getch();}3) Write a program to enter name, price and pages of 10 different books and display them in

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

struct book{char name [15]; float price;int pages; } list [10];

int i;for(i=O;i< 10;i++) {

printf ("Enter name, price & pages of %d bq9k:",(i + 1)); scanf ("%s %f %d", list [ij.name, &list [ii. price,&list [i].pages);

}printf ("Name \t price \t pages \n"); for (i=0;i< 10;i++) {

printf("%s \ t % f\t % d\n", list Ji].name, list [i].price, list[i]. pages);getch ();}

4) Write a C program to read name,marks in 5 different subjects of a student, find total,percentage. Print name, marks, total and percentage in tabular format.

#include<stdio.h>#include<conio.h>struct student{char name[20]; int mark[5];}list;void main() { int tot=0,per,i; printf("Enter name:");

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 44/58

scanf("%s" ,list.name); for(i=0;i<5;i++) { printf("Enter mark:");

scanf(’%d",&list.mark[i]);tot=tot÷list.mark[i];

} per=tot/5;

printf("NAME\tsub 1 \tsub2\tsub3\tsub4\tsub5\tTOTAL\t per\ n")printf("%s" ,list. name);for(i=0;i<5 ;i++){ printf("%d\t" ,list.mark[i]);printf("%d\t%d\n’,per,tot);}getch();}5) Write a program that reads different names and addresse intothe computer; and sorts the name into alphabetical order usingstructure variables. [HSEB-2064]#include<stdio.h>#include<conio.h>#include<string.h>struct stud{char name [80] ,add[80] ,temp[80] ,temp 1 [801;Ia[5];void main(){int i,j;printf("enter name and age:"); for(i=0;i<5 ;i++) { scanf(’%s%s’ ,a[i] .name,a[i] .add);for(i=0;i<5;i÷+){for(j=i+1;j<5;j-t-÷)if(strcmp (a[i] .name,ã[j] .name) >0){strcpy(a[il .temp,a[i] .name);strcpy(a[i] .name,a[j] .name);strcpy(a[j] .name,a [i] .temp);

strcpy(a[i] .temp 1 ,a[i] .add); strcpy(a[i] .add,a[j] .add);strcpy(a[jj .add,a[i] .temp 1);}

}printf("The result\n"); for(i=0;i<5;i+÷) { printf("%s\t%s\n" ,a[i] .name,a[i] .add); }getch();}6) Write a program to read a set of names, roll number, sex, heightand weight of the students from the keyboard and to sort them in ascending order using astructure within an array data type.#include<stdio.h> #include<conio.h>#include.cstring.h>

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 45/58

#define MAX 250int i, n;struct school{char name [25]; int rolino;char sex [7];float height;float weight;}student [MAX];void main (){void output (school student [MAX], int n);void sort (school student [MAX], int n);printf ("How many data ?"); scanf ("%d", &n);for (i = 0; i < n; i++) {

printf ("Record = %d \n", i + 1);printf ("Enter name : \n");scanf("%s", student [i].name);fflush(stdin);printf ("enter roll number \n"); scanf("%d", &student[il. roilno);fflush(stdin);printf ("Enter sex ");scanf("%s", student [i].sex);printf ("Enter height:\n");scanf ("%f’, &student[i]. height);printf ("Enter weight : \n");scanf (‘%f’,&student[i]. weight);printf ("\n n");

}printf ("Unsorted data \n");output (student, n);printf ("Sorted data \n\n");output (student, n);getch();}void output (school student [MAX],int n){printf ("Name \t Roll no \t Sex \t Height \t Weight \n");printf(" \n");for (i = 0; i < n; i++) {

printf("%s \t % d \t % s \t %f\t %f\t \n", student [i]. name, student [ii. rolino, student [I].sex, student [i]. height, student [i]. weight);

}}

void sort (school student [MAX), int n)struct school temp; int i, j;for (i = 0; i < n; i++){ for (j = i+1; j <n;j++) { if (strcmp(student[i] .name, student[j] .name)<=O) { temp = student[i];

student [i] = student [j];student [j] = temp;

}

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 46/58

}}

7) Write a C program to pass structure as parameter to function.#include<stdio.h>#include<conjo.h>struct data{ float amount; char fname[30}; char lname [30];} rec;void print_rec(struct data x);void main(){printf("Enter the donor’s first and last names,\n"); printf("separated by a space: ‘); scanf("%s %s", rec.fname, rec.lname);printf(’\nEnter the donation amount:scanf("%f’, &rec.amount); print_rec( rec);getch();}void print_rec(struct data x){printf("\nDonor %s %s gave Rs%.2f.\n", x.fname, x.lname, x.amount);}

PointerA pointer is a variable which stores the address number of reference number of a cell, instead ofstoring the actual value of the cell. It is really a very powerful variable which is used tø directly dealwith memory of computer. A pointer is denoted by(indirection operator) and has to be declared in the similar way as we declare other ‘ariables.e.g. int a; //A normal variableint *p; //A pointer that will point to an integer datap = &a; //Assign address of ‘a’ to ‘p’, pointer ‘p’ will II Point I/to the value of variable ‘a’.Advantages of pointers are:(a) It allows us to pass variables, arrays, functions, string and structures as function arguments.(b) Pointers are more in handling the data table.(c) They increase the execution speed.(d) Pointer reduce the length and complexity of a program.(e) It supports dynamic memory allocation and de allocation of memory arguments.(f) The use of a pointer array to character strings results in saving of data storage space inmemory.

Uses of Pointer- Pointers are more efficient in handling the data array. They are used to manipulate arrays moreeasily by moving pointers to them instead of moving the arrays themselves.- Pointers reduce the length and complexity of a program.- Pointers are used to return more than one values from a function.- Pointers are used to create complex data structures such as linked lists, trees etc.- Pointer increases the execution speed.- Pointers are used to communicate information about memory, which returns the location of freememory.Eg. Using function like malloc();

Declaration of pointer variablesA pointer should be declared before its use like any other variable. Data type of the pointer is thedata type of the variable to which it is pointing.Pointer variable is defined by using an indirection symbol ". Using this operator, it becomespossible to point to the address of other variable. A pointer variable is declared as follows;

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 47/58

Syntax: Data_type ‘ variable_name;Eg; int *ptr;

Explain the meaning of each of the following declarations:(i) int *p;(ii) int * [10];(iii) int (*p) [10];(iv) int *p [void];(v) int [char *a]; [HSEB-2061]Meaning of declared pointer statements are:(a) int *p; A point that will point to an integer data.(b) int [10]; p is 10-element array of pointer to integer data.(c) int (*p) [10]; P is a pointer to a 10-element integer data.(d) int *p [void]: P is a function that returns a pointer to an integer data.(e) int "p (char*a); P is a function that accepts an argument which is a pointer to a character andreturns a pointer to an integer data.Relation between array and pointerIn fact, the compiler translate array notation into pointer notation when compiling. Since the internalarchitecture of the microprocessor understands pointers but doesn’t understand arrays.

1) Write a program to swap the values of two members using functions.#include <stdio.h>#include <conio.h>void swap (int *, int*);void main (){int a, b;printf ("Eiter two integers :"); scanf ("%d%d", &a, &b);fun (&a, &b);printf (Now, a %d \t b = %d", a, b); getch();}Void swap (int *x, int *y){Int temp;Temp = *x;*x = *y;*y = temp;}2) Write a program that reads N integers and prints them ascending order using pointer and

user defined function.#include<stdio.h> #include.cconio.h> void arr(int 4’);int i,j,n;void main(){Int *p,*q,a[10];q=p;printf("enter the value of N:"); scanf("%d",&n);printf("enter the %d numbers:\n",n);for(i=0;i<n;j++){ scanf("%d",p);

p++;}arr(q);printf( "the array elements after sorting:\n");for(i=O;i<n;i++){printf(’%d\t",*q);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 48/58

q++;}getch();}void arr(int *b){for(i=0;i<n;i++) { for(j=i÷1 ;j<n;j++) { if(*(b+i)>*(b+j)) {

int temp=4’(b+i);*(b+i)=*(b+j);

*(b+j)=temp; } } } return;}

3) Write a program that reads computer marks of N different student and prints them. [Usemalloc 0 function]

#include <stdio.h>#include <conio.h>#include <malloch>void main (){int p, *q, i, N; printf ("Enter N:");scanf("%d", & N); p = (int *) malloc (size of (int)*N);q = p;printf ("Enter computer marks of %d student", N);for (i= 0; i< N; i++){

scanf ("%d", &p); p=p+1;}printf ("The elements are:\n");for (i= 0; i< N; i++){ printf ("The elements are :\n"); for (i=0;i<n;i++) { printf ("%d *q); q = q + 1; }}getch();}

4) Write a program that reads roll, name and marks in 5 different subjects of N differentstudents and prints them in appropriate ormat [Use structurepointer & malloc () function]

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

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 49/58

struct student{int roll;char name[25];float mark[5];};void main(){int n, i, j;float total[5];printf("enter the no of student:");canf("%d" ,&n);J p=(struct student *) malloc(sizeof(struct student)*n); q=p;for(i=0; I<n;i++){total[i]=0;printf(’enter the record ofstd[%d]:\n",i+l); printf("enter the roll:");scanf("%d" ,&p->roll);fflush(stdin); printf("enter the name:");gets (p->name);printf("enter the marks in 5 subjects:\n"); for(j=0;j<5;j++) {

scanf(’%f" ,&p->mark[j]); total [ii =total[i] +p.->mark[j];

}P++;}Clrscr(); printf("\nRoll\tName\tSUB 1\tSUB2\tSUB3\tSUB4\tSU l\tDivi\tRemarks\n"); printf("for(i=0;i<n;i++){printf("%d\t%s\t" ,q->roll,q->name);for(j=0;j<5;j÷+){if(q->mark[j] <40) printf("%O. 1 f"\t",q—>mark[j]); else printf("%. lf\t",q->mark[j]);} printf("%O. 1 f\n",total[i]); q++;} getch();}

Write a program which concates a string to other [use pointer].#include <stdio.h>#include <conio.h> •void main (){char stri [20], str2[20];int i;printf ("Enter two strings :"); scanf ("%s %s’, strl, str2);preconcatenate (str2, str I);printf (" \n \n After adding str2 to other"); printf (" \n The new string : %s", str2);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 50/58

getch ();}preconcatenate (char *i, char *s){ while (*i) i ++; while (*s) *i++ = *s++; *I = ‘\0’;}

Data FileIt is a data structure which help us to store our data on the secondary storage media (i.e. hard disk,floppy disks etc.)and to access and alter information whenever necessary. C programming hasdifferent types of library functions for creating and managing data files. Types of data files are:A. High LevelTypes of high level files are:a. Text filesA text file is a human-readable sequence of characters and words they form that can be encodedinto computer-readable formats such as ASCII. A text file is also known as ASCII file and can beread by any word processing package. There is no sound or video files or graphical files.b. Binary filesIt organizes data into blocks containing contiguous bytes of i information. It consists sound,images, graphical files etc. A binary file is made up of machine-readable symbols that represent l’sand, 0’s.B. Low LevelOperation ‘modes’ of files are:(i) r: open file for reading or display(ii) w: open file for writing(iii) a: open file for appending

syntax of character input/output, string input/output, word input/output and formattedinput/output. Also write the syntax of block read and write.a) Character input/outputa.getc()It is used to read a single character from a file and returns the value of EOF.The statement is ch=getc(fr); b.putc()It is used to write a single character into a file. The function normally returns the character writtenbut will return value of EOF if error is encountered.The statement is putc(ch,fp);b) String input/outputa.fgets()It is used to read a set of characters as a string from a given file and copies the string to a givenmemory location normally in array. The general format of fgets() isfgets(sptr, n,ptr);Where sptr=pointer to the location to receive stringn=count maximum number of character to be in the stringptr=pointer to the file to be readb) fputsIt is used to write a string to a given file. The general format offputs() isfputs(sptr,ptr);where sptr=pointer to the string to be written ptr=file pointer to filec) Word input/outputa.getw()It is used to read an integer value from a given file. The format of getw() isgetw();

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 51/58

b.putw();It is used to write an integer quantity on the specified file. The syntax of putw() isputw(w,fp);where w is an integer value and fp is file pointer.d) Formatted input/outputa.fscanf()It is used to read a formatted data from a specified file.The general format of fscanf 0 isfscanf(ptr, "control string’ clist);where ptr is file pointer,control is different format like %d,%f etc and list is variable parameter list tobe read from specified file.b.fprinf()It is used to write a formatted data into a given file.The genera’ format of fprintf() isfprintf(ptr, "control siring",list);where ptr is file pointer,control string is a formatted comman and list is variable list to be written onthe file.Block read and write(Binarv files) a.fwrite()It is used to write a binary data to a given file.The general form Isfpritef(ptr,size, nitems,fptr);where ptr=pointer that is first structure to be written. size=size in bytes of each structurenitemsnumber of structure to be written fptr=file pointer to the fileb.fread()It is used to read a block of binary data from a given file. fread(ptr,size, nitems,fptr);

1) Steps for writing a file(a) Create a FILE pointer(b) Open fIle in write (w or a) mode(c) Perform general I/O operations(d) Save I/O results using following syntax:fprintf (file_pointer, "format specifier lists", variable lists);(e) close the file using fclose (file_pointer)Example:{ Int age;char name [20];FILE *fp;fp = fopen ("info.dat", "w");printf ("Enter name:");gets (name);printf ("Enter age:");scanf ("%d", &age);fprintf (fp,"%s %d", name, age);fclose (fp); return ();}

2) Steps for reading a file(a) create FILE pointer(b) open file in read mode (r mode)(c) Read the data from file using following syntax:fscanf (file_pointer, "format specifier list", variable lists);(d) Display data as requirede.g.int age;char name[20]; FILE *fp;fp = fopen ("iñlo.dat", "r"); fscanf (fp, "%s %d", name, &age); printf ("Your name: %s", name);printf ("Your age: %d", age);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 52/58

fclose (pp);return ();

Write a program to read data from the keyboard, write it to a file called INFO, again read tlesame data from INFO file, and display it on the screen. N

#include <stdio.h> #include <conio.h>void main (){FILE *fp;int st_no[MAXJ ,marks[MAXJ;char name[MAXI[20];int i,n;printf( How many data? );scanf( /od ,&n);fp = fopen( record.dat , w+ );for(i=0;i<n;++i){printf("Enter roll number:");scanf(’%d",&std_no[iJ);fflush(stdin);prmntf("Enter name");scanf( %s" ,name[i]);printf("Enter marks:");scanf(’%d",&marks[i]);fprintf(fp,"%d%s%d",std_no[i] ,name[i] ,marks[i]);}•rewind(fp);printf("Roll number\tName\tMarks\n");printf(" \n");for(i=0;i<n;÷+i){fscanf(fp,"%d%s%d",&std_no [i] ,name[i] ,&marks[i]);printf("%d\t%s\t%d\n’ ,std_no [i] ,name[i],marks [i]);}fclose(fp);getch();}

3) Write a program for reading a data file. [HSEB-2064]#include<stdio.h>#include<coriio.h>void main(){*FILE fp;int roll number[10],marks[10];char name[10][20];int i,n;fp=fopen("c:\play.dat","r");printf("Rojl numbertName\tMarks\n");printf("-------\n");for(i=0;i<10;++i) { fscanf(fp, "%d%s%dfl,&rofl number[i] ,name [i] ,&marks [i]); printf("%d\t%s\t%d\n",roll_number[i] ,namc[i] ,marks [i]);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 53/58

} fclose(fp);getch();}

4) Write a program to enter name,roll_number and marks of 10 students and store them inthe fi1e- [HSEB-2065]

#inckide<stdio.h>#include<conio.h>void main(){FILE *fp;char name[JO][20Jint roll_number[IOJ,marks{IOJ;int i,n;fp = fopen("c:\play.dat’, "w"); for(i=0;i<10;++i) { printf("Enter roll number:"); scanf("%d", &roll_number[j]); fflush(stdjn); printf("Enter name"); scanf(’%s",name[j]); printf("Enter marks:"); scanf("%d’&marb[j]); fprintf(fp, "%d%s%d,roII number[i] ,flame [i] marks [i]); } fclose(fp);getch();}

6) Write a program that reads name, rank and country of N different players for a data file andprints all the information in descending order on the basis of rank.

#include<stdio.h>#include<conio.h>#include<string.h>#define MAX 500 struct player{int rank, char name[15],country[15]}list[MAX];

void main(){FILE *fp;int i,j,rtemp;char ntemp[15],ctemp[l 5];int n;printf("How many records?:):scanf("%d",&n);printf("ADD RECORDS\n\n");fp=fopen("data.txt","w");for(i=0;i<n;i++) { printf("enter the record of player[%d]n ",i+ 1);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 54/58

fflush(stdin);printf("Enter the Name:");gets (list[i] .name);printf("Enter the rank");scanf("%d",&{jst[j] .rank);fflush(stdjn);printf("Enter the country:");gets (list[i] .country);

}for(i=0;i<n;ji-+){ for(j=i+ 1 ;j<n;j++) { if(list[i] .rank>list[j] .rank) { rtemp=list[i] .rank;

strcpy(ntemp,list[il .name); strcpy(ctemp,Iist[i}.country);list[i] .rank=list[j] .rank; strcpy(1ist[i] .name,Iist[j].name);strcpy(list[i] .country,list[j].country);list[j] .rank=temp;strcpy(list[j] .name,ntemp);strcpy(list[j] .country,ctemp);

} }}

fwrite(&list,sizeof(ljst), 1 ,fp);fclosc(fp);clrscr();fp=fopen("data.txt", "r");prinrf("Rank\tName\tcountryressn ");while(fread(&list,sjzeof(jjst)J ,fp) == 1) { for(i=0;i<n;i++)

printf("%d\t%s\t%s\n",list[i] .rank,list[i] .name,list[i] .country); }fclose(fp);getch();}

7) Write a program that ask the user to input Name, Age of N different film actors for a fileand prints them in appropriate format. [Use fwrite() and fread() functions]

#include <stdio.h.> #include <conio.h>struct actor{int age; char name [25];}rec;void main (){FILE *fp; int i, N;fp =fopen ("dec.dat’, "w+"); printf (‘Enter how many :"); scanf(’% d", &N);for (i = 0; i <N; i++){

printf ("Enter name : \n");

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 55/58

gets (rec.name);printf ("Enter age : \n");scanf ("%d", &rec.age);fwrite (&rec, size of(rec), 1, fp);

}rewind (fp);printf ("Name \t Age \n");printf ("---------\n");while (fread (&rec, sizeof (rec), 1, fp) = = 1){printf ("%s \t %d \n", rec.name, rec.age);}fclose (fp);getch();}

List of graphics functions in C programmingSome of graphics functions are:(a) getmaxx()— gets maximum number of column(b) getmaxy () — gets maximum number of rows(c) line (xi, y, X2, y2) — draws a line starting from the coordinate (xi, yi) to (X2, y2)(d) circle (c, y,’I) — draws a circle with coordinate of center as x & y and radius(e) arc (x, y, stan, endan, hr, vr) : draws an arc with the center at x & y coordinate, starting angle(stan), ending angle (endan), horizontal radius (hr) & vertical radius (vr).(f) ellipse (x, y, stan, endan, hr, vr) where, x & y = screen coordinate stan = starting angle endan = ending anglehr = horizontal radiusyr = vertical radius(g) rectangle (left_x, top_y, right_x, bottom...y)(h) setcolor (color name) — color name means name of color i.e. RED, GREEN etc. —(i) Cleardevice 0 — clear graphics screen(j) Closegraph ( ) — use to close all graphics driver using this function.

1. Write a program to display circle using function of graphics.#include<stdio.h> #include<conio.h>#includeczgraphics.h>void main (){Int gd = DETECT, gm; initgraph (&gd, &gm," \\ tc \\ bgi");setcolor(GREEN);circle (300, 250, 40); getch();closegraph ();}2. Write a program to display rectangle using function of graphics. #include<stdio.h>#include<conio.h>#include<graphics.h>void main(){Int gd = DETEcT, gm;initgraph (&gd, &gm, " \\ tc \\ bgi’);setcolor(GREEN);reectangle(5O, 10,260,180);

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 56/58

getch (); closegraph ();}

3. Write a program to display ellipse using function of graphics.#include<stdio.h>#include<conio.h>#include<graphics.h>void main (){int gd = DETECT, gm; initgraph (&gd, &gm, "\ tc \\ bgi"); setcolor(GREEN);ellipse (100, 100, 0, 360, 30, 20);getch();closegraph ();}

What do you mean by OOPs? Write a the advantages of and disadvantages of OOPs?OOP is a method of implementation in which programs are organized as co-operative collections ofobjects, each of which represents an instance of some class and whose classes are all membersof a hierarchy of classes united through the property. Advantages of OOPs:(a) Code reusability is much easier than conventional programming language.(b) Making the use of in heritance, redundant code is eliminated and the existing class is extended.(c) It is possible to have multiple instances of an object to coexist without any interference.(d) System can be easily upgraded from small to large systems.(e) Software complexity can be easily managed.(f) Aids trapping in an existing patterns of human thought into programming.Disadvantages of OOPs:—(a) Benefits only in long run while managing large software projects.(b) Compiler and runtime overhead object oriented program required greater processing overhead

demands over resources.(c) Re-orientation of software developer to object-oriented thinking.

How object oriented programming is differ from procedure oriented programming?Object oriented programming is differ from procedure oriented:—(a) In oop, emphasis is given on data but in pop, emphasis is given on procedure.(b) In oop, programs are divided into objects but not in pop.(c) Data hiding principle is used in oop but not in pop.(d) Oop follows bottom up approach but pop follows top down approach.(e) Oop provide the code reuse facility but pop does not.(f) In oop, object can communicate with each other through, function but not in pop.(g) In oop, new data and functions can be easily added.

Class in OOP:A class is a collection of objects of similar type which have same property and common behaviour.For example, roll, name, age are member of class student and Pigeon, Sparrow, Crow etc. areobject of class bird. A class is a user defined data type which holds both data and functions. Theinternal data of class is called data member and functions are called member functions. Themember functions mostly manipulate the internaldata of a class. syntax> class class_name{private:

variable declaration;function declaration;

public: variable declaration;

function declaration;}

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 57/58

Posted by Bhuwan Bhandari at 11:49 PM

Object in OOP: Object is the combination of data and functions in a single unit. Object can interactwithout having to know details of each other’s data or code. It is sufficient to know the type ofmessage accepted and the type of response returned by the objects.

Explain the term polymorphism and inheritance. [HSEB-20631Polymorphism:The word polymorphism is derived from the Latin words poly means many and ‘morphos’ meansform thus ‘polymorphism’ means many forms.Polymorphism is the process of defining a number of objects of different classes into a group andcall the methods to carry out the operation of objects using different function calls.Inheritance: [HSEB-2066]Inheritance is the process of creating new class (i.e. derived class) from base class. Each suchclass or derived class share common characteristics of base class. The main advantages ofinheritance are:—(i) Code reusability(ii) to increase the reliability of code, and(iii) to add some enhancements to base class the following figure illustrate inheritanceTypes of Inheritance(a) Single inheritance: There is a derived class with only one base class.(b) (ii) Multiple inheritance: The derived class has several base classes.(c) (iii) Multi level inheritance: Mechanism of designing a class from another derived class.(d) (iv) Hierarchical inheritance: One class may be derived by more than one class.

What do you know about data abstraction and encapsulation? Explain.Data abstraction:Data abstraction can be defined as a list of abstract attributes such as size, weight and cost, andMethod that operate on these attributes. They encapsulate all the essential properties of the objectsthat are to be created.Encapsulation:The wrapping up of data and methods into a single unit (called class) is known as encapsulation.The data is not accessible to the outside world and only those methods which are wrapped in theclass, can access it. These methods provide the interface between object’s data and the program.This insulation of the data from direct access by program is called data hiding.

Recommend this on Google

Enter your comment...

Comment as: Google Account

Publish

Preview

No comments:

Post a Comment

10/26/2014 The Computer Book |where you can learn more|: C - programming

http://finesbook.blogspot.in/2012/06/c-programming.html 58/58

Newer Post Older PostHome

Subscribe to: Post Comments (Atom)

Picture Window template. Powered by Blogger.