C Program Lakhani Notes (Program With Soln + Objectives)

download C Program Lakhani Notes (Program With Soln + Objectives)

of 42

Transcript of C Program Lakhani Notes (Program With Soln + Objectives)

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    1/42

    1

    Lakhanis T.Y.B.COM COMPUTERS

    Class : 9930203872Shruti miss : 9820789390Sir : 9820360320

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    2/42

    2

    C-LanguageIntroductionC Language was 1stdeveloped 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 wordsAt the time of designing a language, some words are reserved to do specific task. Such words are calledKeywords or Reserved words. All these should be written in lower case.int struc goto const union return dosigned auto sizeof while long short unsignedextern break switch volatile char register continueenum float if default double static else entry

    Constants and IdentifiersConstants: -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 adecimal point. Numeric constant is of 2 types.

    i) Integer Constant ii) Real Constant (Floating

    point constant)i) Integer ConstantInteger constants are numeric constants, which do not have a

    decimal point.

    Rules of forming Integer Constant1. An integer constant must have at least one digit2. No Alphabetsand decimal pointare allowed3. No special Charactersexcept +, -If + or is used it should be firstcharacter.4. No commasor blanks are allowed5. The range allowed is 32768 to +32767Examples: - Valid: - 426, +782, -800 Invalid: - 12, 000, A123, 12 45, 67+

    ii) Real Constant (Floating point constant)Real Constants are often called Floating Point. They are

    constants, which have decimal point.

    Rules of Forming Real Constant1. It is made up ofnumeric numbersfrom (0 9).No alphabetsare allowed2. Itmusthave 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 ConstantsA 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 valueassociated with it. This numeric value is known as ASCII code.

    Example: - A, 5, =, (blank space).

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    3/42

    3

    3) String ConstantsIt 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 characterconstants 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 theusers and are names given to various program elements, such asVariables, Arrays, and function.

    Rules of forming Identifiers1. It can be made up ofAlphabets (A- Z), Numbers (0 9) and Underscores(_).2. No other Special characters allowed except underscore.3. First Character should beAlphabet or an underscore.4. It can bemaximummade up of32 characters.5. It must not be a Keyword.6. 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 IdentifiersA, A1, COMM, SALARY, SAL, SAL_INT, IND_COMM, TOT_COMM_SAL.

    Imp points to remember:-1.Each & every character should written in lower case . OnlyIdentifiers 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 thebeginning of the program.

    Data TypesData types are used to define the type of the variables used in a program in thebeginning

    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 QualifiersEach data type may have various type modifiers preceding them. A type modifier is used to change themeaning of basic data types to fit the needs of the various situations. The type modifiers arelong, short, signed and unsigned.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    4/42

    4

    Operators1. Arithmetic OperatorsThere 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 carryout 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 OperationsPriority Operators Description1st * / % Multiplication, Division, Modulus Division

    2nd + - Addition, subtraction3rd = Assignment

    2. Relational OperatorsRelational operators are= =(equal to) , !=(not equal) , < , >

    , =

    3. Logical operatorsLogical Operators are ! ( not ) && (and) || (or)

    4. Assignment OperatorsThe Assignment operators are += -= *= /= %=Examples: s=s+a (s+=a) s=s-a (s-=a) s=s*a (s*=a) 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 decrementoperators ++ 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 OperatorsThe 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 toleft.

    Cast OperatorAt 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 sayx= (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.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    5/42

    5

    C StatementsComments Statement

    Purpose User comments in the program explain certain aspect of the program. It is meant

    to identifythe program. The comment should be enclosed by /* and */. It is an

    optional statement and can be included anywhere within the program

    .Syntax /* any message */

    Action Nil, as it is a non-executable statement.

    Example /* income tax calculation */

    Assignment StatementPurpose It is meant to store values in Computer Memory by assigning a name to

    the value.

    Syntax Variable = Constant / Variable / Expression;

    Action The right hand sideexpression is evaluated and result obtained is stored in the variablegiven on the left hand side.

    Examples a=0, a=5, a=b , s=a+b , comm=sales*0.12, avg =(a +b + c)/3

    Input output statementsInput Output statements are used to provide communication between the user and the program. Theprogram, which contains input/output function, must contain the statement #include at

    the beginning. The file name stdio.h is an abbreviation for standard input-output headerfile.

    Input function1. Formatted input function scanf():

    Purpose With this function call all types of values can be read i.e., int, float,

    character & string.

    Syntax scanf(control string , List of Variables separated by comma);

    Action The execution stops temporary and waits for the user to supply the data.

    Control string or Conversion Specification/characterUser has to provide the type and size of the data. Percent (%) symbol should precede the conversioncharacter. The following are some of the conversion character.

    Conversion Specification /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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    6/42

    6

    %s indicates a string of characters

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    7/42

    7

    Control string: - This contains the conversion characters & determines the number of argumentsthat 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 readsa single characterimmediately as it is typed without

    waiting for the enter keyto be pressed.

    getche() : It reads a single character without waiting for the

    enter keyto 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 thedesired response an enter key is to be pressed

    Escape SequenceThe characters on keyboard can be printed or displayed by a press on the key. But some characters suchas line feed, form feed, tab etc cannot be printed or displayed directly. C provides the mechanism to getsuch 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 asfollows:

    Escape Meaning Result\0 End of string Null

    \n End of a line Moves the active position to the initial position of thenext line.

    \t Horizontal tab Moves the active position to the next horizontal

    position\b Back space Moves the active position toprevious position on current

    line

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

    1. Formatted output function printf():Purpose With this function all types of values can be written. This does not

    give line feed.Syntax printf(control string, list of variables, expression, & constants separated by comma);Example 1. printf(Value of a=%d,a);

    printf(Value of b=%d,b);

    2. 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 feedlike printf statement.

    2. printf(Value of a=%d\n, a);printf(Value of b=%d, b);

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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    8/42

    8

    puts(): It allows toprint only string data on a new line. It

    generates line feedautomatically.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    9/42

    9

    C preprocessorThe 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. Theyincludemacro 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 andoutput procedure like getchar(), getch(), putchar() and clrscr()

    function. To use the C functions, one has to include the required header files by using

    #include

    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 , and .Aprototype 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 compulsoryfunction that should be present in each and every program is the

    function main().The function main() indicates that the program starts from here.

    return 0This 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 thisstatement is not included a warning message appears function should return a value whilecompilation. This statement can be avoided if the function main() is defined as void main().

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    10/42

    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 compoundinterest 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 StatementsThe Computer normally executes the statements sequentially. To transfer the Computer control from onestatement to another, transfer control statements are used.

    1. Unconditional 2. ConditionalConditional Statements

    Purpose It is meant to transfer the computer control from onestatement to another depending on the satisfaction of a

    given condition. There are 2 conditional statements:

    1. if statement 2. if else statementif statementSyntax:- if(condition) and if (condition)

    statement; { statement 1;statement 2;

    }Example: 1) 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=8

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    11/42

    11

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

    b=b+1 ;}a=a+2;b=b+2;

    if-else statementExample: 1) if (a>b)

    a=a+1;else

    b=b+1;a=a+2;

    PROBLEMS (IF STATEMENT): -

    COMMISSION1. 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 Commission1000 and 3000 and 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 totalmarks, average marks and the result. Print the Name, total marks, average marks and result where theresult 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 rate0-100 3.5 Rs /Unit 0-500 7.00 Rs/unitAbove 100 5.5 Rs/Unit above 500 11.50 Rs /unitPrint Consumer type, unit consume, and billing amount.

    7. Input name of the worker, no. of hrs worked & rate per hour. Calculate regular wages, overtimewages, & total wages where, overtime is paid 1.5 times the regular rate if the no. of hrs workedexceeds 40. Print name, regular wages, overtime, & total wages.

    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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    12/42

    12

    EVEN, ODD AND VOWELS8. 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 TAX10.Write a C-Program to input name and taxable income and then compute and print name and Income-

    tax and net income. Where net income= taxable income income tax. where the tax is as follows.

    INCOME INCOME-TAXFirst 1, 10, 000 Nil

    Next 1, 30, 000 10%Next 2, 70, 000 20%Excess 25%

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

    Print bill no, sales, tax, and total amount.

    Loop Control Structure

    Purpose: - Situation may arise in some environment, to repeat theprocess 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 2) while. 3) for

    1) do-while LoopFormat:-

    initialization;do{

    statement 1;statement 2;..

    increment/decrement;}while(condition);

    The block of statements are executed first. Then thecondition is evaluated. The block of statements are

    executed repeatedly until the value of condition is false.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    13/42

    13

    2) while loopFormat:-

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

    3) for loopfor loop structure is different from the other two. It has threeexpressions. The first one is initialization expression, second one isthe condition, third is an expression that is executed for each

    execution.

    Syntax:- 1. for(initialization ; condition ; increment/decrement)Statement 1;

    2. for(initialization ; condition ; increment/decrement){Statement 1;Statement 2;}

    Examples: - 1. for (i=1 ; i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    14/42

    14

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

    DEPRECIATION21. 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, cumulativedepreciation, and net value of the machine after providing depreciation at the year-endfor the n years.

    22. For a certain machine depreciation is provided by reducing balance method at acertain rate of purchase price. Print in tabular form Year, depreciation for the year,cumulative depreciation, and net value of the machine after providing depreciation atthe year-end for the n years.

    23. Write a C program to enter cost, rate of depreciation and number of years.Display depreciation for each year by WDV, along with WDV.

    SIMPLE AND COMPOUNT INTEREST

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

    25. Write a C program to enter amount to be invested, the period of invested and the rateof 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 calculateand print name number, income , tax and total amount using the following schedule

    Taxable income tax

    First 1,00,000 nilNext 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 DearnessAllowance, house rent allowance, provident fund & net salary, where dearnessallowance is 40% of the basic salary or 10,000 whichever is less, house rent allowance is30% of the basic salary or 3000 whichever is more, provident fund is 8.33% of the basicsalary. Net salary = basic salary + dearness allowance + house rent allowance provident fund. Print Name, basic salary & net salary.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    15/42

    15

    Comma operator: -There can be more than one initialization, condition and increment in a for statement. If there are morethan one initialization, condition and increment they should be separated by a comma. This is known ascomma operator.

    For example: 1) { int a,b;for(a=2,b=4;b

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    16/42

    16

    Sorting1. To input 10 number and arrange the numbers in ascending and print 5 number in one line.

    /*ascending order*/#includemain()

    {int x[10],i, j, t;for(i=0;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    17/42

    17

    Switch StatementC 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 statements1. The expressionvaluemust be an integer, hence the type can be integer.2.caseshould always be followed by an integer constant or expression.3. All the casesshould 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 */#includemain()

    {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; }}

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    18/42

    18

    PROBLEMS ON SWITCH STATEMENT1. 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 whereGrade BonusA 50% of Basic

    B 60% of BasicC 70% of BasicRest 80% of Basic

    2. Write a program to enter vowel character from keyboard, depending on the response if it is avowel 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 whohave committed parking violations

    No of violations action1 or 2 polite warning letter3 strong warning letter4 or 5 Collect Fine.6 or more revoke license.

    4. Input worker number, category, and hours worked. Calculate and print the wages. Using switchstatement calculate wages as follows

    Category 1 2 3 4Rate per hour 100 80 60 35.75

    5. Input month number, using switch display a message as : summer if month is >=2 but =6 but

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    19/42

    19

    break StatementExecution 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 breakis executed is terminated.

    Storage ClassesAll variables have data types and the storage classes. There are basically two kinds of location in ascomputer where the contents of the variable are stored: Memory and CPU registers. It is the variablestorage class which determines in which of these two locations the value is stored. Also the storage classgives us the idea about

    1.Wherethe variablewould be stored i.e. in theMainMemory or CPUregister.2.What will be the initialvalue of the variable, either Garbage or Zero.3. What is the scopeofthevariable i.e., in which functions the value of the variable

    isavailable?

    4. What is thelifeofthevariable?There are 4 storage classes auto, register, static,&extern.

    Revision and Tests is the

    Secret of getting100 marks.

    Variables Auto register static extern

    Location Memory CPU register Memory Memory

    Initial value Garbage Garbage Zero Zero

    Scope Local to blockLocal to block

    Local to block Global

    LifeTill control remains

    in the block

    Till controlremains in the

    blockValue persist

    As long asprogram ends

    How todefine

    auto int i; or int i; register int i; static int i; extern int i;

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    20/42

    20

    FFoorrmmaatt OOuuttppuutt

    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-403344125^-40^3344

    %d is called conversion specification. It is a conversionspecification for integer type data. One can also specify width alongwith %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 beprinted before the number. If the number is positive plus sign isprinted 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 numbermust 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 the number must be leftjustified & 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 fieldspecified 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.

    Integer and float type of data are rightjustified by default.

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    21/42

    21

    7) main(){int x=1234;printf(%06d %-06d\n,x,x); }

    001234^1234^^

    8) 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.7777004.556000-876.543200888.777700

    %f always prints 6 digits after the decimal. To control number ofdigits use the format %.df where d stands for no. of places afterdecimal.

    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 placesduring 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 numberrespectively.

    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.784.56^^^-876.543^^^^^888.7777^^^^^^^+5^^^^-876.5^^^+888.78^^^^^

    If the size of the number is larger than the width specified thenwidth is ignored and the number is printed as it is. But the decimalpart 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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    22/42

    22

    Printing character type data:%c is used as conversion specification to print the character typedata.

    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, wstands for total width and d for the number of characters to beprinted.

    14) #includemain(){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^^^^^^^^^^^DipaDipawali^^^^^^^Dipa^^^^^^^^^^^Dipawali

    15) #includemain(){ 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*^^^

    Character and string type ofdata are always right justifiedby default

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    23/42

    23

    - : Find the output: -1. #include

    main(){int x=2,y=2;while(x

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    24/42

    24

    16. main(){int x,y;for(x=5,y=3;y

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    25/42

    25

    C-theory (6 to 8 marks)Data TypesData types are used to define the type of the variables used in a program in the beginning of aprogram. 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 usersand 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 qualifersEach data type may have various type modifiers preceding them. A type modifier is used tochange the meaning of basic data types to fit the needs of the various situations. The typemodifiers 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 OperatorAt times we need to force an expression to be ofspecific 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 Specificationis 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(): 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 typed character 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\0 End of string Null\n End of a line Moves active position to initial position of next line.

    \t Horizontal tab Moves active position to the next horizontal position\b Back space Moves active position toprevious position on current line

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    26/42

    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 printfputs():

    It allows to print only string data on a new line. It generates line feed automatically.

    C preprocessorThe C preprocessor is a program that processes our source program before it is passed on tothe compiler. The processor commands are known as directives. Each of these directives beginwith # symbol & can be placed anywhere in program, but are generally placed at the beginningof the program before the main() function. They include macro definition(# define) and fileinclusion(# include).

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

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

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

    where the function should always return some value.

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

    return StatementThis is used in functions to return a value to the calling function. Every function subprogram canend with return.

    switch StatementC switch is a multi-directional conditional statement through which the control flow can betransferred in multi directions.

    continue StatementThe continue statement is to bypass the remainder of current pass through a loop. Thus the loopdoes not terminate ifcontinue statement is encountered.

    break StatementExecution of break statement causes the program to immediately exit from the loop it isexecuting, whether its for, while or do loop.

    Storage ClassesAll variables have data types and the storage classes. There are basically two kinds of location inas computer where the contents of the variable are stored: Memory and CPU registers. It is thevariable storage class which determines in which of these two location the value is stored. Thereare 4 storage classes auto, register, static & extern.

    Variables Automatic Register Static External

    Location Memory CPU register Memory Memory

    Intial value Garbage Garbage Zero Zero

    Scope Local toblock

    Local toblock

    Local toblock

    Global

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    27/42

    27

    Difference between:

    gets() scanf() gets()is an input statement which iscapable of accepting multiword strings.

    can accept only string data scanf is a input statement which is notcapable accepting multiword strings

    Can accept all types of data such as integer,floating point, character and string.Printf() puts()

    Does not generate line feed automatically.e.g.; printf(GOOD);

    printf(DAY);output: GOODDAY

    Can display all types of data such asinteger floating point, character and string. Printf is an formatted output statement

    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() getch()/getche()/getchar() scanf can input all types of data i.e. integerfloating point, and character data

    getch() or getchar() or getch() accepts onlycharacter data.

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

    putch() or putchar() will print onlycharacter data. putch()/putchar() is an unformatted outputstatement.

    while loop do- while loop The while loop is an entry controlled loopi.e., it evaluates the condition in thebeginning of the loop and if the conditionis false in the beginning, the loop is neverexecuted

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

    Break Continue break statement causes an immediate exitfrom the loop structure. It can also be usedalong with the switch statement to terminatethe switchstatement.

    continue statement bypasses the remainingstatements of the loop and forces the nextrepetition of the loop to take place.

    Switch If C switch is a multi-directionalconditionalstatement through which thecontrol flow can be transferred in multidirections.

    if is a transfer control statement, meant totransfer the computer control from onestatement to another depending on thesatisfaction of a given condition

    In switch statement, value of the variableis checked.

    In if statement, the condition is checked. In switch statement, only one value orvariable can be checked.

    In if statement, more than one conditioncan be checked.

    While IfWhile() is a looping statement where thecondition is check first and then actions are

    carried out repeatedly

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

    =(assign) == (equal to) = is a assignmentoperator which assignthe value to an identifier or variable

    = = is relationaloperator which is used tocheck equality

    %c %s

    %c is conversion specification (controlstring) data item is displayed a singlecharacter.

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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    28/42

    28

    Solutions for Simple Program (page number 8)

    1) /*sum of two number*/#includemain()

    {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;}

    2) /*average of 3 numbers*/#includemain(){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;}

    3) /*area and circumference*/#include#includemain(){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;}

    4) /*area and perimeter*/#includemain(){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;}

    5) /*amount in rupees*/#includemain(){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;}

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    29/42

    29

    6) /*total time in seconds*/#includemain(){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;}

    7) /*sales and commission*/#includemain(){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;}

    8) /*sales and discount*/#includemain(){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;}

    9) /*compound interest*/#include#includemain(){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;}

    10) /*corresponding height in cms*/#includemain(){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;}

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    30/42

    30

    Solutions for If Statement Program (page number 9)1) /*sales and commission*/

    #includemain(){int sno;

    float as, comm;char n[20];

    printf(enter salesman number, name and sales);scanf(%d %s %f, &sno, n, &as);

    if(as1000 && as3000 && as20000)

    comm=as*0.12;else

    comm=as*0.10;printf(sales=%.2f\n, as);printf(commission=%.2f\n, comm);return 0;}

    3) /*sales and commission*/#includemain(){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;}

    4) /*custom duty*/#include

    main(){

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    31/42

    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;elseif(cno==2)

    cd=vg*0.155;elseif(cno==3)

    c=vg*0.25;elsec=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*/#includemain(){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);

    elseprintf(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*/#includemain(){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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    32/42

    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*/#includemain(){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*/#includemain()

    {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;}

    9) /*vowel*/#includemain(){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;}

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    33/42

    33

    10) /*income tax*/#includemain(){char n[20];float in, tax ,net;

    printf(enter name and income);scanf(%s %f, n, &in);

    if(in110000 && in240000 && in

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    34/42

    34

    Solutions for Loops Program (page number 11)1) /*sum of two number*/

    #includemain(){

    float a, b, s, i;for(i=1;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    35/42

    35

    main(){float s=0,i;for(i=1;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    36/42

    36

    main(){float s=0,i;for(i=1;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    37/42

    37

    15)/*sum of series*/#includemain(){float i, s=0;

    for(i=1;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    38/42

    38

    s=s+i*pow(x,j)/(i+1);}printf(sum of series=%.2f\n,s);return 0;}

    20)/*sum of series*/#includemain(){float i, j, s=0;for(i=2,j=5;i

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    39/42

    39

    dep=val*r/100;val=val-dep;printf(%.2f\t\t%.2f\n, dep, val);}return 0;}

    24)/*compound interest*/#include#includemain(){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

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    40/42

    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*/#includemain(){char en[20];float bs, da, hra, pf, ns, i;for(i=1; i10000)da=10000;

    hra=bs*0.30;if(hra

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    41/42

    41

    Solutions for Switch Statement (page number 16)

    1) /*bonus*/#includemain()

    {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;}

    3. /*traffic police */#includemain(){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;}

    2 /*vowel*/#includemain(){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;}

    4. /*wages*/#includemain(){

    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;}

  • 8/2/2019 C Program Lakhani Notes (Program With Soln + Objectives)

    42/42

    42

    5. /*seasons*/#includemain(){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;}

    7. /*alphabet*/#includemain(){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;}

    6. /*message*/#includemain(){

    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;

    }