Vous êtes sur la page 1sur 42

1

Lakhanis T.Y.B.COM COMPUTERS Class : Shruti miss : Sir : 9930203872 9820789390 9820360320

C-Language
Introduction
C Language was 1st developed by Dennis Ritchie of Bell laboratories in 1970s. C is middle level Computer language because it combines features of higher-level language & lower level language.

C-Keywords / C-Reserved words


At the time of designing a language, some words are reserved to do specific task. Such words are called Keywords or Reserved words. All these should be written in lower case. int struc goto const union return do signed auto sizeof while long short unsigned extern break switch volatile char register continue enum float if default double static else entry

Constants and Identifiers


Constants: Constants represent values and whose values cannot be changed during the program execution. They are contents of memory location. Constants are of three types. 1. Numeric Constant 2. Character Constant 3. String Constant

1)

Numeric Constant: -

A Numeric constant is made up of sequence of numeric digits with optional presence of a decimal point. Numeric constant is of 2 types. i) Integer Constant ii) Real Constant (Floating point constant) i) Integer Constant Integer constants are numeric constants, which do not have a decimal point. Rules of forming Integer Constant 1. An integer constant must have at least one digit 2. No Alphabets and decimal point are allowed 3. No special Characters except +, - If + or is used it should be first character. 4. No commas or blanks are allowed 5. The range allowed is 32768 to +32767 Examples: - Valid: - 426, +782, -800 Invalid: - 12, 000, A123, 12 45, 67+ ii) Real Constant (Floating point constant) Real Constants are often called constants, which have decimal point.

Floating

Point.

They

are

Rules of Forming Real Constant


1. It is made up of numeric numbers from (0 9). No alphabets are allowed 2. It must have a decimal point. 3. It can have positive and negative sign in the starting. 4. No commas or blanks or allowed. 5. The range allowed is 3.4*10-38 to 3.4*10+38 Examples: - Valid: - a) 345.0 b) -34.78 c) -48.5799 Invalid: - a) 45,125.67

2)

Character Constants

A Character constant is a single alphabet, a single digit or a single special character enclosed within a pair of single quote marks. The maximum length of a character is one character. Each and every character has a numeric value associated with it. This numeric value is known as ASCII code. Example: - A, 5, =, (blank space).

3)

String Constants

It is a sequence of characters enclosed in double quotes. The characters may be alphabets, numbers, and special characters. This can also be defined as an array of character constants whose last character is \0, which is automatically placed at the end of the string by c compilers. Examples: - Hello, 12334, a=4? 5 +4, Well done, X , (Null string)

Identifiers (variables)
Every C word is classified as either a keyword or an identifier. These are defined by the users and are names given to various program elements, such as Variables, Arrays, and function.

Rules of forming Identifiers


1. (_). 2. 3. 4. 5. 6. It can be made up of Alphabets (A- Z), Numbers (0 9) and Underscores No other Special characters allowed except underscore. First Character should be Alphabet or an underscore. It can be maximum made up of 32 characters. It must not be a Keyword. Upper & Lower case are significant. Both the cases are allowed; usually C variables are in lower case. E.g.:- NUM, Num, & num are considered to be 3 different identifiers.

Example of Identifiers
A, A1, COMM, SALARY, SAL, SAL_INT, IND_COMM, TOT_COMM_SAL.

Imp points to remember:1. Each & every character should written in lower case . Only Identifiers can be in uppercase. 2. Each and every statement should end with a semicolon (;) 3. Each & every variable used in the program should be defined in the beginning of the program.

Data Types
Data types are used to define the type of the variables used in a program in the beginning of a program. In C, there are basic five data types. 1. int (to declare integer data types ) 2. char (to declare Character data types ) 3. float (to declare floating point data types ) 4. double (to declare double floating point types) 5. void (Valueless) (to declare Void data types)

Type Modifiers/Data Type Qualifiers


Each data type may have various type modifiers preceding them. A type modifier is used to change the meaning of basic data types to fit the needs of the various situations. The type modifiers are long, short, signed and unsigned.

Operators
1. Arithmetic Operators

There are 5 Arithmetic operators in C . + , - , * , / , % ( Modulus Division (gives remainder)) Note: - There is no exponentiation operator in C. However, there is a Library function (pow) to carry out exponentiation. Arithmetic operation between integers yields an integer. Arithmetic operation between floating (real) always yields a real result. Operation between an integer and real yields a real result.

Hierarchy of Operations
Priority 1st 2nd 3rd Operators * / % + = Description Multiplication, Division, Modulus Division Addition, subtraction Assignment

2.

Relational Operators
!=(not equal) , < , >

Relational operators are = =(equal to) , , <= , >=

3.

Logical operators
are ! ( not ) && (and) || (or)

Logical Operators

4.

Assignment Operators
+= s=s*a (s*=a) -= *= /= %= s=s/a (s/=a) s=s%a (s%=a)

The Assignment operators are Examples: s=s+a (s+=a) s=s-a (s-=a)

5. Increment and Decrement Operators(++ and --)


To increase or decrease the variable by 1, increment and decrement operators ++ and -- are used. The incrementing and decrementing by 1 can be of 2 types. 1. First increase or decrease then takes the value for processing (Prefix) 2. Take the value for processing & then increment or decrement the variable.(Postfix)

6. Unary Operators
The operators that act upon a single operand to produce the result are known as Unary Operators. Example: - ++x, x++, --x, x--, +a, -b and !. It is solved from right to left.

Cast Operator
At times we need to force an expression to be of specific type. This is called casting. Suppose we have the initialization float x=5/7. We are going to have the value of x=0, as 5 and 7 are of integer type. If we want the correct result we must use the cast operator and say x= (float) 5/7. This will ensure that the expression is evaluated as a float & not integer as the numerator will be treated as float only for this calculation.

C Statements
Comments Statement
Purpose User comments in the program explain certain aspect of the program. It is meant to identify the program. The comment should be enclosed by /* and */. It is an optional statement and can be included anywhere within the program /* any message */ Nil, as it is a non-executable statement. /* income tax calculation */

. Syntax Action Example

Assignment Statement
Purpose It is meant to store values in Computer Memory by assigning a name to the value. Variable = Constant / Variable / Expression; The right hand side expression is evaluated and result obtained is stored in the variable given on the left hand side. a=0, a=5, a=b , s=a+b , comm=sales*0.12, avg =(a +b + c)/3

Syntax Action

Examples

Input output statements


Input Output statements are used to provide communication between the user and the program. The program, which contains input/output function, must contain the statement #include<stdio.h> at the beginning. The file name stdio.h is an abbreviation for standard input-output header file.

Input function

1.

Formatted input function scanf():

Purpose With this function call all types of values can be read i.e., int, float, character & string. Syntax Action scanf(control string , List of Variables separated by comma); The execution stops temporary and waits for the user to supply the data.

Control string or Conversion Specification/character


User has to provide the type and size of the data. Percent (%) symbol should precede the conversion character. The following are some of the conversion character. Conversion Specification /Character %d %ld %f %lf %c Meaning indicates the type to integer indicates the type to long integer indicates the type to float indicates the type to long float indicates the type to character

%s

indicates a string of characters

Control string: - This contains the conversion characters & determines the number of arguments that follows it. It should be given in double quotes. Examples:- 1 scanf(%d, &a); 2 scanf(%d %f, &a, &b); 3 printf(Enter any 2 numbers); 4 scanf(%s, n); scanf(%d %f, &a, &b); good (good will be assigned to n.) Here (&) ampersand is a pointer. It selects address to the variable in the memory.

2.

Unformatted input function getch(), getche(), getchar() & gets():

getch() : It reads a single character immediately as it is typed without waiting for the enter key to be pressed. getche() : It reads a single character without waiting for the enter key to be pressed. The e in getche() means it echoes(displays) the character you have typed on the screen. getchar () : It reads a single character but requires the Enter key to be pressed. It displays the character typed. gets() : It allows to receive the string in a response from keyboard. After typing the desired response an enter key is to be pressed

Escape Sequence
The characters on keyboard can be printed or displayed by a press on the key. But some characters such as line feed, form feed, tab etc cannot be printed or displayed directly. C provides the mechanism to get such characters that are invisible by using Escape sequence. These escape sequences are represented by a back slash (\) followed by a character. Though there are two characters in a escape sequence, they are considered as a single character. Some of them are as follows: Escape Meaning \0 End of string \n End of a line next line. \t Horizontal tab position \b Back space line Result Null Moves the active position to the initial position of the Moves the active position to the next horizontal Moves the active position to previous position on current

Output Function
Through output functions, the result or information can be display.

1.
Purpose give line Syntax Example

Formatted output function printf():

With this function all types of values can be written. This does not feed. printf(control string, list of variables, expression, & constants separated by comma); 1. printf(Value of a=%d,a); printf(Value of b=%d,b);
2.

printf(Value of a=%d\n, a); printf(Value of b=%d, b); printf(Value of a=%d\n and value of b=%d, a, b);

3.

2.

Unformatted output function putch(), putchar()and puts():


It is meant to display a single character on the screen. It does not give line feed like printf statement.

putch()or putchar():

puts():

It allows to print only string generates line feed automatically.

data on a new line. It

C preprocessor
The C preprocessor is a program that processes our source program before it is passed on to the compiler. The processor commands are known as directives. Each of these directives begin with # symbol and can be placed anywhere in the program, but are generally placed at the beginning of the program before the main () function. They include macro definition (# define) and file inclusion (# include).

File inclusion(Header files)


In C- there are variety of functions. These functions are stored as files under different names (headings) and these are known as header files. The header files stdio.h includes some of the input and output procedures. The header files math.h includes mathematical functions. The header file conio.h includes the single character input and output procedure like getchar(), getch(), putchar() and clrscr() function. To use the C functions, one has to include the required header files by using #include<headerfile.h>

Prototypes:
Each and every C function like printf(), scanf(), clrscr(), pow() requires the prototype which understands the above functions. The declarations of these functions are in the header file like <stdio.h> ,<conio.h> and <math.h>. A prototype of user defined function is also required in the main program. If it is omitted in a program then an error message appears function should have a prototype while compilation.

main()
Every C program is made up of one or more than one functions. The only compulsory function that should be present in each and every program is the function main(). The function main() indicates that the program starts from here.

return 0
This statement returns a value zero to the function main(). This is required in some compilers where the function should always return some value. In these compilers if this statement is not included a warning message appears function should return a value while compilation. This statement can be avoided if the function main() is defined as void main().

10

SIMPLE PROBLEMS:
1. To find sum of 2 numbers. Print both the numbers and the sum. 2. To find average of 3 numbers. And print average of three numbers. 3. To input radius. Calculate &print area and circumference. (area r2 circumference 2r) 4. To input length and breadth. Calculate & print area and perimeter. 5. To input amount in dollars and rate of exchange. Calculate and print amount in rupees. 6. To input time in hours, minutes and seconds. Calculate and print total time in seconds. 7. To input name and amount of sales. Calculate commission @7% of sales. Print name, sales and commission. 8. To input salespersons number, name & amount of sales. Calculate discount @ 12% of sales & net price which is sales discount. Print number, name, sales, discount, & net price. 9. To input principal amount, no. of years and rate of interest. Calculate and print compound interest where, compound interest = p (1+r/100) ^ n p. 10. To input height in feet and inches and then print the corresponding height in cms. (1ft=12inches ,1inch=2.54 cms)

Transfer control Statements


The Computer normally executes the statements sequentially. To transfer the Computer control from one statement to another, transfer control statements are used.

1.

Unconditional

2.

Conditional

Conditional Statements
Purpose It is meant to transfer the computer control from one statement to another depending on the satisfaction of a given condition. There are 2 conditional statements:

1. if statement if statement
Syntax:if (condition) statement; and

2. if else statement

if (condition) { statement 1; statement 2; }


If a=5 and b=4, then final value will be a=8 and b=7 If a=4 and b=5, then final value will be a=6 and b=8

Example:

1) if (a>b) a=a+1; b=b+1; a=a+2; b=b+2;

11

2) {

if(a>b) a=a+1; b=b+1 ;} a=a+2; b=b+2;

If a=5 and b=4, then final value will be a=8 and b=7 If a=4 and b=5, then final value will be a=6 and b=7

if-else statement
Example: 1) if (a>b) a=a+1; else b=b+1; a=a+2;

PROBLEMS (IF STATEMENT): COMMISSION


1. Write a C-program to input salesman number, name of the salesman, and sales. Calculate and print salesman number, name of the salesman, sales and commission. The commission is calculated as : Sales Commission <=1000 Nil >1000 and <=3000 5% >3000 and <=5000 10% >5000 25% of sales above 5000 plus Rs. 1200. 2. To input sales and calculate commission at 12% if the sales are more than 20000 and at 10% otherwise. Display sales and commission. 3. To enter name and sales. Print name and commission where commission is computed as follows: commission is 7%of sales. If sales exceed Rs. 50000 then additional 2% of amount exceeding Rs. 50000 is added to the commission. 4. Write C program to input class no. & value of goods & print class no, value goods & custom duty. Class no. Custom duty (% on value of goods) 1 10% 2 15.5% 3 25% 4 40%

5. Write a program to input roll number name & marks in 3 subject of a student & calculate the total marks, average marks and the result. Print the Name, total marks, average marks and result where the result is pass when the student gets 35 or more in each subject otherwise the result is fails. 6. Write a program in C to input meter number, current reading, previous reading and consumer type (residential (r) or commercial (c)). Calculate billing amount as per criteria given below Residential Commercial Units rate units rate 0-100 3.5 Rs /Unit 0-500 7.00 Rs/unit Above 100 5.5 Rs/Unit above 500 11.50 Rs /unit Print Consumer type, unit consume, and billing amount. 7. Input name of the worker, no. of hrs worked & rate per hour. Calculate regular wages, overtime wages, & total wages where, overtime is paid 1.5 times the regular rate if the no. of hrs worked exceeds 40. Print name, regular wages, overtime, & total wages.

12

EVEN, ODD AND VOWELS


8. To input one number and check whether it is even or odd. Print appropriate message. 9. To input any one character and check whether it is vowel or not.

INCOME TAX
10. Write a C-Program to input name and taxable income and then compute and print name and Incometax and net income. Where net income= taxable income income tax. where the tax is as follows. INCOME First 1, 10, 000 Next 1, 30, 000 Next 2, 70, 000 Excess INCOME-TAX Nil 10% 20% 25%

11. To input bill no and amount of sales. Calculate tax as follows: Sales First 50,000 Next 20,000 Next 30,000 Next 50,000 Excess Print bill no, sales, tax, and total amount. tax nil 10% 20% 30% 40%

Loop Control Structure


Purpose: Situation may arise in some environment, to repeat the process of same statements until a condition is reached. Such repetitive statements or block is called loop control structure. C supports three types of loop control structures. They are: -

1)

do while 1)

2)

while.

3)

for

do-while Loop

Format:initialization; do { statement 1; statement 2; .. increment/decrement; } while(condition); The block of statements are executed first. Then the condition is evaluated. The block of statements are executed repeatedly until the value of condition is false.

13

2) Format:initialization; while (condition) { statement 1; statement 2; increment/decrement; }

while loop

The condition is evaluated first. The block of statements are executed repeatedly until the value of condition is false.

3)

for loop

for loop structure is different from the other two. It has three expressions. The first one is initialization expression, second one is the condition, third is an expression that is executed for each execution. Syntax:1. for(initialization ; condition ; increment/decrement) Statement 1; for(initialization ; condition ; increment/decrement) {Statement 1; Statement 2;} for (i=1 ; i<=5 ; i++) printf(Computers\n);

2.

Examples: -

1.

Will print the message Computers 5 times on different lines 2. for (i=1 ; i<=5 ; i++)
{ printf (Computers\n); printf (Today\n); }

Will display the message Computers on one line and Today on another line ,five times.

PROGRAMS (LOOP):
SUM AND PRODUCT
1. 2. 3. 4. To find the sum of any 2 numbers for 10 sets of two numbers. To find the sum of any 10 numbers. To find the sum of any N numbers To find the product of any N numbers

SERIES
5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. To find the sum of first 100 natural numbers. To find the sum of odd numbers from 1 to 100. To find the sum of even numbers from 1 to 100. To find the sum of first 100 odd numbers. To find the product of first N natural numbers( Factorial N) To find the sum of 12+22+32+42+..1002 To find the sum of 13 +33 + 53+.233 To find the sum of 1 + 1 / 2 + 1 / 3 +.+ 1 / 50 To find the sum of 1 / 2 + 2 / 3 + 3 / 4 +.+ N / N+1 To find the sum of 12/2 + 22 / 3 + 32 / 4 +.+10 2 /11 To find the sum of 1x2 + 2x3 + 3x4 + .20x21 To find the sum of 2/(5*6) + 4/(7*8) + 6/(9*10) ++ 12/(15*16)

14

17. 18. 19. 20.

To find the sum of 1x k + 2x k + 3x k. n x k 3X5+7X8+11X11+31X26 2X5/3 + 3X10/4 + 4X15/5 + . 11X50 /12 2x52 + 5x72++ 302x2052

DEPRECIATION
21. For a certain machine depreciation is provided by straight-line method at a certain rate of purchase price. Print in tabular form Year, depreciation for the year, cumulative depreciation, and net value of the machine after providing depreciation at the year-end for the n years. For a certain machine depreciation is provided by reducing balance method at a certain rate of purchase price. Print in tabular form Year, depreciation for the year, cumulative depreciation, and net value of the machine after providing depreciation at the year-end for the n years. Write a C program to enter cost, rate of depreciation and number of years. Display depreciation for each year by WDV, along with WDV.

22.

23.

SIMPLE AND COMPOUNT INTEREST

24. 25.

Write a C program to enter amount to be invested, the period of investment and the rate of interest. The program should calculate & pint compound interest every year. Write a C program to enter amount to be invested, the period of invested and the rate of interest. The program should calculate and print simple interest every year.

INCOME TAX
26. To input for 5 persons the name, employee no. and their taxable income and calculate and print name number, income , tax and total amount using the following schedule Taxable income tax First 1,00,000 nil Next 1,20,000 20% Next 2,80,000 30% Excess 40%

PAYROLL
27. Write a program to input for 12 persons Name & Basic Salary & calculate Dearness Allowance, house rent allowance, provident fund & net salary, where dearness allowance is 40% of the basic salary or 10,000 whichever is less, house rent allowance is 30% of the basic salary or 3000 whichever is more, provident fund is 8.33% of the basic salary. Net salary = basic salary + dearness allowance + house rent allowance provident fund. Print Name, basic salary & net salary.

15

Comma operator: There can be more than one initialization, condition and increment in a for statement. If there are more than one initialization, condition and increment they should be separated by a comma. This is known as comma operator. For example: 1) { int a,b; Output: for(a=2,b=4;b<100;b+=4, a*=3) { b+=a; ^^^2^^^6^^18^^54 printf(%4d,a);}} 2) { int x,y; for(x=1,y=6;x<10,y<20;x++,y+=3) printf(%3d%3d\n,x,y);} The first condition will be ignored

3)

{int x=2,y=1; for(;x<=12;x+=4,y+=3); { printf(%4d%5d\n,x,y);} printf(%4d %5d,y,x);}

Output:

^^^2^^^^1 ^^^6^^^^4 ^^10^^^^7 ^^10^^^14

Nested Loops
A loop within another loop is Nested Loop. We start with outer loop & this loops does not get over, & we have to start inner loop. In nested loops for one value of the outer loop all the values of the inner loop are taken & when all the values of the inner loop are over then only value of outer is changed. for(i=1;i<=3;i++) for(j=1;j<=2;j++) printf( %d %d\n,i,j);
1 1 2 2 3 3 1 2 1 2 1 2

for(i=1;i<=3;i++) {for(j=1;j<=2;j++) Arrays {printf(The %d set of values are,i); printf( %d %d\n,i,j);}}

Arrays
To store each value in different location can be possible by creating an Array. Array is an arrangement of numbers in different locations. main() (Non-Array) {int x,i; for(i=1;i<=10;i++ ) {scanf(%d,&x); printf(%d,x); } main() (Array) {int x[10],i; for(i=0;i<=9;i++ ) {scanf(%d,&x[i]); printf(%d,x[i]); }

Array is a group of related data items that share a common name. Array should be declared as any data type with subscripted number given within square bracket. By declaring an Array, the specified number of locations are fixed in the memory. For example: int x[10]; represent an Array whose name is x which can declare 10 integer variables referred as x[0], x[1], x[2], x[3]..x[9]. Reference to array elements in C will always start from 0. There is no element called x[10].

16

Sorting
1. To input 10 number and arrange the numbers in ascending and print 5 number in one line. /*ascending order*/ #include<stdio.h> main() { int x[10],i, j, t; for(i=0;i<=9;i++) { printf(enter any value for x); scanf(%d, &x[i]); } for(i=0;i<=8;i++) { for(j=i+1;j<=9;j++) { if(x[i]>x[j]) { t=x[i]; x[i]=x[j]; x[j]=t; } } } printf(ascending order\n); for(i=0;i<=9;i++) printf(%16d,x[i]); return 0;} } } printf(descending order\n); for(i=0;i<=9;i++) printf(%16d,x[i]); return 0;} and print in ascending and descending order with 10
3. To arrange 13 number in ascending of order and print the range [range=highest value lowest value].

To arrange 10 numbers in descending order and print 5 number in one line /*descending order*/ #include<stdio.h> main() { int x[10],i, j, t; for(i=0;i<=9;i++) { printf(enter any value for x); scanf(%d, &x[i]); } for(i=0;i<=8;i++) { for(j=i+1;j<=9;j++) { if(x[i]<x[j]) { t=x[i]; x[i]=x[j]; x[j]=t; }

2. To arrange 20 number in ascending order number in one line /*ascending order*/ #include<stdio.h> main() { int x[20],i, j, t; for(i=0;i<=19;i++) { printf(enter any value for x); scanf(%d, &x[i]); } for(i=0;i<=18;i++) { for(j=i+1;j<=19;j++) { if(x[i]>x[j]) { t=x[i]; x[i]=x[j]; x[j]=t; } } } printf(ascending order\n) for(i=0;i<=19;i++) printf(%8d,x[i]); printf(descending order\n); for(i=19;i>=0;i--) printf(%8d,x[i]); return 0;}

/*ascending order*/ #include<stdio.h> main() { int x[13],i, j, t, range; for(i=0;i<=12;i++) { printf(enter any value for x); scanf(%d, &x[i]); } for(i=0;i<=11;i++) { for(j=i+1;j<=12;j++) { if(x[i]>x[j]) { t=x[i]; x[i]=x[j]; x[j]=t; }

} } range=x[12]-x[0]; printf(range of 13 numbers =%d, range); return 0;}

17

Switch Statement
C switch is a multi-directional conditional statement through which the control flow can be transferred in multi directions. Syntax: switch (expression) { case value 1: block of statements; break; case value 2: block of statements; break; . . default : block of statements; break;}

Rules of switch statements


1.

The expression value must be an integer, hence the type can be integer.

2. case should always be followed by an integer constant or expression. 3. All the cases should be distinct. 4. The block of statements under default is executed when none of the cases match the value. default is optional. 5. case and default can occur in any order.
6.

The break statement causes explicit exit from the switch. If it is not present, after executing a particular case, the following other cases are executed.

/* example of switch */ #include<stdio.h> main() {float a,b; char op; printf("enter any 2 nos and the operator"); scanf("%f %f %c", &a, &b, &op); switch(op) { case '+' : printf("sum of 2 nos=%f\n",a+b); break; case '-' : printf("diff of 2 nos=%f\n",a-b); break; case '*' : printf("prod of 2 nos=%f\n",a*b); break; case '/' : printf("sum of 2 nos=%f\n",a/b); break; default : printf("operator invalid=%c\n",op); break; }}

18

PROBLEMS ON SWITCH STATEMENT


1. Write a program in C to input the Name, grade and basic pay of an employee of a factory and calculate the bonus using the switch statement. Print the name and bonus where Grade Bonus A 50% of Basic B 60% of Basic C 70% of Basic Rest 80% of Basic

2. Write a program to enter vowel character from keyboard, depending on the response if it is a vowel print message you are a good reader otherwise you better improve reading.

3. The traffic police department takes the following action against owners of motos vehicles who have committed parking violations No of violations action 1 or 2 polite warning letter 3 strong warning letter 4 or 5 Collect Fine. 6 or more revoke license. 4. Input worker number, category, and hours worked. Calculate and print the wages. Using switch statement calculate wages as follows Category 1 2 3 4 Rate per hour 100 80 60 35.75 5. Input month number, using switch display a message as : summer if month is >=2 but <=5 Monsoon if month is >=6 but <=9, otherwise winter. 6. Input an integer. Display a message. Use switch statement Integer message 11 OR 12 DIG & DWELVE 13 OR 14 LET GO BOATING 15 OR 16 FRIENDS ARE WAITING Otherwise BETTER LUCK NEXT TIME 7. Input an alphabet. Input may be uppercase and lowercase. Display RED if the alphabet is R, BLUE is the alphabet is B, YELLOW is it y, otherwise display not a primary colour using switch statement.

Continue Statement
The continue statement is to by pass the remainder of current pass through a loop. Thus the loop does not terminate if continue statement is encountered. When the keyword continue is encountered inside any loop, control automatically passes to the beginning of the loop. For example: main() { int i,j; Output: for(i=1;i<=2;i++) 1^2 {for(j=1;j<=2;j++) 2^1 {if(i==j) continue; printf(%d %d\n,i,j);}}}

19

break Statement
Execution of break statement causes the program to immediately exit from the loop it is executing, whether its for, while or do loop. When the keyword break is encountered inside the loop, control automatically passes to first statement after the loop. If a break is executed from within a set of nested loops, only the innermost loop in which the break is executed is terminated.

Storage Classes
All variables have data types and the storage classes. There are basically two kinds of location in as computer where the contents of the variable are stored: Memory and CPU registers. It is the variable storage class which determines in which of these two locations the value is stored. Also the storage class gives us the idea about 1. Where the variable would be stored i.e. in the Main Memory or CPU register. 2. What will be the initial value of the variable, either Garbage or Zero. 3. What is the scope of the variable i.e., in which functions the value of the variable is available? 4. What is the life of the variable? There are 4 storage classes auto, register, static, & extern. Variables Location Initial value Scope Auto Memory Garbage Local to block Till control remains in the block auto int i; or int i; register CPU register Garbage Local to block Till control remains in the block register int i; static Memory Zero Local to block extern Memory Zero Global As long as program ends extern int i;

Life How to define

Value persist

static int i;

Revision and Tests is the Secret of getting 100 marks.

20

Format Output
1) main() { int x=125,y= -40, z=3344; printf(%d%d%d\n, x, y, z); printf(%d %d %d\n, x, y, z); } 125-403344 125^-40^3344 %d is called conversion specification. It is a conversion specification for integer type data. One can also specify width along with %d. e.g. %5d indicates: use 5 columns to print the number 2) main() { int x=125,y= -40, z=3344; printf(%6d%6d%6d\n,x,y,z); printf(%4d%5d%6d\n,x,y,z); } ^^^125^^^-40^^3344 ^125^^-40^^3344 Plus sign before the format. Plus sign indicates that the sign must be printed before the number. If the number is positive plus sign is printed otherwise minus sign is printed. 3) main() { int x=125,y= -40, z=3344; printf(%+6d %+5d %+5d\n,x,y,z); } ^^+125^^^-40^+3344 Minus sign before the format. Minus sign indicates that the number must be left justified during printing. 4) main() { int x=125,y= -40, z=3344; printf(%-10d%-8d%-10d\n,x,y,z);} 125^^^^^^^-40^^^^^3344^^^^^^ Plus and minus sign together indicate justified & sign must also be printed. 5) main() { int x=7000; printf(%+-6d %+-7d %+-10d\n,x,x,x); } +7000^^+7000^^^+7000^^^^^ if the size of the number is larger than the width of the field specified in the output format then the width is ignored. 6) main() { int x=17000; printf(%3d %5d %4d\n,x,x,x); } 17000^17000^17000 Zero (0) causes leading zeroes to appear instead of leading blanks, applies only to the data items that are right justified. the number must be left Integer and float type of data are right justified by default.

21

7)

main() {int x=1234; printf(%06d %-06d\n,x,x); } 001234^1234^^ main() { float x=4.556, y=-876.5432, z=888.7777; printf(%f %f %f\n, x, y, z); printf(%f%f%f\n, x, y, z);} 4.556000^-876.543200^888.777700 4.556000-876.543200888.777700

8)

%f always prints 6 digits after the decimal. To control number of digits use the format %.df where d stands for no. of places after decimal. 9) main() { float x=4.556, y=-876.5432, z=888.7777; printf(%.2f %.1f %.3f\n,x,y,z); } 4.56^-876.5^888.778 the least significant digit is always rounded.

%w.df This format can be used to specify width and decimal places during printing. 10) main() { float x=4.556, y=-876.5432, z=888.7777; printf(%10.1f %10.3f %8.0f\n,x,y,z); printf(%8.3f %10.2f %12.3f\n,x,y,z);} ^^^^^^^4.6^^^-876.543^^^^^^889 ^^^4.556^^^^-876.54^^^^^^888.778 Plus and minus sign to print the sign or to left justify the number respectively. 11) main() { float x=4.556, y=-876.5432, z=888.7777; printf(%+8.1f%+12.3f%+10.2f\n,x,y,z); printf(%-6.2f %-12.3f %-15.4f\n,x,y,z); printf(%+-5.0f %+-8.1f %+-12.2f\n,x,y,z);} ^^^^+4.6^^^^-876.543^^^+888.78 4.56^^^-876.543^^^^^888.7777^^^^^^^ +5^^^^-876.5^^^+888.78^^^^^ If the size of the number is larger than the width specified then width is ignored and the number is printed as it is. But the decimal part is not ignored. 12) main() { float x=112233.445566; printf(%10.3f %8.4f %5.3f\n,x,x,x); } 112233.446^112233.4456^112233.446

22

Printing character type data: %c is used as conversion specification to print the character type data. 13) main() {char x= $ ,y= #; printf(%c %c %c %c\n, x, y, y, x); printf(%c%c%c%c\n, y, x, x, y); printf(%4c%4c%4c\n, x, y, x); printf(%-4c%-4c%-4c\n, y, x, y); } $^#^#^$ #$$# ^^^$^^^#^^^$ #^^^$^^^#^^^ Printing string type data: %s is used as conversion specification to print the string type data. %w.ds format can be used for printing string type of data where, w stands for total width and d for the number of characters to be printed. 14) #include<stdio.h> main() { char n[]={D, i, p, a, w, a, l, i}; printf(%s\n, n); printf(%15s\n,n); printf(%15.4s\n,n); printf(%-15s\n,n); printf(%-15.4s\n,n); printf(%6s\n,n);} Dipawali ^^^^^^^ Dipawali ^^^^^^^^^^^Dipa Dipawali^^^^^^^ Dipa^^^^^^^^^^^ Dipawali

Character and string type of data are always right justified by default

15)

#include<stdio.h> main() { int a=339;float b=1234.9999; char p[]= WONDERFUL, c=*; printf(%-05d%+-10.2f%10.6s%4c\n,a,b,p,c); printf(%-8.4s%+6d%+-4.3f\n%-4c,p,a,b,c); } 339^^+1235.00^^^^^^WONDER^^^* WOND^^^^^^+339+1235.000 *^^^

23

- : Find the output: 1. #include<stdio.h> main() {int x=2,y=2; while(x<20) {y++; x+=++y; printf("%d %d\n",x,y);}} #include<stdio.h> main() {int x=2,t=0; while(x<7) {if(x%2==0) t+=2*x; else t+=2; printf("%d %d\n", x ,t); x++;}} #include<stdio.h> main() {int n=2,t=0; while(n<10) { if(n%2==0) t+=n; else t+=2*n; printf("%d ",t); n=n++; if(t>10) break;}} main() {int k=2,s=0,t=60; while(k<15) {s+=t; t-=10; k+=2; printf("%d %d %d\n", k, s, t); t*=k; if(t>200)break;}} main() {int x=10,y=15,z=300,t; z%=--y; t=4*x--; printf("%d %d %d %d\n", x, y, z, t);} #include<stdio.h> main() {int x=4,y=10; x=x++ ; y+=++x *2; y-=3; x-=2*y; printf("%d %d\n", x, y);} 15. 7 main() {int a, b, x; a=5; b=3; a+=b++; x=3%5; x+=++b*2; printf("a=%d b=%d\n x=%d",a,b,x);} 8 #include<stdio.h> main() {int a=0,n; for(n=10;n<25;n+=2) {a+=n; printf("%d\n", a); }} main() {int j=1,i; for(i=j-2;i<=5;i++) {j+=j; printf("value of j=%d\n", j);}} #include<stdio.h> main() { int i,j,k; for(i=1;i<4;i++) for(j=10;j<15;j+=2) {k=i+j; printf("%d %d %d\n",i,j,k); } printf(%d %d %d\n,i,j,k);} #include<stdio.h> {int x,y,z; for(x=12;x<17;x+=3) for(y=2;y<=5;y+=2) {z=x*y; printf("%d %d %d\n",x,y,z); }} main() { int i,j; for(i=1;i<=2;i++) {for(j=1;j<=2;j++) {if(i==j) continue; printf(%d %d\n,i,j);}}}

9. 2.

10.

3.

11.

4.

12.

5.

main() {int r,c,sum; for(c=1;c<=2;c++) for(r=1;r<=2;r++) { sum=r+c; printf("c=%d r=%d sum=%d\n",c,r,sum);}} 14. main() {int i,j,k=0; for(i=1;i<=5;++i) {for(j=1;j<=4;++j) {k=k+i-j; if(i>j)break; printf(%d,k);}} printf(\nk=%d,k);} main() {int x,y; for(x=1;x<=3;x++) for(y=2;y<=4;y+=2) printf("%d %d\n",x,y); }

13.

6.

24

16.

main() {int x,y; for(x=5,y=3;y<=20;x*=2,y+=5) y+=x; printf("%d %d\n",x,y);} 22. main() { int a,b; for(a=2,b=4;b<121;b+=4, a*=3) b+=a; printf(%4d,b);} main() { int x=3,y=2; for(;y<20,x<6;x+=2,y+=3) {y+=x; printf(%4d%5d\n,x,y);} printf(%4d%5d,y,x);} main() { int a,b; for(a=2,b=4;b<100;b+=4, a*=3) {b+=a; printf(%4d,a);}} main() {int x=2,y=3; for(;y<37;y+=3,x*=2) { y+=x*2; printf("%5d",y);}} main() {int a=2,s=0,j=1; 24.

for(;a<10;a+=3,j++) {s=a*a; printf(\n a=%d j=%d,a,j);} printf(\n j=%d a=%d s=%d,j,a,s);} main() {int f[10],i; f[0]=1;f[1]=1; i=2; while(i<5) {f[i]=f[i-1]+f[i-2]; i++;} for(i=0;i<5;i++) printf(%d,f[i]);}} main() {int x=10,y,z; y=x; z=y; y-=x--; z-=--x; x-=--x-x--; printf(x=%dy=%dz=%d\n,x,y,z); printf(x+y+z=%d,x+y+z);} main() {int x=1462,m,y=0; do {m=x%10; y=y*10+m; x/=10;} while(x!=0); printf(\n%d,y);}

17.

18

23.

19.

20.

21.

25

C-theory (6 to 8 marks)

Data Types
Data types are used to define the type of the variables used in a program in the beginning of a program. In C, there are basic five data types. int (to declare integer data types ) char (to declare Character data types ) float (to declare floating point data types ) double (to declare double floating point types) void (Valueless) (to declare Void data types)

Identifiers( variables)
Every C word is classified as either a keyword or an identifier. These are defined by the users and are names given to various program elements, such as Variables, Arrays and function .Rules of forming Identifiers 2) It can be made up of Alphabets (A- Z), Numbers (0 9) and Underscores( _ ) . 3) No other Special characters allowed except underscore. 4) First Character should be Alphabet or an underscore. 5) It can be maximum made up of 32 characters. 6) It must not be a Keyword.

Type Modifiers/ Data type qualifers


Each data type may have various type modifiers preceding them. A type modifier is used to change the meaning of basic data types to fit the needs of the various situations. The type modifiers are long, short, signed and unsigned.

Increment and Decrement Operators(++ and --)


To increase or decrease the variable by 1, increment and decrement operators ++ and -are used. The incrementing and decrementing by 1 can be of 2 types. 1. First increase or decrease then take the value for processing (Prefix) 2. Take the value for processing &then increment or decrement the variable.(Postfix)

Cast Operator
At times we need to force an expression to be of specific type. This is called as casting. e.g int a=5, b=2; float k; k= a/b; (will give the value of k as 2.)k= (float) a/b; (Value of k as 2.5)

Control string or Conversion Specification


is meant to control the data while inputting or displaying Conversion Character Meaning %d indicates the type to integer %ld indicates the type to long integer %f indicates the type to float %lf indicates the type to long float %c indicates the type to character %s indicates a string of characters

Unformatted input functiongetch(), getche(), getchar() & gets():


getch(): getche(): getchar(): gets(): It reads a single character immediately as it is typed without waiting for the enter key to be pressed. It reads a single character without waiting for the enter key to be pressed. The e in getche() means it echoes(displays) the typed character on the screen. It reads a single character but requires the Enter key to be pressed. It displays the character typed. It allows to receive the string in a response from keyboard. After typing the desired response an enter key is to be pressed. End of string End of a line Horizontal tab Back space Null Moves active position to initial position of next line. Moves active position to the next horizontal position Moves active position to previous position on current line

Escape Sequence
\0 \n \t \b

26

Unformatted output function putch(),putchar()and puts(): putch()or putchar():


It is meant to display a single character on the screen. It does not give line feed like printf puts(): It allows to print only string data on a new line. It generates line feed automatically. C preprocessor The C preprocessor is a program that processes our source program before it is passed on to the compiler. The processor commands are known as directives. Each of these directives begin with # symbol & can be placed anywhere in program, but are generally placed at the beginning of the program before the main() function. They include macro definition(# define) and file inclusion(# include).

File inclusion(Header files)


These functions are stored as files under different names (headings) and these are known as header files. The header files stdio.h includes some of the input and output procedures. The header files math.h includes mathematical functions. To use the C functions, one has to include the required header files by using #include<headerfile.h>

main()
Every C program is made up of one or more than one functions. The only compulsory function that should be present in each and every program is the function main().

return 0
This statement returns a value zero to the function main(). This is required in some compilers where the function should always return some value.

Arrays
Array is a group of related data items that share a common name. Array should be declared as any data type with subscripted number given within square bracket. By declaring an Array, the specified number of locations are fixed in the memory.

return Statement
This is used in functions to return a value to the calling function. Every function subprogram can end with return.

switch Statement
C switch is a multi-directional conditional statement through which the control flow can be transferred in multi directions.

continue Statement
The continue statement is to bypass the remainder of current pass through a loop. Thus the loop does not terminate if continue statement is encountered.

break Statement
Execution of break statement causes the program to immediately exit from the loop it is executing, whether its for, while or do loop.

Storage Classes
All variables have data types and the storage classes. There are basically two kinds of location in as computer where the contents of the variable are stored: Memory and CPU registers. It is the variable storage class which determines in which of these two location the value is stored. There are 4 storage classes auto, register, static & extern. Variables Location Intial value Scope Automatic Memory Garbage Local block Register Static Memory Zero Local block External Memory Zero to Global CPU register Garbage to Local to block

27

Difference between: gets()


gets()is an input statement which is capable of accepting multiword strings. can accept only string data

scanf()
scanf is a input statement which is not capable accepting multiword strings Can accept all types of data such as integer, floating point, character and string.

Printf()
Does not generate line feed automatically. e.g.; printf(GOOD); printf(DAY); output: GOODDAY Can display all types of data such as integer floating point, character and string. Printf is an formatted output statement

puts()
Generates line feed automatically. e.g.; puts(GOOD); puts(DAY); output: GOOD DAY can display only string data. puts() is an unformatted output statement.

Scanf()
scanf can input all types of data i.e. integer floating point, and character data

getch()/getche()/getchar()
getch() or getchar() or getch() accepts only character data.

printf()
printf can print all types of data i.e. integer floating point, and character data printf is an formatted output statement

putch()/putchar()
putch() or putchar() will print only character data. putch()/putchar() is an unformatted output statement.

while loop
The while loop is an entry controlled loop i.e., it evaluates the condition in the beginning of the loop and if the condition is false in the beginning, the loop is never executed

do- while loop


do while is an exit controlled loop i.e., it evaluates its condition at the bottom of the loop and if the condition is false in the beginning, still the loop is executed once.

Break
break statement causes an immediate exit from the loop structure. It can also be used along with the switch statement to terminate the switch statement.

Continue
continue statement bypasses the remaining statements of the loop and forces the next repetition of the loop to take place.

Switch
C switch is a multi-directional conditional statement through which the control flow can be transferred in multi directions. In switch statement, value of the variable is checked. In switch statement, only one value or variable can be checked.

If
if is a transfer control statement, meant to transfer the computer control from one statement to another depending on the satisfaction of a given condition In if statement, the condition is checked. In if statement, more than one condition can be checked.

While
While() is a looping statement where the condition is check first and then actions are carried out repeatedly

If
If() is a condition statement where condition is checked and action is carried out once

=(assign)
= is a assignment operator which assign the value to an identifier or variable

== (equal to)
= = is relational operator which is used to check equality

%c
%c is conversion specification (control string) data item is displayed a single character.

%s
%s is conversion specification (control string) data item is displayed as a string with or without blank

28

Solutions for Simple Program (page number 8)


1) /*sum of two number*/ #include<stdio.h> main() { float a, b, s; printf(enter any two values); scanf(%f %f, &a, &b); s=a+b; printf(value of a=%.2f\n,a); printf(value of b=%.2f\n,b); printf(sum=%.2f\n,s); return 0;} /*average of 3 numbers*/ #include<stdio.h> main() { float a,b,avg; printf(enter any 3 values); scanf(%f %f %f, &a, &b, &c); avg=(a+b+c)/3; printf(average=%.2f\n, avg); return 0;} /*area and circumference*/ #include<stdio.h> #include<math.h> main() { float r, a, c; printf(enter radius); scanf(%f,&r); a=3.14*pow(r,2); c=2*3.14*r; printf(area=%.2f\n,a); printf(circumference=%.2f\n,c); return 0;} /*area and perimeter*/ #include<stdio.h> main() {float l,b,a,p; printf(enter length and breadth); scanf(%f %f,&l,&b); a=l*b; p=2*(l+b); printf(area=%.2f\n,a); printf(perimeter=%.2f\n,p); return 0;} /*amount in rupees*/ #include<stdio.h> main() { float d, r, ar; printf(enter dollar and rate of exchange); scanf(%f %f, &d, &r); ar=d*r; printf(amount in rupees=%.2f\n,ar); return 0;}

2)

3)

4)

5)

29

6)

/*total time in seconds*/ #include<stdio.h> main() {float h, m, s, ts; printf(enter time in hours, minutes and seconds); scanf(%f %f %f, &h, &m, &s); ts = h*3600 + m*60 + s; printf(total time in seconds =%.2f\n, ts); return 0;} /*sales and commission*/ #include<stdio.h> main() {char sn[20]; float as, com; printf(enter name and sales); scanf(%s %f, n, &as); com= as*0.07; printf(name=%s\n, sn); printf(sales=%.2f\n, as); printf(commission=%.2f\n, com); return 0;} /*sales and discount*/ #include<stdio.h> main() {int sno; float as, np, dis; char sn[20]; printf(enter salesman number, name and sales); scanf(%d %s %f, &sno, sn, &as); dis=as*0.12; np =as-dis; printf(salesman number=%d\n, sno); printf(salesman name=%s\n, sn); printf(salesman sales=%.2f\n, as); printf(salesman discount=%.2f\n, dis); printf(salesman net price=%.2f\n, np); return 0;} /*compound interest*/ #include<stdio.h> #include<math.h> main() {float p, r, n, ci; printf(enter principal , rate of interest and no of years); scanf(%f %f %f, &p, &r, &n); ci= p*pow(1+r/100,n)-p; printf(compound interest=%.2f\n, ci); return 0;} /*corresponding height in cms*/ #include<stdio.h> main() { float hf, hi, cms; printf(enter height in feet and height in cms); scanf(%f %f, &hf, &hi); cms= hf*12*2.54 + hi*2.54; printf(corresponding height in cms=%.2f\n, cms); return 0;}

7)

8)

9)

10)

30

Solutions for If Statement Program (page number 9)


1) /*sales and commission*/ #include<stdio.h> main() {int sno; float as, comm; char n[20]; printf(enter salesman number, name and sales); scanf(%d %s %f, &sno, n, &as); if(as<=1000) comm=0; else if(as>1000 && as<=3000) comm=as*0.05; else if(as>3000 && as<=5000) comm=as*0.10; else comm=(as-5000)*0.25+1200; printf(salesman number=%.2f\n, sno) printf(salesman name=%s\n, n); printf(salesman sales=%.2f\n, as); printf(salesman commission=%.2f\n, comm); return 0;} 2) /*sales and commission*/ #include<stdio.h> main() { float as, comm; printf(enter sales); scanf(%f,&as); if(as>20000) comm=as*0.12; else comm=as*0.10; printf(sales=%.2f\n, as); printf(commission=%.2f\n, comm); return 0;} /*sales and commission*/ #include<stdio.h> main() { char n[20]; float as, comm; printf(enter name and sales); scanf(%s %f, n, &as); if(as>50000) comm=as*0.07+(as-50000)*0.02; else comm=as*0.07; printf(name = %s\n,as); printf(commission=%.2f\n, comm); return 0;} /*custom duty*/ #include<stdio.h> main() {

3)

4)

31

int cno; float cd, vg; printf(enter class number and value of goods); scanf(%d %f, &cno, &vg); if(cno==1) cd=vg*0.10; else if(cno==2) cd=vg*0.155; else if(cno==3) c=vg*0.25; else c=vg0.40; printf(class number=%d\n, cno); printf(value of good=%.2f\n, vg); printf(custom duty=%.2f\n, cd); return 0;} 5) /*total, average, result*/ #include<stdio.h> main() { int rn; float m1, m2, m3, tm, avg; char n[20]; printf(enter roll number, name, marks in 3 subjects); scanf(%d %s %f %f %f, &rn, n, &m1, &m2, &m3); tm=m1+m2+m3; avg=(m1+m2+m3)/3; if(m1>=35 && m2>=35 && m3>=35) printf(result is pass\n); else printf(result is fail\n); printf(name=%s\n, n); printf(total marks=%.2f\n, tm); printf(average marks=%.2f\n, avg); return 0;} 6) /*electricity bill*/ #include<stdio.h> main() { int mno; float cr, pr, uc, bill; char type; printf(enter meter number, current & previous reading , type); scanf(%d %f %f %c, &mno, &cr, &pr, &type); uc=cr-pr; if(type== r) { if(uc<=100) bill=uc*3.5; else bill=(uc-100)*5.5+100*3.5; } else { if(uc<=500) bill=uc*7; else

32

bill=(uc-500)*11.50+500*7; } printf(consumer type=%c\n, type); printf(unit consume=%.2f\n, uc); printf(billing amount=%.2f\n, bill); return 0;} 7) /*wages*/ #include<stdio.h> main() { float hw, r, rw, ow, tw; char wn[20]; printf(enter workers name, hours worked , rate per hour); scanf(%s %f %f, wn, &hw, &r); if(hw>40) { rw=40*r; ow=(hw-40)*r*1.5; tw= rw + ow; } else { rw=hw*r; ow=0; tw=rw + ow; } printf(name=%s\n, wn); printf(regular wages=%.2f\n, rw); printf(overtime wages=%.2f\n, ow); printf(total wages=%.2f\n, tw); return 0; } 8) /*even or odd*/ #include<stdio.h> main() { int x; printf(enter any value); scanf(%d,&x); if(x%2==0) printf(number is even =%d\n, x); else printf(number is odd= %d\n,x); return 0; } /*vowel*/ #include<stdio.h> main() { char x; printf(enter any character); scanf(%c, &x); if(x== a || x== e || x== i || x== o || x== u) printf(the character is vowel=%c\n, x); else printf(the character is not a vowel=%c\n,x); return 0;}

9)

33

10)

/*income tax*/ #include<stdio.h> main() {char n[20]; float in, tax ,net; printf(enter name and income); scanf(%s %f, n, &in); if(in<=110000) tax=0; else if(in>110000 && in<=240000) tax=(in-110000)*0.10; else if(in>240000 && in<=510000) tax=(in-240000)*0.20+130000*0.10; else tax=(in-510000)*0.25+270000*0.20+130000*0.10; net=in-tax; printf(name=%s\n, n); printf(income tax=%.2f\n, tax); printf(net income=%.2f\n, net); return 0;}

11)

/*sales*/ #include<stdio.h> main() { int bn; float as, tax, totamt; printf(enter bill number, sales); scanf(%d %f, &bn, &as); if(as<=50000) tax=0; else if(as>50000 && in<=70000) tax=(as-50000)*0.10; else if(as>70000 && in<=100000) tax= (as-70000)*0.20+20000*0.10; else if(as>100000 && as<=150000) tax=(as-100000)*0.30+30000*0.20+20000*0.10; else tax=(as-150000)*0.40+50000*0.30+30000*0.20+20000*0.10; totamt=as + tax; printf(bill number=%.2f\n, bn); printf(sales=%.2f\n, as); printf(tax=%.2f\n, tax); printf(total amount=%.2f\n, totamt); return 0;}

34

Solutions for Loops Program (page number 11)


1) /*sum of two number*/ #include<stdio.h> main() { float a, b, s, i; for(i=1;i<=10;i++) { printf(enter any two values); scanf(%f %f, &a, &b); s= a + b; printf(sum of two number=%.2f\n, s); } return 0;} 2) /*sum of any 10 number*/ #include<stdio.h> main() { float a, s=0,i; for(i=1;i<=10;i++) { printf(enter any value); scanf(%f, &a); s=s + a; } printf(sum of 10 number=%.2f\n, s); return 0;} 3) /*sum of any N numbers*/ #include<stdio.h> main() { float a,s=0,n,i; printf(enter any value for n); scanf(%f,&n); for(i=1;i<=n;i++) { printf(enter any value); scanf(%f, &a); s=s+a; } printf(sum of N numbers=%.2f\n,s); return 0;} 4) /*product of N numbers*/ #include<stdio.h> main() { float a, p=1,n,i; printf(enter any value for n); scanf(%f, &n); for(i=1;i<=n; i++) { printf(enter any value); scanf(%f, &a); p=p*a; } printf(product of N numbers=%.2f\n,p); return 0;} 5) /*sum of 100 natural number*/ #include<stdio.h>

35

main() { float s=0,i; for(i=1;i<=100;i++) { s=s + i; } printf(sum of 100 Natural numbers=%.2f\n,s); return 0;} 6) /*sum of 1 to 100 odd numbers*/ #include<stdio.h> main() { float s=0,i; for(i=1;i<=100;i=i+2) { s= s+i; } printf(sum of 1 to 100 odd number=%.2f\n, s); return 0;} 7) /*sum of 1 to 100 even number*/ #include<stdio.h> main() { float s=0,i; for(i=2;i<=100;i=i+2) { s=s+i; } printf(sum of even number=%.2f\n, s); return 0;} 8) /*sum of first 100 odd number*/ #include<stdio.h> main() { float s=0,i; for(i=1;i<=199;i=i+2) { s=s+i; } printf(sum of first 100 odd number=%.2f\n, s); return 0;} 9) /*product of N natural number*/ #include<stdio.h> main() { float n, p=1,i; printf(enter any value for N); scanf(%f, &n); for(i=1;i<=n; i++) { p=p*i; } printf(product of N natural number=%.2f\n, p); return 0;} 10) /*sum of series*/ #include<stdio.h> #include<math.h>

36

main() { float s=0,i; for(i=1;i<=100;i++) { s=s+pow(i,2) } printf(sum of series=%.2f\n,s); return 0;} 11) /*sum of series*/ #include<stdio.h> #include<math.h> main() { float s=0,i; for(i=1;i<=23;i=i+2) { s=s + pow(i,3); } printf(sum of series=%.2f\n, s); return 0;} 12) /*sum of series*/ #include<stdio.h> main() { float s=0,i; for(i=1;i<=50;i++) { s=s + 1/i; } printf(sum of series=%.2f\n,s); return 0;} 13) /*sum of series*/ #include<stdio.h> main() { float i, s=0,n; printf(enter any value for n); scanf(%f, &n); for(i=1;i<=n; i++) { s=s+i/(i+1); } printf(sum of series=%.2f\n, s); return 0;} 14) /*sum of series*/ #include<stdio.h> #include<math.h> main() { float i, s=0; for(i=1;i<=10;i++) { s=s + pow(i,2)/(i+1); } printf(sum of series=%.2f\n,s); return 0;}

37

15) /*sum of series*/ #include<stdio.h> main() { float i, s=0; for(i=1;i<=20;i++) { s=s+i*(i+1); } printf(sum of series=%.2f\n,s); return 0;} 16) /*sum of series*/ #include<stdio.h> main() { float i, s=0; for(i=2;i<=12;i++) { s=s+i/((i+3)*(i+4)); } printf(sum of series=%.2f\n,s); return 0;} 17) /*sum of series*/ #include<stdio.h> main() { float n, k, i,s=0; printf(enter value for n and k); scanf(%f %f, &n, &k); for(i=1;i<=n;i++) { s=s+i*k; } printf(sum of series=%.2f\n,s); return 0;} 18) /*sum of series*/ #include<stdio.h> #include<math.h> main() { float s=0,i,j,x; printf(enter value for x); scanf(%f, &x); for(i=3,j=5;i<=31,j<=26;i=i+4,j=j+3) { s=s+i*pow(x, j); } printf(sum of series=%.2f\n,s); return 0;} 19) /*sum of series*/ #include<stdio.h> #include<math.h> main() { float i,j,s=0,x; printf(enter any value for x); scanf(%f, &x); for(i=2,j=5;i<=11,j<=50;i=i+1,j=j+5) {

38

s=s+i*pow(x,j)/(i+1); } printf(sum of series=%.2f\n,s); return 0;} 20) /*sum of series*/ #include<stdio.h> main() { float i, j, s=0; for(i=2,j=5;i<=302,j<=205;i=i+3,j=j+2) { s=s+i*j; } printf(sum of series=%.2f\n, s); return 0;} 21) /*depreciation slm method*/ #include<stdio.h> main() { float val, r, dep, cd=0,i,n; printf(enter value rate and number of years); scanf(%f %f %f, &val, &r, &n); dep=val*r/100; printf(years \t\t depre\t\t cul dept\t\t net value\n); for(i=1;i<=n; i++) { cd=cd + dep; val=val-dep; printf(%.0f\t\t%.2f\t\t%.2f\t\t%.2f\n,i,dep,cd,val); } return 0;} 22) /*depreciation wdv method*/ #include<stdio.h> main() { float val, r, dep, cd=0,i,n; printf(enter value rate and number of years); scanf(%f %f %f, &val, &r, &n); printf(years \t\t depre\t\t cul dept\t\t net value\n); for(i=1;i<=n; i++) { dep=val*r/100; cd=cd + dep; val=val-dep; printf(%.0f\t\t%.2f\t\t%.2f\t\t%.2f\n, i, dep, cd, val);} return 0;} 23) /*depreciation wdv method*/ #include<stdio.h> main() { float val, r, dep, cd=0,i,n; printf(enter value rate and number of years); scanf(%f %f %f, &val, &r, &n); printf(depre\t\t depreciated value\n); for(i=1;i<=n; i++) {

39

dep=val*r/100; val=val-dep; printf(%.2f\t\t%.2f\n, dep, val);} return 0;} 24) /*compound interest*/ #include<stdio.h> #include<math.h> main() { float p n, r, ci, i; printf(enter amount to be invested, period & rate); scanf(%f %f %f, &p, n, &r); for(i=1;i<=n; i++) { ci=p*r*1/100 p=p+ci; printf(years=%.0f\t\t compound interest=%.2f\n, i, ci); } return 0; } 25) /*simple interest*/ #include<Stdio.h> #include<stdio.h> #include<math.h> main() { float p, n, r, si, i; printf(enter amount to be invested, period & rate); scanf(%f %f %f, &p, &n, &r); for(i=1;i<=n; i++) { si=p*i*1/100 printf(years=%.0f\t\t Simple interest=%.2f\n, i, ci); } return 0; } 26) /*income tax*/ #include<stdio.h> main() { int eno; char en[20]; float in, tax, i, totamt; for(i=1; i<=5; i++) { printf(enter employee number, name and income); scanf(%d %s %f, &eno, en, &in) if(in<=100000) tax=0; else if(in>100000 && in<=220000) tax=(in-100000)*0.20; else if(in>220000 && in<=500000) tax=(in-220000)*0.30+120000*0.20; else tax=(in-500000)*0.40+280000*0.30+120000*0.20; totamt=in+tax;

40

printf(employee number=%.2f\n, eno); printf(employee name=%s\n, en); printf(employee income=%.2f\n, in); printf(employee tax=%.2f\n, tax); printf(total amount=%.2f\n, totamt); } return 0; } 27) /*payroll*/ #include<stdio.h> main() { char en[20]; float bs, da, hra, pf, ns, i; for(i=1; i<=12 ;i++) { printf(enter name and basic salary); scanf(%s %f, en, &bs); da= bs*0.40; if(da>10000) da=10000; hra=bs*0.30; if(hra<3000) hra=3000; pf=bs*0.833; ns=bs + da + hra - pf; printf(name=%s, en); printf(basic salary=%.2f\n, bs); printf(net salary=%.2f\n, ns);} return 0;}

41

Solutions for Switch Statement (page number 16)


1) /*bonus*/ #include<stdio.h> main() { char gr, n[20]; float bs, bonus; printf(enter name, grade and basic); scanf(%s %c %f, n, &gr, &bs); switch(gr) { case A: bonus=bs*0.50; break; case B: bonus=bs*0.60; break; case C: bonus=bs*0.70; break; default bonus=bs*0.80; } printf(name=%s\n, n); printf(bonus=%.2f\n, bonus); return 0;}

/*vowel*/ #include<stdio.h> main() { char x; printf(enter any character); scanf(%c, &x); switch(x) { case a: case e: case i: case o: case u: printf(you are good reader\n); default: printf(you better improve reading\n); } return 0; }

3. /*traffic police */ #include<stdio.h> main() { int no; printf(enter number of violations) scanf(%d, &no); switch (no) { case 1: case 2: printf(polite warning letter\n); break; case 3: printf(strong warning letter\n); break; case 4: case 5: printf(collect fine\n); break: default: printf(revoke license); } return 0; }

4. /*wages*/ #include<stdio.h> main() { int wn, cat; float rate, w, hw; printf(enter n0., category & hours); scanf(%d %d %f, &wn, &cat, &hw); switch (cat) { case 1: w= hw*100; break; case 2: w=hw*80; break; case 3: w=hw*60; break; default: w=hw*35.75; } printf(wages=%.2f\n, w); return 0;}

42

5. /*seasons*/ #include<stdio.h> main() { int m; printf(enter number of the month); scanf(%d, &m); switch (m) { case 2: case 3: case 4: case 5: printf(summer\n); break; case 6: case 7: case 8: case 9: printf(monsoon\n); break; default: printf(winter\n) } return 0; }

6. /*message*/ #include<stdio.h> main() { int no; printf(enter any integer); scanf(%d, &no); switch (no) { case 11: case 12: printf(DIG & DWELVE\n); break; case 13: case 14: printf(LET GO BORATING\n); break; case 15: case 16: printf(FRIENDS ARE WAITING\n); break; default: printf(BETTER LUCK NEXT TIME\n); } return 0; }

7. /*alphabet*/ #include<stdio.h> main() { char x; printf(enter any character); scanf(%c, &x); switch (x) { case R: case r: printf(red\n); break; case B: case b: printf(blue\n); break; case Y: case y: printf(yellow\n); break; default: printf(not a primary colour) } return 0;}

Vous aimerez peut-être aussi