Anna University CP 2 Marks

download Anna University CP 2 Marks

of 62

Transcript of Anna University CP 2 Marks

  • 8/10/2019 Anna University CP 2 Marks

    1/62

    GE6151 Computer Programming Question Bank

    UNIT I - INTRODUCTION

    PART A (2 MARKS)

    1. Define computers?

    A computer is a programmable machine or device that performs pre-defined or programmed

    computations or controls operations that are expressible in numerical or logical terms at high speed and with

    great accuracy.

    (Or)

    Computer is a fast operating electronic device, which automatically accepts and store input data,

    processes them and produces results under the direction of step by step program.

    2. What are the basic operations of Computer? It accepts data or instructions by way of input It stores data. It can process data as required by the user. It gives results in the form of output. It controls all operations inside a computer.

    3. What are the characteristics of computers? (JAN 2009)

    Speed, Accuracy, Automation, Endurance, Versatility, Storage, Cost Reduction.

    4. How will you classify computer systems? (JAN2009)

    Based on physical size, performance and application areas, we can generally divide computers into four

    major categories: Micro computer Mini Computer Mainframe computer Super Computer

    5. Expand ENIVAC, ABC, EDVAC, EDSAC and UNIVAC. (JAN2010)

    ENIAC - Electronic Numerical Integrator and Calculator.

    ABC - Atanasoff and Berry Computer.

    EDVAC - Electronic Discrete Variable Automatic Calculator.

    EDSAC - Electronic Delay Storage Automatic Calculator.

    UNIVAC - UNIversal Automatic Computer.

    6. What are the components of the computer systems?

  • 8/10/2019 Anna University CP 2 Marks

    2/62

    Basic components of the computer system are Input Unit, Central Processing Unit, Secondary Storage Unit

    and Output Unit.

    7. What is an ALU?

    Arithmetic logic unit, the part of a computer that performs all arithmetic computations, such as addition and

    multiplication, and all logical operations such as comparison operations. The ALU is one component of the

    CPU (central processing unit).

    8. What are the functions in the input unit?

    An input device is a device that is used to input data or information into a computer. Some examples of input

    devices include: Keyboards. Computer mice Light Pen. Digitizer. Touchpad.

    9. What are the functions in the output unit?

    In computers, a unit which delivers information from the computer to an external device or from internal

    storage to external storage.

    Speakers. Printer. Headphone

    10. Define Mainframe computer?

    Mainframes are computers used mainly by large organizations for critical applications, typically bulk data

    processing such as census, industry and consumer statistics, enterprise resource planning, and financial

    processing. The term probably had originated from the early mainframes, as they were housed in enormous,

    room-sized metal boxes or frames.

    11. Define super computer?The fastest type of computer. Supercomputers are very expensive and are employed for specialized

    applications that require immense amounts of mathematical calculations. For example, weather

    forecasting requires a supercomputer. Other uses of supercomputers include animated graphics, fluid

    dynamic calculations, nuclear energy research, and petroleum exploration.

    12. What is a volatile and non-volatile memory?

  • 8/10/2019 Anna University CP 2 Marks

    3/62

    Volatile memory: also known as volatile storage is computer memory that requires power to maintain the

    stored information, unlike non-volatile memory which does not require a maintained power supply. It has

    been less popularly known as temporary memory.

    Non-volatile memory: nonvolatile memory, NVM or non-volatile storage, is computer memory that can

    retain the stored information even when not powered.

    13. Write the binary and octal equivalent of hexadecimal number 7BD? (APR2009)

    Binary Equivalent of 7BD = (0111 1011 1101)2

    Octal Equivalent of 7BD = (011 110 111 101) = (3675)814. Convert binary number 100110 into its octal equivalent? (JAN2009)

    Octal equivalent of 100110 = (100 110) = (46)8

    15. What are registers? (JAN2009)

    A special, high-speed storage area within the CPU. All data must be represented in a register before it can be

    processed.

    For example, if two numbers are to be multiplied, both numbers must be in registers, and the result is also

    placed in a register.

    16. Differentiate analog and digital computers? (JAN2010) Analog Computer Digital Computer

    Sl.No Analog Computer Digital Computer

    1 Process measured data Process discrete data

    2 Analog computers are not precise Digital computers are more precise

    3 Processing speed is low Processing speed is high.

    4 Less accuracy More accuracy.

    17. Find the decimal equivalent of hexadecimal number 4D.C8 (JAN2010)

    4D.C8 = 4 X 161 + 13 X 162 + 12 X 16-1 + 8 X 16-2

    = 64 + 13 +0.75 + 0.03125

    = (77.78) 2

    18. Convert hexadecimal number into binary equivalent of EBC (JAN2010)

    Binary equivalent of EBC = (1110 1011 1100) 2

    19. What is algorithm? (JAN2009)Algorithm means the logic of a program. It is a step-by-step description of how to arrive at a solution of a

    given problem.

    20. What are the steps to solve the problem in a computer system?

    Problem must be analyzed thoroughly. Solution method is broken down into a sequence of small tasks. Based on this analysis, an algorithm must be prepared to solve the problem. The algorithm is expressed in a precise notation. This notation is known as Computer Program. The Computer program is fed to the computer. The instruction in the program executes one after another and outputs the expected result.

  • 8/10/2019 Anna University CP 2 Marks

    4/62

    21. What are the characteristics of an algorithm?

    In algorithms each and every instruction should be precise. In algorithms each and every instruction should be unambiguous. The instructions in an algorithm should not be repeated infinitely. Ensure that the algorithm will ultimately terminate. The algorithm should be written in sequence. It looks like normal English.

    22. What is Flowchart?A Flowchart is a pictorial representation of an algorithm. It is often used by programmer as a program

    planning tool for organizing a sequence of step necessary to solve a problem by a computer.

    23. What is the need of Flowchart symbols?

    Each symbol of different shapes denotes different shapes denote different types of instructions. The

    program logic through flowcharts is made easier through the use of symbol that has standardized

    planning.

    24. What is pseudo code?

    Pseudo means imitation of false and code refers to the instruction written in the programming

    language. Pseudo code is programming analysis tool that is used for planning program logic.

    25. Draw the flowchart to find the maximum among three numbers (JAN2009)

  • 8/10/2019 Anna University CP 2 Marks

    5/62

  • 8/10/2019 Anna University CP 2 Marks

    6/62

    UNIT-II

    1. Define Compilation process.

    Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object'

    file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the

    machine language instructions that correspond to the source code file that was compiled.

    2. What do you meant by linking?

    Linking refers to the creation of a single executable file from multiple object files. In this step, it is

    common that the linker will complain about undefined functions (commonly, main itself). During

    compilation, if the compiler could not find the definition for a particular function, it would just assume

    that the function was defined in another file. If this isn't the case, there's no way the compiler would know it

    doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at

    multiple files and try to find references for the functions that weren't mentioned.

    3. Define Constants in C. Mention the types.

    The constants refer to fixed values that the program may not alter during its execution. These fixed valuesare also called literals.

    Constants can be of any of the basic data types like an integer constant, a floating constant, a characterconstant, or a string literal . There are also enumeration constants as well.

    The constants are treated just like regular variables except that their values cannot be modified after theirdefinition.

    4. What are the different data types available in C ?

    There are four basic data types available in C .

    1. int

    2. float

    3. char

    4. double

    5. What is meant by Enumerated data type.Enumerated data is a user defined data type in C language.

    Enumerated data type variables can only assume values which have been previously declared.

    Example :

    enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

    6. What are Keywords?

    Keywords are certain reserved words that have standard and pre- defined meaning in C . These keywords can

    be used only for their intended purpose.

  • 8/10/2019 Anna University CP 2 Marks

    7/62

    7. What do you mean by variables in C ?

    A variable is a data name used for storing a data value. Can be assigned different values at different times during program execution. Can be chosen by programmer in a meaningful way so as to reflect its function in the program

    Example: Sum

    8. Difference between Local and Global variable in C.

    Local

    These variables only exist inside the specific function that creates them. They are unknown to other

    functions and to the main program. As such, they are normally implemented using a stack. Local

    variables cease to exist once the function that created them is completed. They are recreated each time a

    function is executed or called.

    Global

    These variables can be accessed (ie known) by any function comprising the program. They are

    implemented by associating memory locations with variable names. They do not get recreated if the

    function is recalled.

    9. What are Operators? Mention their types in C.

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C

    language is rich in built-in operators and provides following type of operators: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Special Operators

    10. What is the difference between = and == operator?

    Where = is an assignment operator and == is a relational operator.

    Example:while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only when i=5.

    11. What is type casting?

    Type casting is the process of converting the value of an expression to a particular data type.

    Example:

    int x,y;

    c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into float.

    12.What is the difference between ++a and a++?

  • 8/10/2019 Anna University CP 2 Marks

    8/62

    ++a means do the increment before the operation (pre increment)

    a++ means do the increment after the operation (post increment)

    Example:

    a=5;

    x=a++;y=a;

    x=++a;

    3. Distinguish between while..do and do..while statement in C. (JAN 2009)

    While DO..whileExecutes the statements within the while block if only thecondition is true.

    Executes the statements within the while block at least once.

    The condition is checked at the starting of the loop (Entry

    Controlled Statement)

    The condition is checked at the end of the

    loop (Exit Control Statement)

    14. Mention the various Decisions making statement available in C.

    Statement

    if statement

    if...else statement

    nested if statements

    switch statement

    nested switch statements

    Description

    An if statement consists of a boolean expression followed by one or mor

    An if statement can be followed by an optional else statement, which ex

    when the boolean expression is false

    You can use one if or else if statement inside another if or else if statem

    A switch statement allows a variable to be tested for equality against a li

    You can use one swicth statement inside another switch statement(s).

  • 8/10/2019 Anna University CP 2 Marks

    9/62

    15.What do you meant by conditional or ternary operator?

    ? : If Condition is true ? Then value X : Otherwise value Y

    16. What is the use of sizeof() operator in C.

    Sizeof operator is used to return the size of an variable.

    Example : sizeof(a), Where a integer, will return 4.

    17. Define Looping in C .

    A loop statement allows us to execute a statement or group of statements multiple times andfollowing is the general from of a loop statement in most of the programming languages

    18. What are the types of looping statements available in C

    C programming language provides following types of loop to handle looping requirements.

    while loop

    Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

    for loopdo...while loopnested loops

    Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

    Like a while statement, except that it tests the condition at the end of the loop body

    You can use one or more loop inside anyloop.

  • 8/10/2019 Anna University CP 2 Marks

    10/62

    19. What are the types of I/O statements available in C ?

    There are two types of I/O statements available in C .

    Statements

    20. Write short notes about main ( ) function in C program. (MAY 2009)

    m execution starts from the opening brace { and ends with closing brace } , within

    which executable part of the program exists.

    21. Define delimiters in C .

    Delimiters Use

    : Colon

    ; Semicolon

    ( ) Parenthesis

    [ ] Square Bracket

    { } Curly Brace

    # Hash

    , Comma

    22. Why header files are included in C programming?

    This section is used to include the function definitions used in the program. Each header file has h

    extension and include using # include directive at the beginning of a program.

    23.What is the output of the programs given below?

    main() main()

    { {float a; float a;

    int x=6, y=4; int x=6, y=4;

    a=x\y; a=(float) x\y;

    printf(Value of a=%f, a); printf(Value of a=%f,a);

    } }

    Output: Output:

    1. 1.500000

  • 8/10/2019 Anna University CP 2 Marks

    11/62

    24.What is the difference between scanf() and gets() function?

    In scanf() when there is a blank was typed, the scanf() assumes that it is an end. gets() assumes the enter key

    as end. That is gets() gets a new line (\n) terminated string of characters from the keyboard and replaces

    the \n with \0 .

    25.What are the Escape Sequences present in C \n - New Line

    \b - Backspace

    \t - Form feed

    \ - Single quote

    \\ - Backspace

    \t - Tab

    \r - Carriage return

    \a - Alert

    \ - Double quotes

    26.What is the difference between if and while statement?

    If

    (i) It is a conditional statement

    (ii) If the condition is true, itexecutes

    some statements.

    (iii) If the condition is false then itstops

    the execution the statements.

    While

    (i) It is a loop control statement

    (ii) Executes the statements within the

    while block if the condition is true.

    (iii) If the condition is false the control is

    transferred to the next statement of the loop.

  • 8/10/2019 Anna University CP 2 Marks

    12/62

    27.Differentiate between formatted and unformatted you input and output functions? Formatted I/P functions:

    These functions allow us to supply the input in a fixed format and let us obtain the output in the specified

    form. Formatted output converts the internal binary representation of the data to ASCII characters which are

    written to the output file.

    Unformatted I/O functions:

    There are several standard library functions available under this category-those that can deal with a string of

    characters. Unformatted Input/Output is the most basic form of input/output. Unformatted input/output

    transfers the internal binary representation of the data directly between memory and the file.

    UNIT II

    (16 Marks)

    1. Define C language. Mention the basic structure of C programs with explanation. (16)C programs are essentially constructed in the following manner, as a number of well defined sections./* HEADER SECTION *//* Contains name, author, revision number*/

    /* INCLUDE SECTION *//* contains #include statements */

    /* CONSTANTS AND TYPES SECTION *//* contains types and #defines */

    /* GLOBAL VARIABLES SECTION */ /* any global variables declared here*/

    /* FUNCTIONS SECTION *//* user defined functions */

    /* main() SECTION */

    int main(){-----}

    A Simple ProgramThe following program is written in the C programming language.

    #include Void main(){

    printf(Programming in C is easy. \n);}

  • 8/10/2019 Anna University CP 2 Marks

    13/62

    INITIALISING DATA VARIABLES AT DECLARATION TIME

    In C, variables may be initialized with a value when they are declared. Consider the following

    declaration, which declares an integer variable count which is initialized to 10. int count = 10;

    SIMPLE ASSIGNMENT OF VALUES TO VARIABLES

    The = operator is used to assign values to data variables. Consider the following statement, which assigns the

    value 32 an integer variable count, and the letter A to the character variable letter

    count = 32;letter = A

    Variable Formatters%d decimal integer %c character%s string or character array%f float%e double

    HEADER FILES

    Header files contain definitions of functions and variables which can be incorporated into any C

    program by using the pre-processor #include statement. Standard header files are provided with each

    compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading

    of variables. To use any of the standard functions, the appropriate header file should be included. This is

    done at the beginning of the C source file. For example, to use the function printf() in a program, the line

    #include should be at the beginning of the source file, because the definition for printf() is

    found in the file stdio.h All header files have the extension .h and generally reside in the /include

    subdirectory.

    #include

    #include mydecls.h

    The use of angle brackets informs the compiler to search the compilers include directory for the

    specified file. The use of the double quotes around the filename inform the compiler to search in the

    current directory for the specified file.

    2. Discuss about the various data types in C . (MAY 2009)

    The four basic data types area. INTEGER

    These are whole numbers, both positive and negative. Unsigned integers (positive values only) are

    supported. In addition, there are short and long integers.

    The keyword used to define integers is,

  • 8/10/2019 Anna University CP 2 Marks

    14/62

    int

    An example of an integer value is 32. An example of declaring an integer variable called sum is,

    int sum;

    sum = 20;

    b. FLOATING POINT

    These are numbers which contain fractional parts, both positive and negative. The keyword used to define

    float variables is, float An example of a float value is 34.12. An example of declaring a float variable

    called money is,

    float money;

    money = 0.12;

    c. DOUBLE

    These are exponentional numbers, both positive and negative. The keyword used to define double

    variables is, double

    An example of a double value is 3.0E2. An example of declaring a double variable called big is,

    double big;

    big = 312E+7;

    d. CHARACTER

    These are single characters. The keyword used to define character variables is,char An example of a

    character value is the letter A. An example of declaring a character variable called letter is, char letter;

    letter = A ;

    Note the assignment of the character A to the variable letter is done by enclosing the value in single

    quotes.

    Example:

    #include < stdio.h >

    main()

    {int sum;

    float money;

    char letter;

    double pi;

  • 8/10/2019 Anna University CP 2 Marks

    15/62

    sum = 10; /* assign integer value */

    money = 2.21; /* assign float value */

    letter = A ; /* assign character value */

    pi = 2.01E6; /* assign a double value */

    printf(value of sum = %d \n, sum );

    printf(value of money = %f \n, money );

    printf(value of letter = %c \n, letter );

    printf(value of pi = %e \n, pi );

    }

    Sample program output

    value of sum = 10

    value of money = 2.210000 value of letter = A

    value of pi = 2.010000e+06

    3. What are Operators? Explain the various operators available in C. (16)

    An ex pr e ss io n is a sequence of operators and operands that specifies computation of a value, or that

    designates an object or a function, or that generates side effects, or that performs a combination thereof.

    ARITHMETIC OPERATORS:

    The symbols of the arithmetic operators are:-

    Operation Operator Comment Value of Sum before Value of sum after

    Multiply sum = sum * 2; 4 8 Divide / sum = sum / 2; 4 2

    Addition + sum = sum + 2; 4 6

    Subtraction - sum = sum -2; 4 2

    Increment ++ ++sum; 4 5

    Decrement -- --sum; 4 3

    Modulus % sum = sum % 3; 4 1

    Example:

  • 8/10/2019 Anna University CP 2 Marks

    16/62

    #include main(){int sum 50;float modulus;modulus = sum % 10;

    printf("The %% of %d by 10 is %f\n", sum, modulus);}

    PRE/POST INCREMENT/DECREMENT OPERATORS

    PRE means do the operation first followed by any assignment operation. POST means do the operation afterany assignment operation. Consider the following statements

    ++count; /* PRE Increment, means add one to count */ count++; /* POST Increment, means add one to count */

    THE RELATIONAL OPERATORS

    These allow the comparison of two or more variables.

    n equal to !=not equal=greater than or equal to

    Example:

    #include

    main() /* Program introduces the for statement, counts to ten */{ int count;

    for( count = 1; count

  • 8/10/2019 Anna University CP 2 Marks

    17/62

    LOGICAL OR ||

    Logical or will be executed if any ONE of the conditions is TRUE (non-zero).

    LOGICAL NOT !

    logical not negates (changes from TRUE to FALSE, vsvs) a condition.

    LOGICAL EOR ^

    Logical error will be executed if either condition is TRUE, but NOT if they are all true.

    THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR

    This conditional expression operator takes THREE operators. The two symbols used to denote this operator

    are

    the ? and the :. The first operand is placed before the ?, the second operand between the ? and the :, and the

    third after the :. The general format is,

    condition ? expression1 : expression2

    If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the evaluation

    becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its

    result becomes the result of the operation. An example will help,

    s = ( x < 0 ) ? -1 : x * x;

    If x is less than zero then s = -1 If x is greater than zero then s = x * x

    BIT OPERATIONS

  • 8/10/2019 Anna University CP 2 Marks

    18/62

    C has the advantage of direct bit manipulation and the operations available are,

  • 8/10/2019 Anna University CP 2 Marks

    19/62

    Operation Operator Comment

    AND & sum = sum & 2;

    OR | sum = sum | 2;

    Exclusive OR ^ sum = sum ^ 2;

    1's Complement ~ sum = ~sum;

    Left Shift sum = sum >> 2; 4 0

    Example:

    /* Example program illustrating > */#include

    main() { int n1 = 10, n2 = 20, i = 0;

    i = n2 > 5; /* n1 shifted right

    five times */ printf("%d\n", i); }

    4. Explain in detail about managing the Input Output Operations. (16)

    Printf ():

    printf() is actually a function (procedure) in C that is used for printing variables and text. Where text

    appears in double quotes "", it is printed without modification. There are some exceptions however. This has

    to do with the \ and % characters. These characters are modifier's, and for the present the \ followed by the n

    character represents a newline character.

  • 8/10/2019 Anna University CP 2 Marks

    20/62

    Example:

    #include

    main() {

    printf("Programming in is easy.\n"); printf("And so is Pascal.\n"); } O/P:

    Programming in C is easy. And so is Pascal.

    Scanf ():

    Scanf () is a function in C which allows the programmer to accept input from a keyboard.

    Example:

    #include

    main() /* program which introduces keyboard input */{ int number;

    printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); }

    ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD Getchar, Putchar

    getchar() gets a single character from the keyboard, and putchar() writes a single character from the keyboard.

    Example:The following program illustrates this:

    #include main() { int i; int ch;

    for( i = 1; i

  • 8/10/2019 Anna University CP 2 Marks

    21/62

    5. Explain the various decision making mechanism in C. (16) IF STATEMENTS

    The if statements allows branching (decision making) depending upon the value or state of variables. Thisallows statements to be executed or skipped, depending upon decisions. The basic format is,

    if( expression ) program statement;

    Example:

    if( students < 65 )++student_count;

    IF ELSE

    The general format for these is,

    if( condition 1 ) statement1; else if( condition 2 ) statement2;

    else if( condition 3 ) statement3; else statement4;

    The else clause allows action to be taken where the condition evaluates as false (zero).

    The following program uses an if else statement to validate the users input to be in the range 1-10.

    Example:

    #include

    main() { int number; int valid = 0;

    while( valid == 0 ) { printf("Enter a number between 1 and 10 -->"); scanf("%d",&number); if( number < 1 ) {

    printf("Number is below 1. Please re-enter\n"); valid = 0; }

    else if( number > 10 ){

    printf("Number is above 10. Please re-enter\n"); valid = 0; } else valid = 1;

    }

  • 8/10/2019 Anna University CP 2 Marks

    22/62

    printf("The number is %d\n", number ); }

    NESTED IF ELSE

    /* Illustates nested if else and multiple arguments to the scanf function. */

    Example:

    #include

    main() { int invalid_operator = 0; char operator;

    float number1, number2, result;

    printf("Enter two numbers and an operator inthe format\n"); printf(" number1 operatornumber2\n");

    scanf("%f %c %f", &number1, &operator, &number2);

    if(operator == '*') result = number1 * number2; else if(operator == '/') result = number1 / number2; else if(operator == '+')

    result = number1 + number2; else if(operator == '-')

    result = number1 - number2;else invalid_operator = 1;

    if( invalid_operator != 1 ) printf("%f %c %f is %f\n", number1, operator, number2, result );

    else printf("Invalid operator.\n");

    6. With example explain the Branching and Looping mechanism in C (16) ITERATION, FOR LOOPS

    The basic format of the for statement is,

    for( start condition; continue condition; re-evaulation ) program statement;

  • 8/10/2019 Anna University CP 2 Marks

    23/62

    Example:

    /* sample program using a for statement */ #include

    main() /* Program introduces the for statement, counts to ten */{ int count;

    for( count = 1; count

  • 8/10/2019 Anna University CP 2 Marks

    24/62

    Somewhere within the body of the while loop a statement must alter the value of the condition to allow theloop to finish.

    Example:

    /* Sample program including while */#include

    main() { int loop = 0;

    while( loop

  • 8/10/2019 Anna University CP 2 Marks

    25/62

    do { r_digit = value % 10; printf("%d", r_digit); value = value / 10;

    } while( value != 0 ); printf("\n");

    }

    The above program reverses a number that is entered by the user. It does this by using the modulus %

    operator to extract the right most digits into the variable r_digit . The original number is then divided by 10,and the operation repeated whilst the number is not equal to 0.

    SWITCH CASE:

    The switch case statement is a better way of writing a program when a series of if elses occurs. The generalformat for this is,

    switch ( expression ) { case value1:

    program statement; program statement;

    break; case valuen:

    program statement;

    break; default:

    break; }

    he keyword break must be included at the end of each case statement. The default clause is optional,

    and is executed if the cases are not met. The right brace at the end signifies the end of the case

    selections.

    Example:#include

    main()

    {

    int menu, numb1, numb2, total; printf("enter in two numbers -->"); scanf("%d %d",

    &numb1, &numb2 ); printf("enter in choice\n");

    printf("1=addition\n"); printf("2=subtraction\n");

    scanf("%d", &menu );

  • 8/10/2019 Anna University CP 2 Marks

    26/62

    switch( menu )

    {

    case 1: total = numb1 + numb2; break; case 2: total = numb1 -

    numb2; break; default: printf("Invalid option selected\n");

    }

    if( menu == 1 )

    printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 ) printf("%d minus %d is %d\n",

    numb1, numb2, total );

    }

    The above program uses a switch statement to validate and select upon the users input choice, simulating asimple menu of choices.

    7.C programs related to problem solving.

    8..C programs related to scientific problem solving.

  • 8/10/2019 Anna University CP 2 Marks

    27/62

    UNIT -III

    2 MARKS

    1. What is an array?

    An array is a group of similar data types stored under a common name. An array is used to store a

    collection of data, but it is often more useful to think of an array as a collection of variables of the same

    type.

    Example:

    int a[10];

    Here a[10] is an array with 10 values.

    2. What are the main elements of an array declaration?

    Type and

    3. How to initialize an array?

    You can initialize array in C either one by one or using a single statement as follows:

    double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};

    The number of values between braces { } cannot be larger than the number of elements that we declare for

    the array between square brackets [ ]. Following is an example to assign a single element of the array:

    4. Why is it necessary to give the size of an array in an array declaration?

    When an array is declared, the compiler allocates a base address and reserves enough space in the

    memory for all the elements of the array. The size is required to allocate the required space. Thus, the size must

    be mentioned.

    5. What is the difference between an array and pointer?

    Difference between arrays and pointers are as follows.

    Array1.Array allocates space automatically

    2.It cannot be resized.

    3.It cannot be reassigned.

    4.Size of(array name) gives the

    number of bytes occupied by the array.

  • 8/10/2019 Anna University CP 2 Marks

    28/62

    Pointer

    1.Pointer is explicitly assigned to point to an allocated

    space.2.It can be resized using realloc ().3.Pointers can be reassigned.4.Sezeof(pointer name) returns the number of bytesused to store the pointer variable

    6. List the characteristics of Arrays.

    .

  • 8/10/2019 Anna University CP 2 Marks

    29/62

    All elements of an array share the same name, and they are distinguished form one another with help of

    an element number. Any particular element of an array can be modified separately without disturbing

    other elements.

    7. What are the types of Arrays?

    1.One-Dimensional Array

    2. Two-Dimensional Array

    3. Multi-Dimensional Array

    8. Define Strings.

    Strings:

    The group of characters, digit and symbols enclosed within quotes is called as Stirng (or) character

    Arrays. Strings are always terminated with \0 (NULL) character. The compiler automatically adds \0 at

    the end of the strings.

    Example:

    char name[]={C , O , L , L , E , G , E , E , \0 };

    9. Mention the various String Manipulation Functions in C.

    Function & Purposestrcpy(s1, s2); Copies string s2 into string s1.strcat(s1, s2); Concatenates string s2 onto the end of string s1.strlen(s1); Returns the length of string s1.strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1s2.strchr(s1, ch); Returns a pointer to the first occurrence of character ch instring s1.

    strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in strings1.

  • 8/10/2019 Anna University CP 2 Marks

    30/62

    10. What is the use of atoi() function?

    C allows us to manipulate characters the same way we do with numbers. Whenever a character

    constant or character variable is used in an expression, it is automatically converted into integer value by the

    system.

    For eg, if the machine uses the ASCII representation, then,x = a ; printf(%d \n,x);

    will display the number 97 on the screen.

    The C library supports a function that converts a string of digits into their integer values. The

    function takes the formx = atoi(string)11. What is the use of typedef ?

    It is used to create a new data using the existing type.

    Syntax: typedef data type name;

    Example:

    typedef int hours: hours hrs;/* Now, hours can be used as new datatype */

    12. What is meant by Sorting?

    Sorting refers to ordering data in an increasing or decreasing fashion according to some linear relationship

    among the data items. Sorting can be done on names, numbers and records.

    13. What are the types of sorting available in C?

    uick Sort.

    14. Define Heap Sort.

    A sorting algorithm that works by first organizing the data to be sorted into a special type of

    binary tree called a heap. The heap itself has, by definition, the largest value at the top of the

    tree, so the heap sort algorithm must also reverse the order. It does this with the following steps:

  • 8/10/2019 Anna University CP 2 Marks

    31/62

    1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored inan array.

    2. Re-establish the heap.

    3. Repeat steps 1 and 2 until there are no more items left in the heap.

    15. Define Bubble sort.

    A simple but popular sorting algorithm. Bubble sorting is used frequently as a programming exercise

    because it is relatively easy to understand. It is not, however, particularly efficient. Other sorting

    algorithms, such as heap sorts, merge sorts and quick sorts, are used more often in real applications.

    16. Define Searching.

    Searching for data is one of the fundamental fields of computing. Often, the difference between a fast

    program and a slow one is the use of a good algorithm for the data set. Naturally, the use of a hash table

    or binary search tree will result in more efficient searching, but more often than not an array or linked list

    will be used. It is necessary to understand good ways of searching data structures not designed to support

    efficient search.

    17. Mention the various types of searching techniques in C

    18. What is linear search?

    In Linear Search the list is searched sequentially and the position is returned if the key element to be

    searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the

    beginning of an array and move to the end, testing for a match at each item.

    19. What is Binary search?

    A binary search, also called a dichotomizing search, is a digital scheme for locating a specific object in a large

    set. Each object in the set is given a key. The number of keys is always a power of 2. If there are 32 items in

    a list, for example, they might be numbered 0 through 31 (binary 00000 through 11111). If there are, say,

    only 29 items, they can be numbered 0 through 28 (binary 00000 through 11100), with the numbers 29

    through31 (binary 11101, 11110, and 11111) as dummy keys.

  • 8/10/2019 Anna University CP 2 Marks

    32/62

    UNIT III

    16 MARKS

    1. Define array. Explain the array types with an example program for each type.

    Arrays are data structures which hold multiple variables of the same data type. Consider the case where a

    programmer needs to keep track of a number of people within an organization. So far, our initial attempt will be to create a specific variable for each user.

    This might look like,

    int name1 = 101;

    int name2 = 232;

    int name3 = 231;

    It becomes increasingly more difficult to keep track of this as the number of variables increase.Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and

    uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like

    other variables in C, must be declared before they can be used. The replacement of the above example

    using arrays looks like,

    int names[4];

    names[0] = 101;

    names[1] = 232;names[2] = 231;

    names[3] = 0;

    We created an array called names, which has space for four integer variables. You may also see that we

    stored 0 in the last space of the array. This is a common technique used by C programmers to signify the

    end of an array. Arrays have the following syntax, using square brackets to access each indexed value

    (called an element).x[i]

    so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0. Assigning values

    to array elements is done by, x[10] = g; and assigning array elements to a variable is done by, g = x[10]; In the

    following example, a character based array named word is declared, and each

    element is assigned a character. The last element is filled with a zero value, to signify the end of the

    character string (in C, there is no string type, so character based arrays are used to hold strings). A printf

    statement is then used to print out all elements of the array.

  • 8/10/2019 Anna University CP 2 Marks

    33/62

    /* Introducing array's, 2 */

    #include main(){char word[20];word[0] = 'H';word[1] = 'e';

    word[2] = 'l';word[3] = 'l';word[4] = 'o';word[5] = 0;

    printf("The contents of word[] is -->%s\n", word );}

    2. Explain about multi dimensional array with example.

    Multi-dimensioned arrays have two or more index values which specify the element in the array.

    multi[i][j];

    In the above example, the first index value i specifies a row index, whilst j specifies a column index.

    DECLARATION

    int m1[10][10];

    static int m2[2][2] = { {0,1}, {2,3} }; sum = m1[i][j] + m2[k][l];

    NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the

    braces are,

    { 0, 1 },

    { 2, 3 }

    Remember that arrays are split up into row and columns. The first is the row, the second is the column.

    Looking at the initial values assigned to m2, they are,

    m2[0][0] = 0

    m2[0][1] = 1m2[1][0] = 2

    m2[1][1] = 3

  • 8/10/2019 Anna University CP 2 Marks

    34/62

    Example:

    #include

    main()

    {

    static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} }; int row, column, sum;

    sum = 0;

    for( row = 0; row < 4; row++ )

    for( column = 0; column < 3; column++ ) sum = sum + m[row][column];

    printf("The total is %d\n", sum );

    }

    3. Explain String Array with example program.

    CHARACTER ARRAYS [STRINGS] Consider the following program,

    #include

    main()

    {

    static char name1[] = {'H','e','l','l','o'}; static char name2[] = "Hello";

    printf("%s\n", name1);

    printf("%s\n", name2);

    }

    The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in

    name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the initialization can be

    changed to, static char name1[] = {'H','e','l','l','o','\0'};

    Consider the following program, which initialises the contents of the character based array word during the

    program, using the function strcpy, which necessitates using the include file string.h

    Example:#include

    #include

    main()

    {

    Char word[20]; Char word[20]; strcpy(word, "hi there." ) printf("%s\n", word );

    }

  • 8/10/2019 Anna University CP 2 Marks

    35/62

    4. Explain the standard string functions with example to support each type.

    Strings:

    The group of characters, digits and symbols enclosed within quotes is called as strings or character arrays.

    Strings are always terminated with \0 character(NULL).

    Example:

    char name[ ] = {H , E , L , L , O };

    Standard String Functions:

    strlen( )

    strcpy( )

    strncpy( )

    stricmp( )

    strcmp( )

    strncmp( )

    strcat( ) strrev( ) etc.,

    Example:Program

    /*Illustration of string- handling functions*/ #include

    main()

    {

    char s1[20],s2[20],s3[20]; int x, l1, l2, l3;

    printf(Enter two string constants \n); printf(?);

    scanf(%s %s, s1, s2); x = strcmp(s1, s2); if(x != 0)

    printf(Strings are not equal \n); strcat(s1, s2);

    else

    printf(Strings are equal \n); strcpy(s3,s1); l1 = strlen(s1);

  • 8/10/2019 Anna University CP 2 Marks

    36/62

    l2 = strlen(s2);

    l3 = strlen(s3);

    printf( \ns1 = %s \t length = %d characters \ n,s1, l1); printf( \ns2= %s \t length = %d characters \ n,s2, l2);

    printf( \ns3 = %s \t length = %d characters \ n,s3, l3);

    }

    OUTPUT

    Enter two string constants

    ? New York

    Strings are not equal

    s1 = New York length = 7 characters

    s2 = York length = 4 characters

    s3 = New York length = 7 characters

    Enter two string constants? London LondonStrings are equals1 = London length = 6 characterss2 = London length = 6 characterss3 = London length = 6 characters

    5. Write a C program to do the matrix addition using C.

    C program for addition of two matrices using arrays source code. Matrix addition in c language:

    Example Program:

    #include

    int main(){

    int a[3][3],b[3][3],c[3][3],i,j;

    printf("Enter the First matrix->"); for(i=0;i

  • 8/10/2019 Anna University CP 2 Marks

    37/62

    for(i=0;i

  • 8/10/2019 Anna University CP 2 Marks

    38/62

    scanf("%d %d",&o,&p);

    if(n!=o)

    {

    printf("Matrix mutiplication is not possible");

    printf("\nColumn of first matrix must be same as row of second matrix");

    }

    Else

    {

    printf("\nEnter the First matrix->"); for(i=0;i

  • 8/10/2019 Anna University CP 2 Marks

    39/62

    }

    }

    printf("\nThe multiplication of two matrix is\n"); for(i=0;i

  • 8/10/2019 Anna University CP 2 Marks

    40/62

    }

    printf("\n\nTraspose of a matrix is -> "); for(i=0;i

  • 8/10/2019 Anna University CP 2 Marks

    41/62

    UNIT V

    2 MARKS

    1. Compare arrays and structures.

    Comparison of arrays and structures is as follows.

    Arrays Structures

    An array is a collection of data items of same data A structure is a collection of data items of different

    type.Arrays can only be declared. data types. Structures can be declared and defined.

    There is no keyword for arrays. The keyword for structures is struct.

    An array name represents the address of the starting A structrure name is known as tag. It is a

    element.Shorthand notation of the declaration.

    An array cannot have bit fields.

    2. Compare structures and unions.

    Structure

    Every member has its own memory.

    The keyword used is struct.

    All members occupy separate memory location, hence different interpretations of the

    same memory location are not possible.

    Consumes more space compared to union.

    A structure may

    Union

    All members us The keyword us

    Different inter

    location are pos

    Conservation of

    Page 88

  • 8/10/2019 Anna University CP 2 Marks

    42/62

    3. Define Structure in C.

    C Structure is a collection of different data types which are grouped together and each element in a C

    structure is called member.

    structure members in C, structure variable should be declared.

    each separately.

    structure members.

    4. What you meant by structure definition?

    A structure type is usually defined near to the start of a file using a typedef statement. typedef defines and

    names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and

    #include statements in a file.

    Here is an example structure definition.

    typedef struct {

    char name[64];char course[128];

    int age;

    int year;

    } student;

    This defines a new type student variables of type student can be declared as follows.

    student st_rec;

    5. How to Declare a members in Structure?

    A struct in C programming language is a structured (record) type [1] that aggregates a fixed set of labeled

    objects, possibly of different types, into a single object. The syntax for a struct declaration in C is:

    Page 89

  • 8/10/2019 Anna University CP 2 Marks

    43/62

    struct tag_name

    {

    type attribute ;

    type attribute2 ;

    /* ... */

    };

    6. What is meant by Union in C.?

    A union is a special data type available in C that enables you to store different data types in the same

    memory location. You can define a union with many members, but only one member can contain a value

    at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

    7. How to define a union in C.

    To define a union, you must use the union statement in very similar was as you did while defining

    structure. The union statement defines a new data type, with more than one member for your program. The

    format of the union statement is as follows:

    union [union tag ]

    {

    member definition ;

    member definition ;

    member definition ;

    } [one or more union variables ];

    8. How can you access the members of the Union?

    To access any member of a union, we use the member access operator (.). The member access operator is

    coded as a period between the union variable name and the union member that we wish to access. You woulduse union keyword to define variables of union type.

    Page 90

  • 8/10/2019 Anna University CP 2 Marks

    44/62

    9. What are the pre-processor directives?

    10. What are storage classes?

    A storage class defines the scope (visibility) and life time of variables and/or functions within a C

    Program.

    11. What are the storage classes available in C?

    There are following storage classes which can be used in a C Program

    12. What is register storage in storage class?

    Register is used to define local variables that should be stored in a register instead of RAM. This means that

    the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&'

    operator applied to it (as it does not have a memory location).

    {

    register int Miles;

    }

    13.What is static storage class?

    Page 91

  • 8/10/2019 Anna University CP 2 Marks

    45/62

    Static is the default storage class for global variables. The two variables below (count and road) both have a

    static storage class.

    static int Count;

    int Road;

    {

    printf("%d\n", Road);

    }

    14. Define Auto storage class in C.

    auto is the default storage class for all local variables.

    {

    int Count;

    auto int Month;

    }

    The example above defines two variables with the same storage class. auto can only be used within

    functions, i.e. local variables.

    15. Define pre-processor in C.

    The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In

    simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer to the C Preprocessor as the

    CPP.

    Example:

    #define Substitutes a preprocessor macro#include Inserts a particular header from another file

    Page 92

  • 8/10/2019 Anna University CP 2 Marks

    46/62

    16. Define Macro in C.

    A macro definition is independent of block structure, and is in effect from the #define directive

    that defines it until either a corresponding #undef directive or the end of the compilation unit is

    encountered.

    Its format is: #define identifier replacement

    Example: #define TABLE_SIZE 100int table1[TABLE_SIZE];int table2[TABLE_SIZE];

    17. What are conditional Inclusions in Preprocessor Directive?

    Conditional inclusions (#ifdef, #ifndef, #if, #endif, #else and #elif)

    These directives allow including or discarding part of the code of a program if a certain condition is met.

    #ifdef allows a section of a program to be compiled only if the macro that is specified as the parameter has

    been defined, no matter which its value is.

    For example:

    1 #ifdef TABLE_SIZE

    2 int table[TABLE_SIZE];

    3 #endif

    18. What you meant by Source file Inclusion in Preprocessor directive?

    Source file inclusion (#include)This directive has also been used assiduously in other sections of this tutorial. When the preprocessor findsan #include directive it replaces it by the entire content of the specified file. There are two ways to specify afile to be included:

    1 #include "file" 2 #include

    Page 93

  • 8/10/2019 Anna University CP 2 Marks

    47/62

    19. What is Line control?

    Line control (#line)

    When we compile a program and some error happens during the compiling process, the compiler shows anerror message with references to the name of the file where the error happened and a line number, so it is easier

    to find the code generating the error.

    The #line directive allows us to control both things, the line numbers within the code files as well as the file

    name that we want that appears when an error takes place. Its format is:

    #line number "filename"

    Where number is the new line number that will be assigned to the next code line. The line numbers of

    successive lines will be increased one by one from this point on.

    UNIT V

    16 MARKS

    1. Define Structures. Explain structures in detail. (JAN 2009 / MAY2009)

    A structure is a collection of one or more variables of different data types grouped together under a singlename. It contains different data types. C Structure is a collection of different data types which are grouped

    together and each element in a C structure is called member.

    cture variables can be declared for same structure and memory will be allocated for

    each separately.

    structure members.

    Syntax:

    struct struct-name

    {

    type variable 1;

    Page 94

  • 8/10/2019 Anna University CP 2 Marks

    48/62

    type variable 2;

    type variable n;

    } structure_variables;

    Example program for C structure:

    This program is used to store and access id, name and percentage for one student. We can also store and

    access these data for many students using array of structures. You can check C - Array of Structures

    to know how to store and access these data for many students.

    #include #include

    struct student{int id;

    char name[20];float percentage; };

    int main(){struct student record = {0}; //Initializing to null

    record.id=1;strcpy(record.name, "Raju");record.percentage = 86.5;

    printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage);return 0;

    Output:

    Id is: 1 Name is: RajuPercentage is: 86.500000

    Page 95

  • 8/10/2019 Anna University CP 2 Marks

    49/62

    2. Explain Array of structure in C.

    Since structures are data types that are especially useful for creating collection items, why not make a

    collection of them using an array? Let us now modify our above example object1.c to use an array of

    structures rather than individual ones.

    Example Program:

    1. #include

    2. #include

    3.

    4. struct object {

    5. char id[20];

    6. int xpos;

    7. int ypos;

    8. };

    9.

    10. struct object createobj(char id[], int xpos, int ypos);

    11.

    12. void printobj(struct object obj);

    13.

    14. void main() {

    15.

    16. int i;

    17. struct object gameobjs[2];

    18. gameobjs[0] = createobj("player1", 0, 0);

    19. gameobjs[1] = createobj("enemy1", 2, 3);

    20.

    21. for (i = 0; i < 2; i++)

    22. printobj(gameobjs[i]);

    23.

    24. //update enemy1 position

    25. gameobjs[1].xpos = 1;

    26. gameobjs[1].ypos = 2;

    Page 96

  • 8/10/2019 Anna University CP 2 Marks

    50/62

    27.

    28. for (i = 0; i < 2; i++)

    29. printobj(gameobjs[i]);

    30. }

    31.

    32. struct object createobj(char id[], int xpos, int ypos) {

    33. struct object newobj;

    34. strcpy(newobj.id, id);

    35. newobj.xpos = xpos;

    36. newobj.ypos = ypos;

    37. return newobj;

    38. }

    39.

    We create an array of structures called gamobjs and use the createobj function to initilize it's elements.

    You can observer that there is not much difference between the two programs. We added an update for

    the enemy1's position to show how to access a structure's members when it is an element within an array.

    Output:

    3. How can pass a structure to function in C.

    A structure can be passed to any function from main function or from any sub function. Structure definition

    will be available within the function only.

    Page 97

  • 8/10/2019 Anna University CP 2 Marks

    51/62

    It won t be available to other functions unless it is passed to those functions by value or by

    address(reference).

    Else, we have to declare structure variable as global variable. That means, structure variable should bedeclared outside the main function. So, this structure will be visible to all the functions in a C program.

    Passing structure to function in C:

    It can be done in below 3 ways.

    1. Passing structure to a function by value

    2. Passing structure to a function by address(reference)

    3. No need to pass a structure - Declare structure variable as global

    program - passing structure to function in C by value:

    In this program, the whole structure is passed to another function by value. It means the whole

    structure is passed to another function with all members and their values. So, this structure can be

    accessed from called function. This concept is very useful while writing very big programs in C.

    #include

    #include

    struct student{int id;

    char name[20];float percentage; };

    void func(struct student record);

    int main(){

    struct student record;

    record.id=1;strcpy(record.name, "Raju");record.percentage = 86.5;

    Page 98

  • 8/10/2019 Anna University CP 2 Marks

    52/62

    func(record);return 0;}

    void func(struct student record){

    printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name);

    printf(" Percentage is: %f \n", record.percentage);}

    Output:

    Id is: 1

    Name is: Raju

    Percentage is: 86.500000

    4. How can you insert structure with in another structure?

    Structures can be used as structures within structures. It is also called as 'nesting of structures'.

    Syntax:

    struct structure_nm

    { element 1; element 2;----------- ----------- element n;

    struct structure_nm{ element 1; element 2;----------- -----------

    element n;}inner_struct_var;

    }outer_struct_var;

    Page 99

  • 8/10/2019 Anna University CP 2 Marks

    53/62

    Example Program :

    Program to demonstrate nested structures.

    #include

    #include

    struct stud_Res

    {

    int rno;

    char std[10];

    struct stud_Marks

    {

    char subj_nm[30];

    int subj_mark; }marks;

    }result;

    void main()

    {

    clrscr();

    printf("\n\t Enter Roll Number : "); scanf("%d",&result.rno);

    printf("\n\t Enter Standard : "); scanf("%s",result.std);

    printf("\n\t Enter Subject Code : ");

    scanf("%s",result.marks.subj_nm);

    printf("\n\t Enter Marks : ");

    scanf("%d",&result.marks.subj_mark);

    printf("\n\n\t Roll Number : %d",result.rno);

    printf("\n\n\t Standard : %s",result.std);

    printf("\nSubject Code : %s",result.marks.subj_nm);

    00

  • 8/10/2019 Anna University CP 2 Marks

    54/62

    printf("\n\n\t Marks : %d",result.marks.subj_mark);

    getch();

    }

    Output :

    Enter Roll Number : 1

    Enter Standard : MCA(Sci)-I

    Enter Subject Code : SUB001

    Enter Marks : 63

    Roll Number : 1

    Standard : MCA(Sci)-I

    Subject Code : SUB001

    Marks : 63

    5. Explain the concept of pointer to structure.

    C structure can be accessed in 2 ways in a C program. They are,

    1. Using normal structure variable

    2. Using pointer variable

    Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to

    access the data using pointer variable. You have learnt how to access structure data using normal variable

    in C - Structure topic. So, we are showing here how to access structure data using pointer variable in

    below C program.

    01

  • 8/10/2019 Anna University CP 2 Marks

    55/62

    Example program for C structure using pointer:

    In this program, record1 is normal structure variable and ptr is pointer structure variable. As you

    know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to accessdata using pointer variable.

    #include

    #include

    struct student

    {

    int id;char name[30];

    float percentage; };

    int main()

    {

    int i;

    struct student record1 = {1, "Raju", 90.5}; struct student *ptr;

    ptr = &record1;

    printf("Records of STUDENT1: \n");

    printf(" Id is: %d \n", ptr->id);

    printf(" Name is: %s \n", ptr->name);

    printf(" Percentage is: %f \n\n", ptr->percentage);

    return 0;}

    02

  • 8/10/2019 Anna University CP 2 Marks

    56/62

  • 8/10/2019 Anna University CP 2 Marks

    57/62

    union student record2;

    // assigning values to record1 union variable strcpy(record1.name, "Raju");strcpy(record1.subject, "Maths"); record1.percentage = 86.50;

    printf("Union record1 values example\n"); printf(" Name : %s \n", record1.name); printf(" Subject : %s \n", record1.subject); printf(" Percentage : %f \n\n", record1.percentage);

    // assigning values to record2 union variable printf("Union record2 values example\n"); strcpy(record2.name,"Mani");

    printf(" Name : %s \n", record2.name);

    strcpy(record2.subject, "Physics"); printf(" Subject : %s \n", record2.subject);

    record2.percentage = 99.50; printf(" Percentage : %f \n", record2.percentage);return 0;}

    Output:

    Union record1 values example Name :Subject :Percentage : 86.500000

    Union record2 values example Name : ManiSubject : PhysicsPercentage : 99.500000

    04

  • 8/10/2019 Anna University CP 2 Marks

    58/62

    7. What are storage classes? Explain each with example.

    A storage class defines the scope (visibility) and life time of variables and/or functions within a C

    Program.

    There are following storage classes which can be used in a C Program

    extern

    auto - Storage Class

    auto is the default storage class for all local variables.

    {

    int Count;

    auto int Month;

    }

    The example above defines two variables with the same storage class. auto can only be used within

    functions, i.e. local variables.

    register - Storage Class

    register is used to define local variables that should be stored in a register instead of RAM. This means that

    the variable has a maximum size equal to the register size (usually one word) and can t have the unary '&'

    operator applied to it (as it does not have a memory location).

    {

    register int Miles;

    }

  • 8/10/2019 Anna University CP 2 Marks

    59/62

    Register should only be used for variables that require quick access - such as counters. It should also be

    noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it

    MIGHT be stored in a register - depending on hardware and implementation restrictions.

    static - Storage Class

    static is the default storage class for global variables. The two variables below (count and road) both have a

    static storage class.

    static int Count;

    int Road;

    {

    printf("%d\n", Road);

    }

    static variables can be 'seen' within all functions in this source file. At link time, the static variables

    defined here will not be seen by the object modules that are brought in.

    static can also be defined within a function. If this is done the variable is initialized at run time but is not

    reinitialized when the function is called. This inside a function static variable retains its value duringvarious calls.

    void func(void);

    static count=10; /* Global variable - static is the default */

    main()

    {while (count--)

    {

    func();

    }

  • 8/10/2019 Anna University CP 2 Marks

    60/62

  • 8/10/2019 Anna University CP 2 Marks

    61/62

    #define OR |

    #define EQUALS ==

    game_over = TRUE;while( list_pointer != NULL )

    MACROS

    Macros are inline code which is substituted at compile time. The definition of a macro, which accepts an

    argument when referenced,

    #define SQUARE(x) (x)*(x) y = SQUARE(v);

    In this case, v is equated with x in the macro definition of square, so the variable y is assigned the square of v.

    The brackets in the macro definition of square are necessary for correct evaluation.

    The expansion of the macro becomes y = (v) * (v);

    Naturally, macro definitions can also contain other macro definitions,

    #define IS_LOWERCASE(x) (( (x)>='a') && ( (x)

  • 8/10/2019 Anna University CP 2 Marks

    62/62

    #endif

    In the preceding case, the definition of NL and SP will only occur if NULL has been defined prior to the

    compiler encountering the #ifdef NULL statement. The scope of a definition may be limited by

    #undef NULL

    This renders the identification of NULL invalid from that point onwards in the source file.

    Typedef

    This statement is used to classify existing C data types, eg,

    typedef int counter; /* redefines counter as an integer */

    counter j, n; /* counter now used to define j and n as integers */ typedef struct {

    int month, day, year;

    } DATE;

    DATE todays_date; /* same as struct date todays_date */