CS 101-LM

Post on 06-Apr-2018

215 views 0 download

Transcript of CS 101-LM

  • 8/2/2019 CS 101-LM

    1/63

    SIR PADAMPAT SINGHANIA UNIVERSITY

    Udaipur(Rajasthan)

    SCHOOL OF ENGINEERING

    Lab Manual

    Of

    Introduction to Computers and

    Programming

    Program : B. Tech. Semester : I Semester

    Session : 2010-11 Subject Code : CS 101

    Subject Name : Introduction to Computers & Programming

    Credits : 3 (L) + 0 (T) + 1 (P) = 4

    Faculty : Mr. Arun Kumar.

    Mr. Ashutosh Gupta.

    Mr. Harish Tiwari.

    Mr. Sandeep Chaurasia

  • 8/2/2019 CS 101-LM

    2/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 2

    Mr. Arjun Singh

    DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

    TABLE OF CONTENTS

    CHAPTER 1 INTRODUCTION ............................................................................... 8

    1.1. OBJECTIVE: ..............................................................................................................................................................81.2. STEPSOFDEVELOPING,COMPILINGANDRUNNINGCPROGRAM .....................................................91.3. PRINTF()FUNCTION. ................................................................................................................................................91.4. SCANF()FUNCTION................................................................................................................................................121.5. PROGRAMLIST ..................................................................................................................................................14

    CHAPTER 2 IDENTIFIERS, KEYWORDS, OPERATORS, DATA TYPES ......... 15

    2.1. NAMING RULES FOR IDENTIFIERS ..........................................................................................................................152.2. KEYWORDS .............................................................................................................................................................152.3. C'S OPERATORS.....................................................................................................................................................152.4.

    C'S DATA TYPES ....................................................................................................................................................16

    2.5. EXPRESSIONS....................................................................................................................................................182.6. PROGRAMLIST ..................................................................................................................................................20

    CHAPTER 3 DECISION MAKING STATEMENT................................................. 21

    3.1. STATEMENTS AND BLOCKS ...................................................................................................................................213.2. IF-ELSE STATEMENT ..............................................................................................................................................213.3. ELSE-IF(LADDER ELSE IF)......................................................................................................................................223.4. PROGRAM LIST.......................................................................................................................................................23

    CHAPTER 4 ITERATION STATEMENTS ............................................................ 25

    4.1. WHILE LOOP ............................................................................................................................................................254.2. DO-WHILE LOOP ......................................................................................................................................................264.3. FOR LOOP: ..............................................................................................................................................................264.4. PROGRAMLIST ..................................................................................................................................................27

    CHAPTER 5 MULTI WAY DECISION MAKING STATEMENT BASEDPROGRAMS ................................................................................................................. 29

    5.1. INTRODUCTION .......................................................................................................................................................295.2. PROGRAMLIST ..................................................................................................................................................32

    CHAPTER 6 ARRAY ............................................................................................ 33

  • 8/2/2019 CS 101-LM

    3/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 3

    6.1. INTRODUCTION: ......................................................................................................................................................336.2. TYPES OF ARRAY ...................................................................................................................................................336.3. PROGRAMLIST ..................................................................................................................................................40

    CHAPTER 7 STRINGS......................................................................................... 42

    7.1. INITIALIZATION OF STRINGS....................................................................................................................................427.2. READING AND WRITING STRINGS: .........................................................................................................................427.3. STRING HANDLING FUNCTIONS: ............................................................................................................................437.4. PROGRAM LIST .......................................................................................................................................................43

    CHAPTER 8 FUNCTION....................................................................................... 44

    8.1. DEFINITION .............................................................................................................................................................448.2. NEED OF FUNCTION : .............................................................................................................................................448.3. FUNCTION DECLARATION: .....................................................................................................................................448.4. HOW A FUNCTION WORKS .....................................................................................................................................448.5. DECLARATION VERSUS DEFINITION ......................................................................................................................458.6. SPECIFYING RETURN TYPES..................................................................................................................................458.7. LOCAL AND GLOBAL VARIABLES ..........................................................................................................................458.8. MAKING FUNCTION CALLS.....................................................................................................................................458.9. RECURSION ............................................................................................................................................................468.10. PASSING ARGUMENTS TO A FUNCTION..................................................................................................................478.11. PROGRAM LIST: .....................................................................................................................................................48

    CHAPTER 9 STRUCTURE AND UNION ..................................................................

    9.1. DEFINITION OF STRUCTURE: ..................................................................................................................................499.2. DECLARATION OF STRUCTURE: .............................................................................................................................499.3. DECLARATION OF STRUCTURE VARIABLE:............................................................................................................509.4. ACCESSING STRUCTURE ELEMENT.......................................................................................................................509.5. POINTS TO BE REMEMBER: ....................................................................................................................................519.6. DEFINITION OF UNION :..........................................................................................................................................529.7. DECLARATION OF UNION: ......................................................................................................................................529.8. DIFFERENCES BETWEEN STRUCTURE AND UNION :...............................................................................................539.9. PROGRAM LIST.......................................................................................................................................................54

    CHAPTER 10 POINTERS BASED PROGRAMS.................................................. 55

    10.1. DEFINITION AND CONCEPT OF POINTER: ................................................................................................ 5510.2. DECLARATION OF POINTER: ................................................................................................................. 55

    10.2.1 SYNTAX:.... ...................... ......................... ......................... ...................... ......................... .... 5510.2.2 EXAMPLE :.................... ......................... ...................... ......................... ......................... ....... 55

    10.3. INITIALIZATION OF POINTER : ................................................................................................................ 5510.3.1 EXAMPLE :.................... ......................... ...................... ......................... ......................... ....... 56

    10.4. POINTERS AND ARRAYS ........................ ........................ ....................... ......................... ....................... 5610.5. POINTER TO POINTER.............. ......................... ......................... ......................... ...................... ............ 5610.6. VOID POINTERS ...................... ......................... ......................... ......................... ...................... ............ 56

  • 8/2/2019 CS 101-LM

    4/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 4

    10.7. POINTERS AND FUNCTIONS...................... ......................... ......................... ...................... ..................... 5710.8. POINTERS AND STRUCTURES ......................... ...................... ......................... ......................... ............... 5710.9. PROGRAM LIST ...................... ......................... ......................... ......................... ...................... ............ 57

    CHAPTER 11 FILE HANDLING BASED PROGRAMS ......................................... 5811.1. INTRODUCTION: ......................... ......................... ...................... ......................... ......................... ....... 5811.2. FILE OPERATIONS :....................... ......................... ......................... ...................... ......................... .... 58

    11.2.1 OPENINGOFAFILE...................... ......................... ......................... ...................... ............ 5811.2.2 FILEMODES:.... ......................... ...................... ......................... ......................... ............... 5811.2.3 CLOSINGAFILE........................ ...................... ......................... ......................... ............... 59

    11.3. PROGRAM LIST: ............................................................................................................................... 59

  • 8/2/2019 CS 101-LM

    5/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 5

    1. AIM:Main aim of this course is to understand and solve logical & mathematical problems through C language.Strengthen knowledge of a procedural programming language. Design and develop solutions to intermediate levelproblems using the C language. Further develop your skills in software development using a procedural language.

    2. ASSESSMENT CRITERIA:

    Total marks : 50Internal Assessment*

    External Assessment#

    * In the internal assessment student have to perform all programs and have to prepare lab record. In the lab recordstudent will need to write program in prescribed format. During the whole semester student will be evaluated forhis/her performance. At the end of the session faculty -will conduct a internal lab exam to evaluate the studentprogress.# in the end term external examination faculty will conduct lab exam for the assessment the student knowledgeabout the subject.

    3. LAB OBJECTIVE

    1) Introduction to general programming terms learning how to develop program and how to transfer ourlogic to any programming language.

    2) To gain practical experience with the C programming language.

    3) To teach the student to write programs in C solve the problems

    4) To gain some understanding of the principles of good program design and program testing.

    5) To gain some experience of the Microsoft Visual Studio for developing C programs.

  • 8/2/2019 CS 101-LM

    6/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 6

    4. GUIDELINES TO STUDENTS:

    1 Equipment in the lab for the use of student community. Students need to maintain a proper decorum in thecomputer lab. Students must use the equipment with care. Any damage caused is punishable.

    2 Students are required to carry their observation / programs book with completed exercises while enteringthe lab.

    3 Students are supposed to occupy the machines allotted to them and are not supposed to talk or make

    noise in the lab. The allocation is put up on the lab notice board.

    4 Lab can be used in free time / lunch hours by the students who need to use the systems should take priorpermission from the lab in-charge.

    5 Lab records need to be submitted on or before date of submission.

    6 Students are not supposed to use pen drives/CDs

    5. FORMAT OF INDEX

    S.No.Aim Of the

    program

    Date of

    Performance

    Date Of

    SubmissionRemark Signature

    write complete

    aim of the

    program that

    student has

    written in the

    aimm section in

    every program

    DD/MM/YYYY DD/MM/YYYY

    Here faculty will write

    some

    remark/grade/comment/etc.

    Signature of the

    faculty

  • 8/2/2019 CS 101-LM

    7/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 7

    6. HOW TO WRITE PROGRAM IN THE LAB RECORD

    Student will need to write program in following format.

    1. Aim: write the complete aim of the program to be developed.

    2. Software Used: what types of different software used to develop this program

    a. IDE/Compiler :

    b. Operating System :

    3. Source Code: write complete source code with name of the file in the middle of the sheet and program

    should be written in proper indentation.

    4. Output: write the compete output with set of input entered by user during execution.

    For example:

    1. Aim : write a program in C to display Hello World on to the computer

    Screen

    2. Software Used :

    a. IDE/Compiler : Microsoft Visual Studio 6.0

    b. Operating System : Windows Xp

    3. Source Code :

    Hello.c

    #include

    void main( )

    {

    printf(Hello World)

    }

  • 8/2/2019 CS 101-LM

    8/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 8

    4. Output

    Hello World

    Chapter 1 Introduction

    1.1. Objective:

    Objective of this module is to make simple programs using C language and to developing, editing, compiling andrunning C programs. In this module student are supposed to make very simple program to getting different types ofinputs and displaying them on to the monitor using various escape sequences and formatting tags.

    The simple steps to find a solution to problems are the same steps used to write a program and basically can bedefined as follows:

    1. Define the problem.2. Devise a plan to solve it.3. Implement the plan.4. Test the result to see whether the problem is solved.

    When creating a program in C:1. Determine the objective(s) of the program.2. Decide which method the program will use to solve the problem.3. Translate this method into a computer program using the C/C++ language.4. Run and test the program.

  • 8/2/2019 CS 101-LM

    9/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 9

    1.2. STEPS OF DEVELOPING, COMPILING AND RUNNING C PROGRAM

    1. Most of the editor used nowadays called Integrated Development Environment (IDE) that combines theprocess of compiling, linking, running, debugging, code validation, standard conformance and otherfunctionalities in one environment such as Microsoft Visual Studio.

    2. After developing program in editor, save this program (source code) with .c file extension. And then useIDE to compile and run the program.

    3. If there is any error, during the process of compilation, IDE will inform you about the error. Remove that

    error and again compile the source code and observe the output.4. The program start with what is called preprocessor directive, #include.5. Then the main program start, with keyword main(), each program must have a main() function.6. All the coding is included in the body of the main program in the opening and closing curly braces.7. Be familiar with the writing codes, compiling, running and your IDE programming environment.8. Your task is to write the source code, compile and run. Notice that you only have to change some of the

    codes in the curly braces { } and adding or deleting the preprocessor directive to complete all objectives.9. Learn how to modify the program source code and re run the program. You will learn a lot more things!

    1.3. printf( ) Function.

    To get started, use %hi to display a short, %i for an int, %li for a long, %G for a float ordouble, %LG for along double, %c for a char(or%i to display it as a number), and %s for a string (char * orchar []). Thenrefine the formatting further as desired.To print a percent sign, use %%.

    1.3.1 Prototypes ( in )

    int printf(const char *format, ...)

    The functions return the number of characters written, or a negative value if an error occurred.

  • 8/2/2019 CS 101-LM

    10/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 10

    1.3.2 Format String:

    The format string is of the form

    % [flags] [field_width] [.precision] [length_modifier] conversion_character

    where components in brackets [] are optional. The minimum is therefore a % and a conversion character(e.g. %i).

    1.3.3 Flags

    These can be in any order.

    Flag Meaning

    - The output is left justified in its field, not right justified (the default).

    + Signed numbers will always be printed with a leading sign (+ or-).

    space Positive numbers are preceded by a space (negative numbers by a - sign).

    0 For numeric conversions, pad with leading zeros to the field width.

    1.3.4 Field width

    The converted argument will be printed in a field at least this wide, and wider if necessary. If the convertedargument has fewer characters than the field width, it will be padded on the left (or right, if left adjustmenthas been requested) to make up the field width. The padding character is normally ' ' (space), but is '0' ifthe zero padding flag (0) is present.

    1.3.5 Precision

    A dot '.' separates the field width from the precision.If the precision is specified as *, the value is computedfrom the next argument, which must be an int.

    Conversion Meaning

    S The maximum number of characters to be printed from the string.

  • 8/2/2019 CS 101-LM

    11/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 11

    e, E, f The number of digits to be printed after the decimal point.

    G, G The number of significant digits.

    d, i, o, u, x,X

    The minimum number of digits to be printed. Leading zeros will be added to make up thefield width.

    1.3.6 Length modifier

    Character Meaning

    H The value is to be displayed as a short orunsigned short.

    L Ford, I, o, u, x orX conversions: the argument is a long, not an int.

    L Fore, f, g orG conversions: the argument is a long double.

    1.3.7 Conversion character

    Character Meaning

    D, i Display an int in signed decimal notation.

    O Display an int in unsigned octal notation (without a leading 0).

    u Display an int in unsigned decimal notation.

    X, XDisplay an int in unsigned hexadecimal notation (without a leading 0x or 0X). x gives lower

    case output, X upper case.

    C Display a single char (after conversion to unsigned int).

    E, EDisplay a double or float (after conversion to double) in scientific notation. e gives lower caseoutput, E upper case.

    F Display a double or float (after conversion to double) in decimal notation.

  • 8/2/2019 CS 101-LM

    12/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 12

    G, Gg is either e or f, chosen automatically depending on the size of the value and the precisionspecified. G is similar, but is either E or f.

    N Nothing is displayed. The corresponding argument must be a pointer to an int variable. Thenumber of characters converted so far is assigned to this variable.

    SDisplay a string. The argument is a pointer to char. Characters are displayed until a '\0' isencountered, or until the number of characters indicated by the precision have beendisplayed. (The terminating '\0' is not output.)

    P Display a pointer (to any type). The representation is implementation dependent.

    % Display the % character.

    1.4. scanf( ) Function

    To get started, use %hi to input a short, %i for an int, %li for a long, %ffor a float, %lffor a double, %Lffor a long double, %c for a char(or%i to input it as a number) or%s for a string (char * orchar []). Then refinethe formatting further as desired.

    An extremely common error is to forget that the arguments must be pointers! So ifx is a float, the correctcall is scanf("%f", &x); (because &x is of type float *), not scanf("%f", x);.

    For ease of debugging: if you want to input multiple values from the keyboard, do so one at a time. Eachtime output a suitable prompt, and then calls scanfto input a single value.

    1.4.1 Prototypes ( )

    int scanf(const char *format, ...)

    The functions return the number of input values converted and assigned, or 'EOF' if the end of file isreached or an error occurs before any conversion.

    1.4.2 Format string

    The format string tells scanf how to interpret the input. It may contain:

    Spaces and tabs, which are ignored but can be included for readability. Ordinary characters which are matched against non-whitespace characters in the input. (Whitespace

    characters are space ' ', tab '\t', newline '\n', carriage return '\r', vertical tab '\v' and formfeed '\f'.Allothers are non-whitespace. The '%'character is a special case; see below.)

    One or more conversion specifications, each of the form

    % [*] [field_width] [length_modifier] conversion_character

    where components in brackets [ ] are optional. The minimum is therefore a % and a conversioncharacter (e.g. %i). There is generally one conversion specification for each variable. The conversion

  • 8/2/2019 CS 101-LM

    13/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 13

    process stops when the format string is exhausted or when an input fails to meet the conversionspecification.

    An input field is defined as a string of non-whitespace characters.

    1.4.3 Assignment suppression flag, *

    If the optional * flag is included, assignment is suppressed, i.e. the input field is converted according to thespecification, but not assigned to a variable. Otherwise the assignment is made to the correspondingargument, which must be a pointer to a variable of the appropriate type.

    1.4.4 Field width

    An input field (a sequence of non-whitespace characters) extends either to the next whitespace character

    or until the field width, if specified, is reached. (So scanf will read across line ends to find its input, becausenewlines are whitespace.)

    1.4.5 Length modifier

    Character Meaning

    H For d, I, o, u or x conversions, the value is to be input as a short, not an int.

    L

    For d, i, o, u or x conversions, the value is to be input as a long, not an int.

    For e, f or g conversions, the value is to be input as a double, not a float.

    L For e, f or g conversions, the value is to be input as a long double.

    1.4.6 Conversion character

    Character Meaning

    D Input a decimal integer; argument must be int *.

    IInput an integer; argument must be int *. The integer may be in octal(with a leading 0) or hexadecimal (with a leading 0x or 0X).

    OInput an octal integer (with or without a leading 0); argument must be int*.

    U Input an unsigned decimal integer; argument must be unsigned int *.

  • 8/2/2019 CS 101-LM

    14/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 14

    XInput a hexadecimal integer (with or without a leading 0x or 0X);argument must be int *.

    c

    Input one or more characters; argument must be char *. The charactersare put in the character array, up to the number given by the field width.(No terminating '\0' is added.) If a field width is given, whitespace is notskipped. If no field width is given, only one character is input. (To readthe next non-white space character, use %1s.)

    SInput a string of non-whitespace characters; the argument must be char*. A terminating '\0' is added.

    E, f, g

    Input a floating point number; argument must be float *. The inputformat is an optional sign, a string of numbers (possibly containing adecimal point), and an optional exponent field containing an E or efollowed by a (possibly signed) integer. So numbers to be input can bein either decimal or scientific notation.

    PInput a pointer value; argument must be void *. The representation isimplementation dependent and is as printed by printf("%p").

    NNo input is read. Instead, the argument receives the number ofcharacters read so far by this call; argument must be int *.

    [...]

    Inputs a string; argument must be char *. A terminating '\0' is added.Only the characters listed between the brackets are accepted. Inputends when a non-matching character is reached or the field width isreached. To accept the ']' character, list it first: []...]

    [^...]

    Inputs a string; argument must be char *. A terminating '\0' is added.Only characters not listed between the brackets are accepted. Inputends when a non-matching character is reached or the field width isreached. To reject the ']' character, list it first: [^]...]

    % Literal %: reads the '%' character. No assignment is made.

    1.5. PROGRAM LIST

    1. Write a program to print your name and some text lines and demonstrates various escape sequences (\n, \t, etc.)to format output.

  • 8/2/2019 CS 101-LM

    15/63

    Chapter 2 Identifiers, keywords, Operators, Data Types

    2.1. Naming Rules for Identifiers

    1. Identifiers may only include the following characters: letters ('a'..'z', 'A'..'Z'), digits ('0'..'9') and underscores('_'). C is case sensitive, so seaside, SeaSide and SEASIDE are distinct identifiers.

    2. The first character must not be a digit.3. The identifier must not be one of C's 32 keywords.

    2.2. Keywords

    auto break case charconst continue default do

    double else enum externfloat for goto ifint long register returnshort signed sizeof staticstruct switch typedef unionunsigned void volatile while

    2.3. C's Operators

    Precedencelevel

    Type OperatorsAssociativity

    direction

    1 Primary ( ) [ ] -> . ++ -- left-to-right

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

    3 Binary * / % left-to-right

    4 Binary + - left-to-right

    5 Binary > left-to-right

    6 Binary < >= left-to-right

    7 Binary ==!= left-to-right

    8 Binary & left-to-right

    9 Binary ^ left-to-right

    10 Binary | left-to-right

    11 Binary && left-to-right

    12 Binary || left-to-right

    13 Ternary ?: right-to-left

    14Binary = += -= *= /= %= &= ^= |= = right-to-left

    15 Binary , left-to-right

  • 8/2/2019 CS 101-LM

    16/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 16

    Notes:

    1. Operations with the highest precedence (level 1) are performed first, those with the lowest precedence(level 15) are performed last.

    2. All operators at the same level have equal precedence.3. For operators at the same level of precedence, the order in which operations are performed is determined

    by the direction of their associatively.4. A unary operator operates on a single object and is prefixed to it, e.g. &a5. A binary operator operates on two objects and is placed between them, e.g. a * b.6. The only ternary operator operates on three objects, viz. a ? b : c7. The postfix (primary) versions of ++ and -- have higher precedence than the prefix (unary) versions.8. The unary versions of +, -, * and & have higher precedence than the binary versions.

    2.4. C's Data Types

    C language is rich in data types. The fundamental data types which can be used in C are integer data types,character data types and floating point data types. Each of the data types and their corresponding keywords aregiven in the table below.

    Integer data type is used to represent an integer-valued number. Character data type represents one single

    alphabet or a single-digit integer. Each character type has an equivalent integer representation. Integer andcharacter data types can be augmented by the use of the data type qualifiers, short, long, signed and unsigned.Floating point data types are used to represent real numbers. Basic floating point data type offers six digits ofprecision. Double precision data type can be used to achieve a precision of 14 digits. To extend the precisionfurther more, we may use the extended double precision floating point data type.

    A schematic representation of the various data types in C is given below

    DATA TYPES KEYWORD

    Character char

    Unsigned Character unsigned char

    Signed Character signed char

    Signed Integer signed int (or int)

    Signed Short Integer signed short int (or short int or short)Signed Long Integer signed long int (or long int or long)

    Unsigned Integer unsigned int (or unsigned)

    Unsigned Short Integer unsigned short int (or unsigned short)

    Unsigned Long Integer unsigned long int (or unsigned long)

    Floating Point float

    Double Precision Floating Point double

    Extended Double Precision Floating Point long double

  • 8/2/2019 CS 101-LM

    17/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 17

    In the table below, the memory size required by each data type in bits and the range of values they canposses are listed.

    DATA TYPE SIZE in BITS RANGE

    char or signed char 8 -128 to 127.

    unsigned char 8 0 to 255.

    int or signed int 16 -32768 to 32767.unsigned int 16 0 to 65535.

    short int or signed short int 8 -128 to 127.

    unsigned short int 8 0 to 255.

    long int or signed long int 32 -2,147,483,648 to2,147,483,647.

    unsigned long int 32 0 to 4,294,967,295.

    float 32 3.4e-38 to 3.4e+38.

    double 64 1.7e-308 to 1.7e+308.

    long double 80 3.4e-4932 to

    3.4e+4932.

    The syntax of the declaration of variables using data type is:

    data-type vname-1, vname-2,..vname-n;

    where vname-1, vname-2, vname-n are variable names. Some examples for the variable declaration aregiven below.

    int number;char a;long double big-number;

  • 8/2/2019 CS 101-LM

    18/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 18

    2.5. EXPRESSIONS

    Expressions in C are classified according to the operators used in them. The classifications are

    Relational expression. Logical expression. Arithmetic expression.

    2.5.1 Relational Expression.An expression containing a relational operator is termed as relational expression. The list of all relationaloperators is given below

    OPERATOR MEANING

    < Is less than. Is greater than.

    >= Is greater than or equal to.

    == Is equal to.

    != Is not equal to.

    relational operator, the arithmetic expressions will be evaluated first and then the results are compared.

    2.5.2 Logical Expression.

    Logical expressions are the expressions where logical operators are used to combine more than onerelational expression. Logical expressions are also called compound relational expressions. The logicaloperators used in C are && (logical AND), || (logical OR), and ! (logical NOT). Logical expressions alsoyields a value of one or zero, and used in decision statements.

    Format of a logical expression:

    (rel-expression-1) logical operator (rel-expression-2)

    Where rel-expression-1 and rel-expression-2 are relational expressions.

    2.5.3 Arithmetic Expressions

    An expression is a combination of variables constants and operators written according to the syntax of Clanguage. In C every expression evaluates to a value i.e., every expression results in some value of acertain type that can be assigned to a variable. Some examples of C expressions are shown in the tablegiven.

  • 8/2/2019 CS 101-LM

    19/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 19

    Algebraic Expression

    C Expression

    a x b c a * b c

    (m + n) (x + y) (m + n) * (x + y)

    (a x b / c) a * b / c

    3x2

    +2x + 13*x*x+2*x+1

    (x / y) + c x / y + c

    2.5.3.1 Evaluation of Expressions

    Expressions are evaluated using an assignment statement of the form

    Variable = expression;

    Variable is any valid C variable name. When the statement is encountered, the expression is evaluated firstand then replaces the previous value of the variable on the left hand side. All variables used in theexpression must be assigned values before evaluation is attempted.

    Example : x = a * b c; y = b / c * a; z = a b / c + d;

    2.5.3.2 Precedence in Arithmetic Operators

    An arithmetic expression without parenthesis will be evaluated from left to right using the rules ofprecedence of operators. There are two distinct priority levels of arithmetic operators in C.

    High priority : * / %

    Low priority : + -2.5.3.3 Rules for evaluation of expression

    First parenthesized sub expression left to right are evaluated. If parentheses are nested, the evaluation begins with the innermost sub expression.

    The precedence rule is applied in determining the order of application of operators in evaluatingsub expressions.

    The associability rule is applied when two or more operators of the same precedence level appearin the sub expression.

    Arithmetic expressions are evaluated from left to right using the rules of precedence.

    When Parenthesis are used, the expressions within parenthesis assume highest priority.

  • 8/2/2019 CS 101-LM

    20/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 20

    2.6. PROGRAM LIST

    1. Write a program that receives radius of the circle as the input from the keyboard and find out area andcircumference as output.

    2. Write a program in c to find out the simple interest and compound interest when principle, rate of interestand time is input through the keyboard.

    3. Write a program in C to convert temperature from Celsius to Fahrenheit and vice versa.

    4. Write a program in C to compute the salary slip of a person, when basic salary of the person is enteredby the user, and HRA is 40% of Basic Salary, DA is 20% of Basic Salary. Program should generateoutput with all salary components.

    5. Write a program to convert Kilometer to Meters, Centimeters, and Millimeters.

    6. Write a program to convert Hours to Minutes and Seconds.

    7. Write a program to convert given number of days into equivalent weeks, months, and years.

    8. Write a program in C to SWAP the values of two variables with each other with the help of third variable.

    9. Write a program in C to SWAP the values of two variables with each other without the help of thirdvariable.

  • 8/2/2019 CS 101-LM

    21/63

    Chapter 3 Decision making Statement

    The control-flow of a language specifies the order in which computations are performed. We have already met themost common control-flow constructions in earlier examples; here we will complete the set, and be more preciseabout the ones discussed before.

    3.1. Statements and Blocks

    An expression such as x = 0 ori++or printf(...) becomes a statement when it is followed by a semicolon, as in

    x = 0;i++;

    printf(...);

    In C, the semicolon is a statement terminator. Braces { and } are used to group declarations and statements

    together into a compoundstatement, orblock, so that they are syntactically equivalent to a single statement. Thebraces that surround the statements of a function are one obvious example; braces around multiple statementsafter an if, else, while, or for. There is no semicolon after the right brace that ends a block.

    3.2. If-Else Statement

    The if-else statement is used to express decisions. The if statement is used to conditionally execute a block of codebased on whether a test condition is true. If the condition is true the block of code is executed, otherwise it isskipped.

    3.2.1 Syntaxif (expression)

    true_statement();

    else

    false_statement();

    3.2.2 Program Flow

    1. First, the boolean expression condition is evaluated.

    2. Ifcondition evaluates to true, the true_statement(s) are executed.

    3. Ifcondition evaluates to false and an else clause exists, the false_statement(s) are executed.

    4. Flow exits the if-else structure.

    where the else part is optional. Since an if tests the numeric value of an expression, certain codingshortcuts are possible. The most obvious is writing.

    if (expression)

    instead ofif (expression != 0)

    Sometimes this is natural and clear; at other times it can be cryptic. Because the else part of an if-else isoptional, there is an ambiguity when an else if omitted from a nested if sequence. This is resolved byassociating the else with the closest previous else-less if. For example, in

    if (n > 0)

    if (a > b)

    z = a;

  • 8/2/2019 CS 101-LM

    22/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 22

    else

    z = b;

    the else goes to the inner if, as we have shown by indentation. If that isn't what you want, braces must beused to force the proper association:

    if (n > 0)

    {

    if (a > b)

    z = a;

    }

    else

    z = b;

    3.2.3 Example

    #include int main(void){

    int number = 75; int mark;printf("Your examination mark\n");printf("Enter your score, please\n");scanf("%d",&mark);if (mark >= number){printf("Incredible, you passed with a merit\n");}return 0;

    }

    3.2.4 COMMON ERRORS

    Make sure that if you want to test equality in the condition to use the boolean operator == and not theassignment operator =. Consider the following bad piece of code.

    double x=0;if(x=1){System.out.println("x is 0");}else{

    System.out.println("x is not 0. x is "+x);}

    The output will be

    x is not 0. x is 1 //since x is assigned to 1 in the condition.

    3.3. Else-If(Ladder else if)

    The construction of ladder else-if is as follows

  • 8/2/2019 CS 101-LM

    23/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 23

    if (expression)statement

    else if (expression)statement

    else if (expression)

    statementelse if (expression)

    statementelse

    statement

    This sequence of if statements is the most general way of writing a multi-way decision. The expressions areevaluated in order; if an expression is true, the statementassociated with it is executed, and this terminatesthe whole chain. As always, the code for each statementis either a single statement, or a group of them inbraces. The last else part handles the none of the above or default case where none of the otherconditions is satisfied.

    3.4. Program List

    1. Write a program in C to find out whether a given number is Even or Odd. (Demonstration of if Block).

    2. Write a program in C to find out whether a given number is Positive or Negative Number or Zero.(Demonstration of if Block).

    3. Write a program in C that receives 2 integer numbers from the keyboard and find out greater betweenthese two numbers.(Demonstration of if Block).

    4. Write a program in C that receives year as the input through the keyboard and find out whether a year isleap or not. (Demonstration of if- else Block).

    5. Write a program in C that receives 2 integer numbers from the keyboard and find out addition of 2numbers if first number is greater than second number otherwise perform subtraction of 2numbers.(Demonstration of if- else Block).

    6. Write a program in C that receives 3 integer numbers from the keyboard and find out greatest amongthese three numbers. (Demonstration of nested if-else Block).

    7. Write a program in C to read four integer values from the keyboard and evaluate the ration of a+b and c-d and print the result when (c-d)!=0

    8. Write a program in C to calculate the Gross salary of a employee if basic salary is entered through thekey board. if the basic salary is less than 1500 rupees, then HRA is 10% of basic salary and DA is 90% ofBasic salary. But if Basic salary is equals or above the 1500 rupees then HRA is 500 rupees and DA is98% of Basic salary. Output should contain all components like Basic salary, HRA, DA and Gross salary.

    9. Write a program in C to print the division obtained by a student where marks obtained by a student in 6different subjects are entered by the user. A student gets division as per following rules.

    Percentage >= 60% then First division.

    Percentage >49% and

  • 8/2/2019 CS 101-LM

    24/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 24

    Percentage > 40% and

  • 8/2/2019 CS 101-LM

    25/63

    Chapter 4 Iteration Statements

    Iteration statements specify looping. These statements are used to repeat certain statement(s) until condition istrue. So instead of writing same statement again and again to be executed, programmer can write that statement tobe repeated as the part of loop body. C language provides 3 iteration statements that are as follows:

    1. while loop.2. do- while loop.3. for loop.

    In the while and do statements, the sub-statement is executed repeatedly so long as the value of the expressionremains unequal to 0; the expression must have arithmetic or pointer type.

    4.1. while loop

    The simplest of all the c looping structures in C is the while statement . The while statement is an entry -controlled loop statement. The test condition is evaluated and if the condition is true then the body of theloop is executed. After the execution of the body the test condition is once again evaluated and if it is true,the body is executed once again. This process of repeated execution of the body is continued until the testcondition becomes false and the control is transferred out of the loop. On exit the program is continued withthe statement after the body of the loop. The body of the loop may have one or more statements. Thebraces are needed only if the body contains two or more statements.

    4.1.1 SYNTAX

    initialization of loop counter

    while (test condition){Statement(s); //body of the loop

    //Alteration of loop counter}

    4.1.2 PROGRAM FLOW

    1. First initialization of loop counter takes place. Declaration of loop counter is typically done when wedeclare all necessary variables at the beginning of the program in main( ) function. But we can initializethe loop counter wherever we need, like int i=0;

    2. The Boolean expression test is then evaluated. This is typically something like i

  • 8/2/2019 CS 101-LM

    26/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 26

    main(){int count,n; //n is the power and count is the loop counter.float x,y; // x is the base and y is the result

    printf(Enter the values of x and n:);scanf(%f %d, &x, &n);y= 1.0;count = 1; //loop counter initialization

    /* LOOP BEGINS*/while(count

  • 8/2/2019 CS 101-LM

    27/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 27

    initialization for the loop. There is no restriction on its type. The second expression must have arithmetic or pointertype; it is evaluated before each iteration, and if it becomes equal to 0, the for is terminated. The third expression isevaluated after each iteration, and thus specifies a re- initialization for the loop. If we want to execute only singlestatement as the part of loop body then pair of curly brackets can be omitted.

    4.3.1 SYNTAXfor (initialization; test; increment){statements; //Body of the loop}

    OR

    for (initialization; test; increment)statement;

    4.3.2 PROGRAM FLOW

    1. The initialization is first executed. This is typically something like int i=0, which creates a newvariable with initial value 0, to act as a counter. Variables that you declare in this part of the for loopcease to exist after the execution of the loop is completed. Multiple, comma separated,expressions are allowed in the initialization section. But declaration expressions may not be mixedwith other expressions.

    2. The Boolean expression test is then evaluated. This is typically something like i

  • 8/2/2019 CS 101-LM

    28/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 28

    14.Write a program in C to print your name given number of times on to the monitor Using for loop , do while loop and while loop. (Demonstration of Loops).

    15.Write a program in C to print numbers from 1-50 in ascending order and descending order all loops types

    in C languages. (Forward loop and backward loop Demonstration).

    16.Write a program that receives height of 10 students of CSE A, and find out the average height of allstudents using loop.

    17.Write a program in C to print the table of a number where number is entered by user in following formatusing all loops( for loop, do-while loop and while loop);

    2 X 1 = 2

    2 X 2 = 4

    2 X 3 = 6

    ..

    ..

    2 X 10 = 20

    18.Write a program in C to print sum of all even numbers and odd numbers from 1-50 using all loops.(Demonstration of If else with loop).

    19.Write a program in C to print sum of all numbers that are divisible by 7 from 1-50 using all loops.(Demonstration of If else, operator and loop).

    20.Write a program in C to find out the factorial of a number, where number is entered by user using allloops (for loop, while loop and do-while loop).

    21.Write a program in C to find out the sum of the digits of given four digits number, where number isentered by the user.

    22.Write a program in C to find out the sum of four digits number with the reverse of that number, wherenumber is entered by the user.

    23.Write a program in C to fin out the average of 10 numbers; all numbers are entered by the user throughkeyboard.

    24.Write a program in C to generate fibonaci series.

    25.Write a program in C to see whether a given number is prime or not, where number is entered by user.Write a C program to read in two numbers, x and n, and then compute the sum of this geometricprogression:1+x+x2+x3+.+xn For example: if n is 3 and x is 5, then the program computes1+5+25+125.

  • 8/2/2019 CS 101-LM

    29/63

    Chapter 5 Multi way Decision Making statement based programs

    5.1. Introduction

    The switch statement is another form of the multi way decision. It tests whether an expression matches one of anumber ofconstantinteger values, and branches accordingly. It is well structured, but can only be used in certaincases where;

    Only one variable is tested, All branches must depend on the value of that variable. The variable must bean integral type.(int long, short or char).

    Each possible value of the variable can control a single branch. A final ,catch all default branch mayoptionally be used to trap all unspecified cases.

    5.1.1 SYNTAX

    switch (expression){case const-expr1:

    statements;break;

    case const-expr2:statements;break;

    .

    .case const-exprN:

    statements;break;default: statements}

    5.1.2 PROGRAM FLOW:

    1. First the value of the expression is evaluated.2. Each case is labeled by one or more integer-valued constants or constant expressions. Then value of

    the expression is matched with all available cases constant expression.3. If a case matches the expression value, execution starts at that case. All case expressions must be

    different.4. if match is not found next cases constant expression is matched and so on . The case labeled default

    is executed if none of the other cases are satisfied. A default is optional; if it isn't there and if none ofthe cases match, no action at all takes place.

    5.1.3 EXAMPLES

  • 8/2/2019 CS 101-LM

    30/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 30

    Example 1 : write a program in C to count number of digits, white spaces, line and words in the text line.

    #include main() /* count digits, white space, others */

    {int c, i, nwhite, nother, ndigit[10];nwhite = nother = 0;for (i = 0; i < 10; i++)ndigit[i] = 0;while ((c = getchar()) != EOF){switch (c){

    case '0':case '1':

    case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':

    ndigit[c-'0']++;break;

    case ' ':

    case '\n':case '\t':nwhite++;break;

    default:nother++;break;

    }}printf("digits =");for (i = 0; i < 10; i++)

    printf(" %d", ndigit[i]);printf(", white space = %d, other = %d\n",nwhite, nother);return 0;}

    The break statement causes an immediate exit from the switch. Because cases serve just as labels, afterthe code for one case is done, execution falls through to the next unless you take explicit action to escape.

    Cases and the default clause can occur in any order.

    break and return are the most common ways to leave a switch.A break statement can also be used to forcean immediate exit from while, for, and do loops.

  • 8/2/2019 CS 101-LM

    31/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 31

    Falling through cases is a mixed blessing. On the positive side, it allows several cases to be attached to asingle action, as with the digits in above example. But i t also implies that normally each case must end witha break to prevent falling through to the next.

    Example 2: This is a program which accepts four mathematical symbols + , - , * , / .Then the programaccepts two integers a & b & displays the output as the value of a + b , a b , a * b or a / b depending uponthe symbol entered.#includemain(){int a,b;char c;printf(Enter the symbol \n);scanf(%c,&c);switch(c)

    {case + :

    printf(Enter the values for a & b\n);scanf(%d %d,&a,&b);printf(a + b = %d\n,a+b);break;

    case - :printf(Enter the values for a & b\n);scanf(%d %d,&a,&b);printf(a - b = %d\n,a-b);break;

    case * :printf(Enter the values for a & b\n);scanf(%d %d,&a,&b);printf(a * b = %d\n,a*b);break;

    case / :printf(Enter the values for a & b\n);scanf(%d %d,&a,&b);printf(a / b = %d\n,a/b);break;

    default :

    printf(Invalid operator\n);}}

    Here, each interesting case is listed with a corresponding action. The control passes to the statementwhose case constant- expression matches the value of switch (expression).

    The switch statement can include any number of case instances, but no two case constants within thesame switch statement can have the same value.

    Execution of the statement body begins at the selected statement and proceeds until the end of the body oruntil a break statement transfers control out of the body.

    The break statement prevents any further statements from being executed by leaving the switch

  • 8/2/2019 CS 101-LM

    32/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 32

    The default statement is executed if no case constant-expression is equal to the value switch (expression).If the default statement is omitted and no case match is found, none of the statements in the switch bodyare executed. There can be at most one default statement. The default statement need not come at theend, it can appear anywhere in the body of the switch statement. A case ordefault label can only appear

    inside a switch statement. Switch statement can be nested.

    ANSI C requires at least 257 case labels be allowed in a switch statement.

    5.2. PROGRAM LIST

    1. Write a menu driven program calculator that receives 2 numeric values from the keyboard and performsfollowing operations: (Using nested if else and do while loop).

    Addition of 2 numbers.

    Subtraction of 2 numbers. Multiplication of 2 numbers.

    Division of 2 numbers. Modulo Division(remainder)

    Greater between 2 numbers.

    Power function.2. Write a program in C to find out whether a given number is Even or Odd using Switch-case- default (Multi

    way Decision Making Statement). (Demonstration of Switch).

    3. Write a menu driven program calculator that receives 2 numeric values from the keyboard and performsfollowing operations: (Using Switch).

    Addition of 2 numbers.

    Subtraction of 2 numbers. Multiplication of 2 numbers.

    Division of 2 numbers.

    Modulo Division(remainder)

    Greater between 2 numbers.

    Power function.4. Write a menu driven program that receives a number from the keyboard en having following functionality :

    Even or odd.

    Positive or negative or zero. Generate table.

    Factorial of number. Whether number is divisible by 5 or not.

    5. Write a C program that uses functions to perform the following operations:i) Reading a complex numberii) Writing a complex numberiii) Addition of two complex numbersiv) Multiplication of two complex numbers(Note: represent complex number using a structure.)

  • 8/2/2019 CS 101-LM

    33/63

    Chapter 6 Array

    6.1. Introduction:

    A single variable of specific type is able to store only single value at a time. But sometimes we need tostore multiple values of same types that are interrelated. For example marks of 100 students of a class orsalary of 100 employee of particular department of an organization. We either multiple variable of sametype and store single value in single variable or we declare an Array.

    An array is a group of related data items of same type that share a common name. For instance, we candefine an array name salary to represent a set of salaries of a group of employees. A particular value isindicated by writing a index number or subscript in square brackets after the array name. For example,

    Salary [10]

    Above statement represents the salary of the 10th employee. While the complete set of values is referredto as an array, the individual values are called elements. Arrays can be of any variable type. The ability touse a single name to represent a collection of items and to refer to an item by specifying the item numberenables us to develop concise and efficient programs.

    An Array will be Stored in Sequential Memory locations.

    The Elements of an array can be accessed using indices or subscripts. for Exampleint a[10];

    10 here represents size of the array , always should be a positive value , and the elements of this array canbe accessible in the following manner:

    a[0],a[1],a[2],a[3]a[9]

    An Array always starts with an Index 0 and last index will be N-1 where N is the size of the array.The total Bytes Occupied by an array is : Size of array * size of (single data type)C language has a drawback it has no array bound checking for example:

    int a[10];Starting index: 0 last index: 9, if we access a [20] the compiler wont generate any error.

    6.2. Types of Array

    1. One Dimensional Array.(Single Dimensional Array)2. Two Dimensional Arrays.3. Multi Dimensional Array.

    6.2.1 One Dimensional Array

    It is also known as Single Dimensional Array. An array that has only one subscript to refer array elementis known as one dimensional array or a list of items can be given one variable name using only onesubscript and such a variable is called a single/one dimensional array.

    6.2.1.1. Declaration of One Dimensional Array:

    Like any other variable, arrays must be declared before they are used. In the declarationprogrammer specifies type of the array, its name and number of elements present in the array.Following is the syntax :

    [Size];

  • 8/2/2019 CS 101-LM

    34/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 34

    The type specifies the type of element that will be contained in the array, such as int, float, or char.

    The Size indicates the maximum number of elements that can be stored inside the array. Forexample

    Float height [50];

    Above statement declares the height to be an array containing 50 real elements. Any subscripts 0to 49 are valid.

    The C language treats character strings simply as arrays of characters. The size in a characterstring represents the maximum number of characters that the string can hold. For instance,

    Char name [10];

    Declares the name as a character array (string) variable that can be hold maximum of 10characters.

    6.2.1.2. Initialization of One Dimensional Arrays We can initialize the elements of arrays in the same way as the ordinary variable when they are

    declared. The values in the list are separated by commas and enclosed within the curly brackets.int marks[6]={55,56,87,89,67,68};

    orint marks[ ]={55,56,87,89,67,68};

    while initializing an array at the time of declaration, size is optional .

    static int a[10]; - sets all the elements to 0.

    int a[10];- an array will be created by default contains garbage.

    If the number of values in the list is less than the number of elements, then only that manyelements will be initialized. The remaining elements will be set to zero automatically.

    int marks[6]={55,56,87,89};The above statement will initialized the first four elements to 55,56,87,89 and the remaining twoelements to zero.

    We can also initialize an array element by specifying the array name followed by subscript value insquare bracket at the left hand side of the assignment operator and value/expression at the righthand side of the assignment operator as:

    marks[4]=67;marks[5]=68;

    Array elements are numbered from 0 to n-1. Subscript value of the first element in the array is

    always 0 and subscript value of last element in the array is total number of element minus 1.

    6.2.1.3. Programming Examples of One Array:

    Example 1: write a program to enter 10 values fro the keyboard and display them and find out the totalof all elements.

    void main ( ){int i;float x [10], value, total;printf(ENTER 10 REAL NUMBERS\n); // Reading valuesfor (i = 0 ; i < 10; i + +)

  • 8/2/2019 CS 101-LM

    35/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 35

    {scan f (% f, &value);x[i] = value;}

    total = 0.0;for (i = 0; i < 10; i + + )total = total + x[i] * x[i] //COMPUTATION OF TOTALprint f (\n);printf(Array Value\n)for (i = 0; i< 10; i + + ) //PRINTING OF x[i]AND TOTALprintf ( X [ % 2d] = % 5.2f\n, i +1, x[i]);printf (\nTotal = % 2f\n, total);

    }

    Output

    ENTER 10 REAL NUMBERS1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10. 10

    Array ValueX[1] = 1.10X[2] = 2.20X[3] = 3.30X[4] = 4.40X[5] = 5.50X[6] = 6.60X[7] = 7.70X[8] = 8.80

    X[9] = 9.90X[10] = 10.10Total = 446.86

    Example 2 : write a program to enter 10 values fro the keyboard and find the minimum andmaximum of array elements.

    #include#includevoid main(){int a[10],i,min,max;

    clrscr();printf(enter the size of array\n);scanf(%d,&n);printf(enter the elements into the array\n);for(i=0;i

  • 8/2/2019 CS 101-LM

    36/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 36

    if(min>a[i])min=a[i];

    }printf (minimum element in the array : %d\n,min);

    printf(maximum element in the array: %d\n,max);getch();}

    6.2.2 Two Dimensional ArrayA two dimensional array is the collection of related same types of elements where two subscript values areused to access an element of array. It is also known as matrix. Consider the following data table, whichshows the value of marks of three subjects by four students :

    Subject 1 Subject 2 Subject 3

    Student 1 60 67 72

    Student 2 58 72 65Student 3 64 65 89Student 4 67 68 87

    The table contains a total of 12 values, three in each line. We can think of this table as a matrix consistingof four rows and three columns. Each row represents the marks obtained by a particular student and eachcolumn represents the marks in particular subject. C allows us to define such tables of items by using twodimensional arrays.

    6.2.2.1.Declaration of Two Dimensional Array:

    Like any other variable or one dimensional array, 2-D array must be declared before they are used.In the declaration programmer specifies type of the array, its name, number of rows and number of

    columns present in the array. Following is the syntax :

    [Row-Size] [Column-Size];

    The type specifies the type of element that will be contained in the array, such as int, float, or char.

    The row Size indicates the maximum number of elements rows in 2 D-array and column sizeindicates maximum number of elements in each row.. For example

    int matrix [3][3];

    Above statement declares the matrix of 9 elements, where there are 3 rows and every row hasthree elements. The subscript of first row and first column in [0][0] and subscript of last element is

    [2][2]. since subscript varies from 0 to N-1.Row-1 Row-1 Row-1

    Column-1

    Column-1

    Column-1

    Matrix[0][0] Matrix[0][1] Matrix[0][]

    Matrix[1][0] Matrix[1][1] Matrix[1][2]

    Matrix[2][0] Matrix[2][1] Matrix[2][2]

  • 8/2/2019 CS 101-LM

    37/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 37

    6.2.2.2. Initialization of Two Dimensional Array:

    Like the one dimensional arrays, two dimensional arrays may be initialized by following their

    declaration with a list of initial values enclosed in braces. For example-int table [2] [3] = {0,0,0,1,1,1};

    Above statement initializes the elements of the first row to zero and the second row to one.

    The initialization is done row by row. The above statement can be equivalently written as

    int table [2] [3] = {{0,0,0}, {1, 1,1}};

    By surrounding the elements of each row by braces. Note the syntax of the above statements.Commas are required after each brace that closes off a row, except in the case of the last row.

    If the values are missing in an initializer, they are automatically set to zero. For instance, thestatement

    int table [2][3] = { {1,1}, {2} };

    Above statement will initialize the first two elements of the first row tone, the first element of thesecond row to two, and all other elements to zero.

    When all the elements are to be initialized to zero, the following short cut method may be used.

    int m [3] [5] = { {0}, {0}, {0}};

    The first element of each row is explicitly initialized to zero while other elements are automaticallyinitialized to zero.

    6.2.2.3. Programming Examples of Two Arrays:

    Example 1: Write a C program that uses functions to perform the following:

    Addition of Two Matrices

    Multiplication of Two Matrices

    #include

    void main(){int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10];clrscr();

    printf("************************************");printf("\n\t\tMENU");printf("\n**********************************");printf("\n[1]ADDITION OF TWO MATRICES");printf("\n[2]MULTIPLICATION OF TWO MATRICES");printf("\n[0]EXIT");printf("\n**********************************");printf("\n\tEnter your choice:\n");scanf("%d",&ch);

    if(ch0)

  • 8/2/2019 CS 101-LM

    38/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 38

    {printf("Valid Choice\n");

    }

    switch(ch){

    case 1:printf("Input rows and columns of A & B Matrix:");scanf("%d%d",&r1,&c1);printf("Enter elements of matrix A:\n");for(i=0;i

  • 8/2/2019 CS 101-LM

    39/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 39

    {c[i][j]=0;for(k=0;k

  • 8/2/2019 CS 101-LM

    40/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 40

    return 0;}

    6.2.3 Multi Dimensional Array

    C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The generalform of a multidimensional array is:

    [size-1][size-2 ][size-3].[size-N]

    The type specifies the type of element that will be contained in the array, such as int, float, or char. Forexample;

    float table [5] [4] [3];

    Similarly table is a three dimensional array containing 60 elements of floating point type. In above example

    there is table array having 5 Rows, every row having 4 columns, every column have 3 sub columns.

    6.3. PROGRAM LIST

    1. Write a program in C that declare an array of size 10 and Demonstrate initialization at compile time andalso initialize array from user input. Also prints all values on to the computer screen.(Demonstration ofarray Declaration, initialization at Compile time and from the user)

    2. Write a program in C that declare an array of size 10 and find out the average of the elements.

    3. Write a program in C that declare an array of size 10 and find out largest and smallest number amongarray elements.

    4. Write a program in C to copy the contents of one array in to another array of the same size and type inthe reverse order.

    5. Write a program in C to SWAP the contents of one array with another array of same size and same typewith the help of third variable.

    6. Write a program in C to SWAP the contents of one array with another array of same size and same typewithout the help of any third element.

    7. Write a program in C to add the content of one array with the reverse of another array and store the resultin third array. Where all arrays are of same type and same size.

    8. Write a program to convert given decimal number to equivalent binary, octal and hexadecimal numbers.

    9. Write a menu driven program that declare array of size 10. Insert values in to the array from the keyboardand having following options.

  • 8/2/2019 CS 101-LM

    41/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 41

    a. Sum of all elements of the array.

    b. Average of all elements of the array.

    c. Total even numbers and total odd numbers in the array.

    d. Total Positive numbers and total Negative numbers in the array.

    e. Sum of even numbers and sum of Odd numbers.

    f. Sum of positive numbers and sum of negative numbers.

    10.Write a menu driven program that declare array of size 10. . Insert values in to the array from thekeyboard and having following options.

    a. Searching a given number and printing location if exists in the array.

    b. Sorting array element in ascending order.

    c. Sorting array element in descending order.

    d. Insertion of a new element at particular location in the array.

    e. Deletion of a existing element from a particular location from the array.

    11.write a program in C to declare a 2-D array, initialize array elements at compile time and run time anddisplay contents as matrix form like

    | 1 2 3|

    |4 5 6|

    |7 8 9|

    12.Write a menu driven program that declare A 3X3 2-D matrix and perform following operations.

    a. Addition of two matrices.

    b. Subtraction of two matrices.

    c. Multiplication of two matrices.

    d. Transpose of first matrix.

    e. Whether a matrix is symmetric or not.

  • 8/2/2019 CS 101-LM

    42/63

    Chapter 7 Strings

    Character array is known as string. We know that an array has multiple elements of same types so string is anarray of character types elements. A String is a Collection of characters and ends with a null character \0 whichrepresents end of the string. String.h is the header file which contains functions to manipulate with strings. The sizeof the sstring is equals to the total characters present in the string plus 1( one extra byte for null character).

    7.1. Initialization of strings

    An initialization of string can be done in four ways:1. A string can be initialized by writing the string in douvle quation marks as follows. In this case it is not necessary

    to specify null character explicitly.char str[11] = University;

    2. The alternative way to declare and initialize a string is as follows:char str[11] = { University};

    3. We can also specify each character separately as:char str[11] = {U,n,i,v,e,r,s,I,t,y,\0};

    4. char str[ ] = {U,n,i,v,e,r,s,I,t,y,\0};

    In all the above initializations size is optional as strings are initialized statically.

    5. char a[ ]=hello;char *p = hello;

    In the above example a and p are same, first one is a character array, and p is a pointer which points to thestring. In all the above initializations size is optional as strings are initialized statically.

    6. char *p = hello; *q;q=p;printf(%s %s,p,q);

    it will prints hello hello7. char a[10]=hello,b[10];

    b = a;it will give error, since an array cannot be directly assigned to another array.

    7.2. Reading and Writing strings:

    gets(char array) reads string with multiple words with spaces.

    scanf(%s, &char array); - reads a string with out spaces.

    puts(char array); function used to write a string followed by \n automatically.

    7.2.1 Tips char a[ ]=hello;

    char *p = hello;In the above example a and p are same, first one is a character array, and p is a pointer whichpoints to the string.

    char a[10]=hello,b[10];

  • 8/2/2019 CS 101-LM

    43/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 43

    b = a;Error , array cannot be directly assigned to another array.

    char *p = hello; *q;q=p;

    printf(%s %s,p,q);it will print hello hello

    7.3. String Handling Functions:

    String Handling functions are library functions that are used to perform operations over strings. All string handlingfunctions are the part of string.h header file.

    strlen( ) which returns the length of the string.Ex: int i = strlen(welcome);If we print the value of i then it will print 7.

    strcat( ) which concatenates two stringsEx: strcat(good,morning); prints good morning

    strcpy( )- which copies one string to another.Ex: - strcpy(str,hello); copies hello to string str where str is a character array

    strcmp() compares two strings and returns0 if both strings are exactly equalPositive value if first string is > second stringNegative value if first string is < second string (conclusion: returns ASCII Difference)

    strrev() which reverses a string

    Ex: char str[] = computers;strrev(str);printf(%s,str);it will print sretupmoc

    strupr() which converts a string to upper case

    strlwr() which converts a string to lower case.

    7.4. Program List

    1. Write a program in C to fin out the length of the string, where string is entered by user.

    2. Write a program in C to demonstrate the working of gets( ) and puts( ) functions.

    3. Write a program in C to copy the contents of one string into another string without using anylibrary function.

    4. Write a program in C to concatenate the contents of one string after another string withoutusing any library function.

    5. Demonstration of all string Handling Library Functions (String.h).

  • 8/2/2019 CS 101-LM

    44/63

    Chapter 8 Function

    8.1. Definition

    A function is a set/block of statements that has predefined objective. It is a self contained block of code thatperforms a specific task. In C, a program is a collection of well defined and interrelated functions. A function isdeclared with three parameters. The first one is name of the function, the second gives the argument list, and the third is the type of the returned value. Functions break large computing tasks into smaller ones.

    A function is a group of Statements binded together to perform a particular task.Functions are broadly classified into two categories:

    Library Functions: They are also called Predefined, built in functions, incorporated in header files.Ex: - printf( ), scanf( ) , sqrt( ), clrscr( ),getch( ).

    User defined Functions: The functions defined by the user are called user defined functions.main() is the best example for user defined function.

    8.2. Need of Function :

    The most important advantage of the function is to avoid rewriting the same code again and again. Once a functionis implemented, it can be called any number of times and every time it will perform the same task, but may havedifferent types of values for operation.As programs become more complex and large, several problems arise. Most common are

    Algorithms for solving more complex problems become more difficult and ,hence difficult to design Even if algorithms are known, its implementation becomes more difficult because the size of the program is

    longer As programs become larger and complex, debugging and testing becomes more difficult. As programs become larger and complex, more documentation is required to make the program

    understandable for people who will use and maintain the program.

    8.3. Function Declaration:

    As you know, you have to declare or define a variable before you can use it. This is also true for functions. In C, youhave to declare or define a function before you can call it.The general form of a function declaration, including its prototype, is as follows:

    data_type_specifier function_name(

    data_type_specifier argument_name1,data_type_specifier argument_name2,data_type_specifier argument_name3,.data_type_specifier argument_nameN,);

    The purpose of using a function prototype is to help the compiler check whether the data types of argumentspassed to a function match what the function expects. The compiler issues an error message if the data types donot match. Although argument names, such as argument_name1, argument_name2, and so on, are optional, it isrecommended that you include them so that the compiler can identify any mismatches of argument names.

    8.4. How a Function Works

  • 8/2/2019 CS 101-LM

    45/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 45

    A C program doesn't execute the statements in a function until the function is called by another part of the program.When a function is called, the program can send the function information in the form of one or more arguments. Anargument is program data needed by the function to perform its task. The statements in the function then execute,performing whatever task each was designed to do. When the function's statements have finished, execution

    passes back to the same location in the program that called the function. Functions can send information back tothe program in the form of a return value.

    8.5. Declaration Versus Definition

    According to the ANSI standard, the declaration of a variable or function specifies the interpretation and attributes ofa set of identifiers. The definition, on the other hand, requires the C compiler to reserve storage for a variable orfunction named by an identifier.

    A variable declaration is a definition, but a function declaration is not. A function declaration alludes to a functionthat is defined elsewhere and specifies what kind of value is returned by the function. A function definition defines

    what the function does, as well as gives the number and type of arguments passed to the function.A function declaration is not a function definition. If a function definition is placed in your source file before thefunction is first called, you don't need to make the function declaration. Otherwise, the declaration of a function mustbe made before the function is invoked.

    For example, the printf() function is used in almost every sample program. Each time, it include a header file,stdio.h, because the header file contains the declaration of printf(), which indicates to the compiler the return typeand prototype of the function. The definition of the printf() function is placed somewhere else. In C, the definition ofthis function is saved in a library file that is invoked during the linking states.

    8.6. Specifying Return Types

    A function can be declared to return any data type, except an array or function. The return statement used in afunction definition returns a single value whose type should match the one declared in the function declaration.By default, the return type of a function is int, if no explicit data type is specified for the function. A data typespecifier is placed prior to the name of a function like this:

    data_type_specifier function_name();

    Here data_type_specifier specifies the data type that the function should return. function_name is the function namethat should follow the rule of naming in C.

    8.7. Local and Global Variables

    The variables declared inside a function are local to that function. It can be accessed only with in thatfunction. Memories for the local variables are allocated only when the function is invoked and deallocatedwhen the control returns to the calling function. These variables are also known to be automatic variables.

    The variables declared outside of all function are global variables. These global variables are visible to allfunctions.

    8.8. Making Function Calls

  • 8/2/2019 CS 101-LM

    46/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 46

    When a function call is made, the program execution jumps to the function and finishes the task assigned tothe function. Then the program execution resumes after the called function returns. A function call is anexpression that can be used as a single statement or within other statements.

    8.9. Recursion

    The term recursion refers to a situation in which a function calls itself either directly or indirectly. Indirect recursionoccurs when one function calls another function that then calls the first function. C allows recursive functions, andthey can be useful in some situations. If a function is having a self-reference, it is recursion. In order that thefunction should not continue indefinitely, a recursive function must have the following properties:

    There must be certain criteria, called base criteria, for which a function does not call itself.

    Each time, when a function calls itself, it must be close to the base criteria. That is, it uses an argument(s)smaller than the one it was given at previous reference.

    For example, recursion can be used to calculate the factorial of a number. The factorial of a number x is written x!and is calculated as follows:

    x! = x * (x-1) * (x-2) * (x-3) * ... * (2) * 1However, you can also calculate x! like this:

    x! = x * (x-1)!

    Going one step further, you can calculate (x-1)! using the same procedure:(x-1)! = (x-1) * (x-2)!

    You can continue calculating recursively until you're down to a value of 1, in which case you're finished. Thefollowing program uses a recursive function to calculate factorials. Because the program uses unsigned integers,it's limited to an input value of 8; the factorial of 9 and larger values are outside the allowed range for integers.

    EXAMPLE: write a program to calculate the factorial of given number using a recursion.#include int factorial(int a); //function declarationmain(){

    int f, x;puts("Enter an integer value between 1 and 8: ");scanf("%d", &x);

    if( x > 8 || x < 1){

    printf("Only values from 1 to 8 are acceptable!");}else{f = factorial(x); //function callprintf("%u factorial equals %u\n", x, f);}

    return 0;}

    int factorial(int a) //function definition

  • 8/2/2019 CS 101-LM

    47/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 47

    {if (a == 1)

    return 1;else

    {a *= factorial(a-1);return a;

    }}

    Out Put:-Enter an integer value between 1 and 8:66 factorial equals 720

    8.10. Passing arguments to a Function

    The mechanism used to pass data to a function is via argument list. There are two approaches to passingarguments to a function. These are

    Call by Value

    Call by Reference

    8.10.1 Call by Value:

    In this method the value of the actual arguments in the calling functions are copied in to corresponding

    formal arguments of called function. With this method the changes made to the formal arguments in calledfunction have no effect on the values of actual arguments in calling function.

    Example: write a program to swap the values of two variables with the help of third variable.void main(){

    int a, b;a=10;b=20;swap(a, b);/* passing the values of a and b to c and d of swap function*/printf(%d %d, a, b); /* Prints 10 20 */

    }//definition og swap function.void swap(int c, int d)/*Function used to swap the values of variables c and d */{int temp;temp = c;c = d;d = temp;}

  • 8/2/2019 CS 101-LM

    48/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 48

    8.10.2Call by Rerference

    In call by reference method we are passing the address of the data as argument. This means thatusing these addresses, we would have an access to actual argument and hence we would able to

    manipulate them. In this approach, the addresses of actual arguments are used in the function call. Theformal arguments should be declared as Pointer variables.This approach is of practical importance while passing arrays and structures among functions and also forpassing back more than one value to the calling function.

    Example: write a program to swap the values of two variables with the help of third variable.void main(){int a, b;a=10;b=20;

    swap(&a, &b); /* passing the addresses of a and b to c and d of swap function*/printf(%d %d, a, b);/* Prints 20 10 */}void swap(int *c, int *d){int temp;temp = *c;*c = *d;*d = temp;}

    8.11. Program List:

    1. Write a program in C to find out factorial of given number, where number is entered by userusing the concept of Function. (Without Recursion).

    2. Write a program in C to SWAP the values of two variables with the help of function. Programshould display values of both variables before and after the swapping operation(Using call byvalue).

    3. Write a program in C to SWAP the values of two variables with the help of function. Programshould display values of both variables before and after the swapping operation (Using call byReference).

    4. Write a program in C to find out factorial of given number, where number is entered by user

    using the concept of Function. (Recursion).

    5. Write C programs that use both recursive and non-recursive functions, to find the GCD(greatest common divisor) of two given integers.

  • 8/2/2019 CS 101-LM

    49/63

    Chapter 9 Structure and Union

    9.1. Definition of structure:

    A structure is a collection of one or more variables, possibly of different types, groupedtogether under a single name.

    Or

    Structure is a Derived Data type, and collection of dissimilar data items.

    It is a convenient tool for handling a group of logically related data items. Structures help to organize complicateddata, particularly in large programs, because they permit a group of related variables to be treated as a unit instead

    of as separate entities.One traditional example of a structure is the student record: a student is described by a set of attributes such asname, enrollment number, fathers name, branch, year, address, semester, marks in different subjects, etc. Some ofthese in turn could be structures: a name has several components, as does an address.

    9.2. Declaration of structure:

    A structure is declared by declaring all of its fields. They are grouped between curly braces and are preceded by thekeyword struct. A structure, as a type, may be named to be reused later. This feature avoids repeating the fullcontent of the structure. Such a name is called a tag name and is placed between the keyword structand theopening curly brace.

    9.2.1 SYNTAX:

    Struct { member name1; member name1;

    .

    . member name1;

    };9.2.2 EXAMPLE:

    Consider a book database consisting of book name, author, number of pages, and price. We can define astructure to hold this information as follows:struct book_bank{char titile[20];char author[15];int pages;float price;};The keyword struct declares a structure to hold the details of four fields, namely titile, author, pages, andprice. These fields are called structure elements or members. Each member may belong to a different type

    of data. book_bank is the name of the structure and is called the structure tag. The tag name used

  • 8/2/2019 CS 101-LM

    50/63

    Developed By- Harish Tiwari, Lecturer, Department of CSE/IT, SPSU, Udaipur 50

    subsequently to declare variables that have the tags structure. Structure declaration is terminated by semicolon.

    9.3. Declaration of Structure variable:

    Structure is a user defined data type. So we can declare variable as we declare for primary data types. Once astructure has been declared, we can declare structure variable to access structures members. Once a tag namehas been associated to a structure, any further declaration does not need to repeat the structure content The actualmemory is allocated to the structure when structure variable is