Programming in C

 What is program? What is programming language?

Program :- 

         A computer program is a sequence of instructions for performing a task designed to solve specific problems. A computer program is a list of instructions that tell a computer what to do. Everything a computer does is done by using a computer program. A computer program is written in a programming language.

Programming Language :- 

            A set of words, symbols and codes used to write programs is called programming language. With the help of programming language, a programmer tells a computer what to do. Some popular computer programming languages are C, C++, Java etc.


___________________________________________________________________________________

Explain different types of computer programming languages.

            There are two main types of computer programming languages.

-> Low-level languages

-> High-level languages.

Low Level Programming Languages :-

            These languages are near to computer hardware and far from human languages. Computer can understand these languages easily. Following are two low-level languages:

-> Machine Language

-> Assembly Language

    Machine Language :-

            A computer language in which instructions are written in binary form (0 and 1) is called machine language.

-> It is the only language that is directly understood by the computer.

-> Machine language is the native language of computer.

    Advantages of Machine Languages:

-> Very fast program execution: Because the machine language is the native language of computer that computers directly understand and execute.

-> There is no need of a translator program, because computer can already understand and execute the machine language instructions directly without the need of translation.

    Disadvantages of Machine Languages:

->Machine Language is difficult to understand

-> Machine Language is difficult to learn

-> Programs of Machine Language are difficult to modify

 Machine Language requires deep knowledge of hardware

 Programs of Machine Language are difficult to remove errors

 Programs of Machine Language are Machine dependent Machine language is also known as first generation language.


Assembly Language :-

     Assembly language is a low-level language.

 In assembly language, symbols are used instead of binary code.

 These symbols are easy to remember.

 For example Add instruction is used to add two numbers.

Assembly language is also known as second generation language


    Advantages of Assembly Langauge:

     Assembly language programs are executed with fast speed

     Assembly language programming is easier to learn, understand and modify than machine language


    Disadvantages of Assembly Language:

     Assembly language programs are machine dependent

     Assembly language programming requires deep knowledge of hardware High Level Programming Languages

     A type of language that is close to human languages is called high level language.

     High-level languages are easy to understand.

     Instructions of these languages are written in English like words e.g. Print, Display, Write etc.


Examples of High Level Programming Languages

 COBOL

 BASIC

 PASCAL

 C

 C++

 JAVA

 Visual Basic


Advantages of High Level Programming Languages:

     High Level Programming Languages are Easy to learn and understand

     Programs written in High Level Programming Languages are Easy to modify

     It is Easy to remove errors in the Programs written in High Level Programming Languages

     Programs written in High Level Programming Languages are Machine independent

     High Level Programming Languages have Better documentation Disadvantages of High Level Programming Languages

     A disadvantage of High Level Programming Languages is slower program execution.

                    High Level Programming Languages provide programming facilities for performing Certain operations.


___________________________________________________________________________________


Explain history of c language.

            C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

HISTORY of C:-

ALGOL:-

        The root of all modern languages is ALGOL. ALGOL is introduced in the early 1960s. ALGOL was the first computer language to use a block structure. ALOGL was widely used in Europe. ALGOL language gave the concept of structured programming to the computer science community.


BCPL:-

            In 1967, Martin Richards developed a language called BCPL. The full form of BCPL is Basic Combined Programming Language. BCPL was developed primarily for writing System software.


B :-

            In 1970, Ken Thompson developed a language called B at Bell Laboratory. Language B has been developed using many features of BCPL.

C:-

            C was evolved from ALGOL, BCPL and B. Dennis Ritchie has developed C Language at Bell Laboratory in 1972. C uses many concepts of ALGOL, BCPL and B languages and added the concept of data types and other powerful features. Unix operating system, which was also developed at Bell Laboratory, was coded almost entirely in C. Today, C is running under a variety of operating system and hardware platforms.


___________________________________________________________________________________


Explain C character set

            The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. However, a subset of characters is available that can be used on most personal, micro, mini and mainframe computers.

The characters in C are grouped into the following categories:

1. Letters :-

        - Uppercase A...Z

        - Lowercase a...z

2. Digits :- 

        - All decimal digits 0...9

3. Special characters :-

          , Comma                                                       . Period

          ; Semicolon

          : Colon

          ? Question Mark

          ‟ Apostrophe

          ” Quotation Mark

          ! Exclamation Mark

          | Pipe

          / Slash

          \ Backslash

          ~ Tilde

          _ Under Score

          $ Dollar Sign

          % Percent Sign

          & Ampersand

          ^ Caret

          * Asterisk

          - Minus Sign

          + Plus Sign

          < Less Than Sign

          > Greater Than Sign

          ( Left Parenthesis

          ) Right Parenthesis

          [ Left Bracket

          ] Right Bracket

          { Left Brace

          } Right Brace

          # Number Sign

          @ At the rate Sign  


4. White spaces:-

          Blank space

          Horizontal tab

          Carriage return

          New line

          Form feed


                The compiler ignores white space unless they are a part of a string constant. White spaces may be used to separate words, but are prohibited (illegal) between the characters of keywords and identifiers.


___________________________________________________________________________________


Explain different types of C Tokens.

C TOKENS :-

            In a paragraph of text, individual words and punctuation marks are called tokens. Similarly, in a program the smallest individual units are known as C tokens. C programs are written using these tokens and the syntax of the language. C has following six types of tokens:

            The smallest individual elements or units in a program are called as Tokens. C has following tokens:

 Identifiers

 Keywords

 Constants

 Operators

 Special characters

 Strings


Identifiers :

            Identifiers in c refer to the name of the variables, functions, arrays,etc. created by the programmer, using the combination of following characters.

                     Alphabets : A to Z (or) a to z

                    Digits : 0 to 9

                    Underscore : _


Keywords :

            Keywords are the words whose meaning has been already explained by the compiler. That means at the time of designing a language, some words are reserved to do specific tasks. Such words are called as keywords (or) reserved words. All C compilers support 32 keywords.


Constants :

            Constants define fixed values, that do not change during the execution of a program. C supports the following constants.

                        Integer constants 

                        Character constants

                        Real or floating constants

                        String constants


Operators:

            Operator is a symbol which performs particular operation. C supports a rich set of operators. C operators can be classified into No of categories. They include arithmetic operators, logical operators, bitwise operators, etc.


Special characters:

                All characters other than alphabets and digits are treated as special characters.

Eg: * , % , $ , { ,etc.


___________________________________________________________________________________

Explain Keyword.

            Every C word is classified as either a keyword. All keywords have fixed meanings and these meanings cannot be changed. Keywords serve as basic building blocks for program statements. All keywords must be written in lowercase. The following shows the C keywords:


            int, float, double, char, unsigned, signed, short, long, if, else, switch, case, default, for, while, do, break, continue, void, return, auto, register, static, extern, struct, union, typedef, const, volatile, enum, goto, sizeof


___________________________________________________________________________________


What is identifier? Write rules for identifier.

            Identifiers refer to the names of variables, functions and arrays. These are userdefined names and consist of a sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters are permitted, although lowercase letters are commonly used. The underscore character is also permitted in identifiers. Underscore character is usually used as a link between two words in long identifiers. Some following rules we have to follow to declare an identifier:

Rules for Identifiers :-

 First character must be an alphabet (or Underscore).

 Must consist letters, digits or underscore.

 Only first 31 characters are significant.

 Cannot use a keyword.

 Must not contain white space.



___________________________________________________________________________________


What is constant? Explain different types of constants.

            Constants in C refer to fixed values that do not change during the execution of the program. C supports following types of constants:

Numeric Constant

        Integer Constant

        Real Constant

Character Constant

        Single Character Constant

        String Constant


___________________________________________________________________________________


What is variable? Write rules to declare variables.

            A variable is a data name that may be used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during execution. A variable name can be chosen by the programmer. Some examples of such variables names are:
                    Average_age
                    dollar
                    counter
                    standard

            As mentioned earlier, variable names may consist of letters, digits, and the underscore (_) character, subject to the following rules:
    1. Variables must begin with a letter. Some systems permit underscore as the first character.
    
    2. ANSI standard recognizes a length of 31 characters. However, length should not be normally more than eight characters, since only the first eight characters are treated as significant by many compilers.
    
    3. Uppercase and lowercase are significant. That is, the variable Total is not the same as total or TOTAL.
    
    4. It should not be a keyword.
    
    5. White space is not allowed.

___________________________________________________________________________________

What is operator? Explain different types of operators available in C language.

            An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulation. C language supports a rich set of built-in operators. Operators are used in programs to manipulate data and variables. C operators can be classified into following types:
     Arithmetic operators
     Relational operators
     Logical operators
     Assignment operators
     Unary operators / Increment and Decrement Operators
     Ternary Operator / Conditional operator
     Bitwise operators
     Special operators

Arithmetic Operators :-
        An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication and division on numerical values (constants and variables).

            Operator         Meaning of Operator
                +                    addition or unary plus
                -                     subtraction or unary minus
                *                    multiplication
                /                     division
              %                     remainder after division( modulo division)



Relational Operators :-
        Relational operators are used for comparison of the values of two operands. For example: checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not etc. Some of the relational operators are (==, > , = , <= ).

        A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. Relational operators are used in decision making and loops.

            Operator         Meaning of Operator         Example
                ==                 Equal to                                5 == 3 returns 0
                >                   Greater than                          5 > 3 returns 1
                <                   Less than                              5 < 3 returns 0
                !=                 Not equal to                          5 != 3 returns 1
                >=                Greater than or equal to        5 >= 3 returns 1
                <=                Less than or equal to             5 <= 3 return 0

Logical Operators :-
            Logical Operators are used to combine two or more conditions. An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.

            Operator         Meaning of Operator                                 Example
                 &&              Logial AND. True only if all                        If c = 5 and d = 2 then, expression                                         operands are true                                          ((c== 5) && (d > 5)) equals to 0.

                  ||                  Logical OR. True only if                              If c = 5 and d = 2 then, expression                                           either one operand is true                            ((c== 5) || (d > 5)) equals to 1.

                  !                 Logical NOT. True only if the                       If c = 5 then, expression ! (c == 5)                                         operand is 0                                                     equals to 0.

Assignment Operators:-
            An assignment operator is used for assigning a value to a variable. The most common assignment operator is =    

            Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error.

            “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Different types of assignment operators are shown below:
                
                        Operator             Example             Same as
                            =                         a = b                    a = b
                           +=                       a += b                 a = a+b
                           -=                        a -= b                  a = a-b
                           *=                       a *= b                  a = a*b
                           /=                        a /= b                   a = a/b
                          %=                       a %= b                a = a%b



Unary Operators / Increment and decrement operators :-
            C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.
            
            Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.

-> C provides shortcuts to add or subtract constant 1 to a variable.

                    Operator            Description             Example
                        ++                     Increment             a++ means a = a + 1
                        --                       Decrement            a-- means a = a - 1

Ternary Operator / Conditional Operator (?:) :-
            A conditional operator is a ternary operator, that is, it works on 3 operands. 
            
        Conditional operator is of the form Expression1 ? Expression2 : Expression3 . Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3. We may replace the use of if..else statements by conditional operators.

-> Conditional Operator Syntax
            conditionalExpression ? expression1 : expression2
   
            The conditional operator works as follows:
 The first expression conditionalExpression is evaluated first. This expression
evaluates to 1 if it's true and evaluates to 0 if it's false.
 If conditionalExpression is true, expression1 is evaluated.
 If conditionalExpression is false, expression2 is evaluated.


Bitwise Operators :-
            During computation, mathematical operations like: addition, subtraction, addition and division are converted to bit-level which makes processing faster and saves power.

            Bitwise operators are used in C programming to perform bit-level operations.

            The bitwise operators operate on integers thought of as binary numbers or strings of bits. These operators let us work with the individual bits of a variable; one common use is to treat an integer as a set of single-bit flags.

                    Operators       Meaning of operators
                            &             Bitwise AND
                            |               Bitwise OR
                            ^              Bitwise exclusive OR
                            ~              Bitwise complement
                           <<             Shift left
                           >>             Shift right

Special Operators :-
            C supports some special operators like ,', and sizeof() operators. 

            The ,', (comma) operator can be used to link the related expression together.

            The sizeof() is a compile time operator and, when used with an operand it returns the numbers of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier.

                    Operator         Description                 Example
                        ,                    Comma Operator         Value=(x=10, y=5, x+y) Results: value=15
                    sizeof()             Sizeof() Operator         k= sizeof(235L)


Comma Operator :-
            Comma operators are used to link related expressions together. 
    
            The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator. Comma acts as both operator and separator.
    -> For example:
                int a, c = 5, d;

The sizeof operator :-
            The sizeof is an unary operator which returns the size of data (constant, variables, array, structure etc).
        
            sizeof is a much used in the C/C++ programming language. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. Basically, sizeof operator is used to compute the size of the variable.

___________________________________________________________________________________

Explain type casting. or Explain type conversion.

-> Implicit Type Conversion :-
            C permits mixing of constants and Variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic conversion is known as implicit type conversion.

            During evaluation it adheres (remains or stays) to very strict rules of type conversion. If the operands are of different types, the „lower‟ type is automatically converted to the „higher‟ type before the operation proceeds. The result is of the higher type.

Note that some versions of C automatically convert all floating-point operands to
double precision.

Explicit Conversion :-
            We have just discussed how C performs type conversion automatically. However, there are instances when we want to force conversion in a way that is different from the automatically conversion. Consider, for example, the calculation of ratio to females to males in a town.
    
                            ratio = female_number/male_number

            Since female_number and male_number are declared as integers in the program, the decimal part of the result of the division would be lost and ratio would represent a wrong figure. The problem can be solved by converting locally one of the variables to the floating point as shown below:
        
                            ratio = (float) female_number/male_number

            The operator (float) converts the female_number to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed in floating point mode, thus retaining the fractional part of result.

->The general form a cast is:
            (type-name) expression

___________________________________________________________________________________

Explain different data types available in C language.

DATA TYPES :-
            C language is rich in its data types. The variety of data types allows the programmer to select the type appropriate to the needs of the application as well as the machine.

-> ANSI C supports three categories of data types:
    1. Primary (or Fundamental) Data Types (int, char, float, double)
    2. Derived Data Types (Array, Function, Structure, Pointer)
    3. User Defined Data Types (typedef, enum)

Primary Data Types :-
            C compiler supports four fundamental data types, namely integer (int), character (char), floating point (float) and double-precision floating point (double). Many of them also offer extended data types such as long int and long double. Primary data types, size they hold in memory, range of the data they can store and format specifiers used for the data type (on 16-bit machines) are given in table below:

-> Fundamental or Primary or Basic Data Types

            Basic Data Type        Size in Memory             Range                         Format Specifier
                char                         1Byte or 8 Bits          -128 to 127                             %c
                int                            2 Bytes or 16 Bits     -32767 to 32768                     %d
               float                         4 Bytes or 32 Bits      3.4E-38 to 3.4E+38                %f
              double                      8 Bytes or 64 Bits      1.7E-308 to 1.7E+308            %lf


User-Defined Type Declaration :-
            C compiler supports two user defined data types like : typedef and enum 
                            
                        typedef data type
    
            C supports a feature known as “type definition” that allows users to define an identifier that would represent an existing data type. The user-defined data type identifier can later be used to declare variables. It takes the general form:

                        typedef type identifier;

            Where type refers to an existing data type and “identifier” refers to the “new” name given to the data type. The existing data type may belong to any class of type, including the user-defined ones. Remember that the new type is “new” only in name, but not the data type. typedef cannot create a new type. Some examples of type definition are:
                        
                        typedef int units;
                        typedef float marks;

enum data type :-
            Another user-defined data type is enumerated data type provided by ANSI standard. It is defined as follows:
                        enum identifier {value1, value2,..... valueN};

            The “identifier” is a user-defined enumerated data type, which can be used to declare variables that can have one of the values enclosed within the braces (known as enumeration constants). After this definition, we can declare variables to be of this “new” type as below:

                        enum identifier v1,v2, .... vN;

            The enumerated variables v1, v2, .... vN can only have one of the values value1, value2, .... valueN.

___________________________________________________________________________________

What is pre-processor? or Explain pre-processor.

            Preprocessor is a program which will executed automatically before passing the source program to compiler. This process is called pre-processing. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control.

            The C Preprocessor is not a part of compiler, it is a separate program invoked by the compiler as the first part of translation.
        
            Commands used in preprocessor are called preprocessor directives and they begin with pound "#" symbol and should be not ended with (;).

#include
    Inserts a particular header from another file.

#define
    Substitutes a preprocessor macro.

___________________________________________________________________________________

What is flow chart? Explain different symbols used to develop flow chart.

            A flowchart is a pictorial (graphical) representation of an algorithm. Programmers often use it as a program-planning tool for visually organizing a sequence of steps necessary to solve a problem using a computer. It uses boxes of different shapes to denote different types of instructions. The actual instructions are written within these boxes using clear and concise (brief) statements. Solid lines having arrow marks connect these boxes to indicate the flow of operation, that is, the exact sequence in which to execute the instructions. The process of drawing a flowchart for an algorithm is known as flowcharting.

Terminal :-

:-  

        The terminal symbol is used to indicate the beginning and the end and the pause of the program logic flow. It is the first symbol and the last symbol in the program logic. We can also use this symbol for halting the program. 


Input/Output :-


            The input/output symbol is used to denote any function of an input/output device in the program. We can use the same symbol both for inputting the data into the program or we want the get some output from the program.


Process :-






            A processing symbol is used in a flowchart to represent arithmetic and data movement instructions. Whatever the logic we want to create. We have to write all the logic to execute into the process symbol.


Decision :-



        The Decision symbol is used in a flowchart to indicate a point at which a decision has to be made. We can also use the symbol to check any condition if we want to check like if condition.


Flow Lines :-



            Flow lines with arrowheads are used to indicate the flow of the flowchart. We can use the flow line to describe our flow whether it is from top to bottom or bottom to top. Or left to right or right to left


Connectors :-

            connectors are the one of the rare use symbol of the flowchart, which is used to connect the two pages but the same program. If any program is longer then the one page then the connector is used to describe the joint of the both the pages and the program.

___________________________________________________________________________________

What is dry run? Explain its use.

            A dry run is the process of a programmer manually working through their code to trace the value of variables. There is no software involved in this process.

            Traditionally, a dry run would involve a print out of the code. The programmer would sit down with a pen and paper and manually follow the value of a variable to check that it was used and updated as expected. It is not uncommon for programmers to carry out a dry run when reading the code on screen rather than using a pen and paper.

            If a programmer found that the value is not what it should be, they are able to identify the section of code that resulted in the error. Characteristics of a dry run are:
 carried out during design, implementation, testing or maintenance
 used to identify logic errors
 they will not find execution errors

___________________________________________________________________________________


What is escape sequence? or Explain escape sequence or Explain backslash
character constants.
    
            C supports some special backslash character constants those are used in output functions. For example, the symbol „\n‟ stands for newline character. A list of such backslash character constants is given in table below. Note that each one of them represents one character, although they consist of two characters. These characters combinations are known as escape sequences.

-> Backslash Character Constants or Escape Sequences :-

                        Constant                     Meaning
                            '\a'                        Audible Alert (Bell)
                            '\b'                       Back Space
                            '\f'                        Form Feed
                            '\n'                       New Line
                            '\r'                        Carriage Return
                            '\t'                        Horizontal Tab
                            '\v'                       Vertical Tab
                            '\' '                       Single Quote
                            '\” '                      Double Quote
                            '\?'                      Question Mark
                            '\\'                       Backslash
                            '\0'                      Null


___________________________________________________________________________________


Explain basic structure of a C program.
            The C Program can be viewed as a group of building blocks of called functions. A function is a subroutine that may include one or more statements designed to perform a specific task. 

-> A C Program may contain one or more sections which are shown in figure below :


DOCUMENTATION SECTION :-
            The documentation section consists of a set of comment lines giving the name of the program, name of the author, Program definition and other details, which the programmer would like to user later.

LINKAGE SECTION :-
            The linkage section provides instructions to the compiler to link functions from the
system library.

DEFINITION SECTION :-
            The definition section defines all symbolic constants.

GLOBAL DECLARATION SECTION :-
            There are some variables those are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. Global Declaration Section also declares all the userdefined functions.

main ( ) FUNCTION SECTION :-
            Every C program must have one main( ) function section. This section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and the closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is the logical end of the program. All statements in the declaration and executable parts end with a semicolon.

SUBPROGRAM SECTION :-
            The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order. All sections except the main and Linkage sections may be absent when they are not required.

___________________________________________________________________________________

Explain Comment in C language.
            The first line beginning with /* and ending with */ is known as comment line. Such comment lines are used to enhance (increase or develop) its readability and understanding. Comment lines are not executable statements and therefore anything between /* and */ is ignored by the compiler. Although comments can appear anywhere, they cannot be nested in C. This means, we cannot have comments inside comments.

The comment line :-
                        /* This /* multi line */ comment style is not valid */
        
                is not valid and therefore this comment line generates an error. Since comments do not affect the execution speed and the size of a compiled program, we should use them freely (liberally) in our programs. Comments help the programmers and other users in understanding the program or code.

There are two style comments available in C language:
1) Single line comment style //
2) Multi line comment style /* */

___________________________________________________________________________________

simple if...else with syntax and example.
            Decision making is an important part of programming. Every programming language supports decision making statements allowing programmers to branch according to the condition. In C programming language, if statement is used to check condition and make decision. The decisions or statements are enclosed inside curly braces, however if only a single statement has to be executed, curly
braces are not mandatory.
    
            if ... else statement is a two way branching statement. It consists of two blocks of statements each enclosed inside if block and else block respectively. If the condition inside if statement is true, statements inside if block are executed, otherwise statements inside else block are executed. Else block is optional and it may be absent in a program.

Syntax of if...else statement :-
if (condition)
{
        statements;
        ... ... ...
}
else
{
        statements;
        ... ... ...
}

Flowchart of if ... else statement :-

Example of if ... else statement :-
    C program to find if a number is odd or even.
    
#include <stdio.h>

int main(){
    int n;
    printf ("Enter any number : ");
    scanf ("%d",&n);

    if(n%2==0){
        printf ("%d is even.", n);
    }
    else{
        printf ("%d is odd.", n);
    }
    return 0;
}


=> Here, a number is entered by user which is stored in n. The if statement checks if the remainder of that number when divided by 2 is zero or not. If the remainder is zero, the number is even which is printed on the screen. If the remainder is 1, the number is odd.


=> Note :- If there is only one statement inside if block, we don't need to enclose it with curly brackets { }.


____________________________________________________________________________________________


Multiple if with syntax and example.

            When a number of conditions are checked, we may use more than one if statements as below:

                if (test–expression1)
                {
                            statement–block1;
                }
                if (test–expression2)
                {
                            statement–block2;
                }
                …
                …
                …
                if (test–expressionN)
                {
                            statement–blockN;
                }

=>  First, test–expression1 is checked. If the condition is true than the statementblock1
is executed, otherwise the statement–block1 is skipped. After that, the
test–expression2 is checked. If the condition is true than the statement-block2 is
executed, otherwise the statement–block2 is skipped and so on. In multiple if
structure, all the conditions written in each if are checked, whether the previous if
is true or false, the next if checked and so on.

Example : program shows the number is positive, negative or zero.

#include <stdio.h>
int main(){
    int n;
    printf ("Enter any number : ");
    scanf ("%d",&n);

    if(n == 0){
        printf ("%d is Zero.", n);
    }
    if(n > 0){
        printf ("%d is Positive.", n);
    }
    if(n < 0){
        printf ("%d is Negative.", n);
    }
    return 0;
}

=> The above program gets a number from the user and displays the message as
POSITIVE if it is greater than 0, as NEGATIVE if it is less than 0 or ZERO if it is 0.

____________________________________________________________________________________________


if...else if...else if...else ladder with syntax and example.

            It is used when more than one condition is to be checked. A block of statement is enclosed inside if, else if and else part. Conditions are checked in each if and else if part. If the condition is true, the statements inside that block are executed. If none of the conditions are true, the statements inside else block are executed. A if ... else if ... else statement must have only one if block but can have as many else if block as required. Else part is optional and may be present or absent.


Syntax of if...else if...else statement :-

if (condition 1)

{

        statements;

        ... ... ...

}

else if (condition 2)

{

        statements;

        ... ... ...

}

... ... ...

... ... ...

else if (condition n)

{

        statements;

        ... ... ...

}

else

{

        statements;

        ... ... ...

}


Flowchart of if ... else if ... else statement :-



Example of if ... else if ... else statement
Example : C program to find if a number is negative, positive or zero.

#include <stdio.h>
int main(){
    int n;
    printf ("Enter any number : ");
    scanf ("%d",&n);

    if(n > 0){
        printf ("%d is Positive.", n);
    }
    else if(n < 0){
        printf ("%d is Negative.", n);
    }
    else{
        printf ("%d is Zero.", n);
    }
    return 0;
}


=> In this program, a number is entered by user stored in variable n.
The if ... else if ... else statement tests two conditions:

    1. n<0: If it is true, "Number is negative" is printed on the screen.     2. n>0: If it is true, "Number is positive" is printed on the screen.     
    If both of these conditions are false then the number is zero. So the
program will print "Number is zero".

____________________________________________________________________________________________


nested if with syntax and example.

            When a if statement is kept inside another if statement, it is called nested if statement. Nested if statements are used if there is a sub condition to be tested. The depth of nested if statements depends upon the number of conditions to be checked.


Syntax of nested if statement :-

if (condition 1)

{

        statements;

        if (sub condition 1)

        {

                statements;

        }

        statements;

}

else if (condition 2)

{

        statements;

        if (sub condition 2)

        {

                statements;

        }

        statements;

}

... ... ...

... ... ...

else

{

        statements;

        if (sub condition n)

        {

                statements;

        }

        statements;

}


Flowchart of nested if statement :-


Example of Nested if statement
Example : C program to check if a number is less than 100 or not. If it is
less than 100 then check if it is odd or even.

#include <stdio.h>
int main(){
    int n;
    printf ("Enter any number : ");
    scanf ("%d",&n);

    if(n < 100){
        printf ("%d is less than  100\n", n);
        if(n%2==0){
            printf ("%d is even.", n);
        }
        else{
            printf ("%d is odd.", n);
        }
    }
    else{
        printf ("%d is equal to or greater than 100\n", n);
    }
    return 0;
}

This program tests two conditions:     1. If the number is less than 100 or not.     2. If the number is less than 100 then is it odd or even.
=> It consists of a nested if statement. The outer if statement checks
whether the number is less than 100 or not. If the number is less than
hundred, another condition i.e. if the number is even or odd is checked
and respective message is displayed.


____________________________________________________________________________________________


switch...case with syntax and example.

We have seen that when one of the many alternatives is to be selected, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes difficult to read and follow. At times, it may confuse even the person who designed it. Fortunately, C has a built-in multi-way decision statement known as a switch. The switch statement tests the value of a given variable ( or expression ) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:

switch ( expression )

{

        case value-1;

                    block-1

                    break;

        case value-2;

                    block-2

                    break;

        ……….

        ……….

        default:

                    default-block

                    break;

}

statement-x;


=> The expression is an integer expression or characters. Value-1, Value-2 ….. are constants or constant expressions ( evaluable to an integral constant ) and are known as case labels. Each of these values should be unique within a switch statement. block-1, block-2 ….. are statement lists and may contain zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon (:).

=>When the switch is executed, the value of the expression is successfully compared against the values value-1, value-2,... If a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed.


=> The break statement at the end of each block signal the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.


=> The default is an optional case. When present, it will be executed if the value of the expression does not match with any of case values. If not present, no action takes place if all matches fail and the control goes to the statement-x.


=>The selection process of switch statement is illustrated in the flow chart shown in figure below:

Rules for switch statement :-
 The switch expression must be an integral type.
 Case labels must be constants or constant expressions.
 Case labels must be unique. No two labels can have the same value.
 Case labels must end with colon.
 The break statement transfers the control out of the switch statement.
 The break statement is optional. That is, two or more case labels may
    belong to the same statements.
 The default label is optional. If present, it will be executed when the
    expression does not find a matching case label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.


Example :-


#include <stdio.h>
int main(){
    int day;
    printf ("Enter Day number between 1 to 7 : ");
    scanf ("%d",&day);

    switch (day)
    {
        case 1:
            printf ("Monday");
            break;
        case 2:
            printf ("Tuesday");
            break;
        case 3:
            printf ("Wednesday");
            break;
        case 4:
            printf ("Thursday");
            break;
        case 5:
            printf ("Friday");
            break;
        case 6:
            printf ("Saturday");
            break;
        case 7:
            printf ("Sunday");
            break;
         default:
            printf ("Invalid Choice");
            break;
    }
    return 0;
}

____________________________________________________________________________________________

ternary operator or conditional operator with syntax and example.

                                THE ? : OPERATOR

            The C language has an unusual operator, useful for making two-way decisions. This operator is a combination of ? and :, and takes three operands. This operator is popularly known as the conditional operator. The general form of use of the conditional operator is as follows :

            Conditional expression ? expression1 : expression2

            The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated and its value is returned. For example, the segment

                If (x<0)

                        Flag=0;

                Else

                        Flag=1;

Can be written as

            Flag=(x<0) ? 0:1;

            The conditional operator may be nested for evaluating more complex assignment decisions. 

            It is better to use if statements when more than a single nesting of conditional operator is required.


____________________________________________________________________________________________

while loop with syntax and example.

             In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.


How it Works :-

            The below diagram depicts a loop execution,



 As per the above diagram, if the Test Condition is true, then the loop is executed,
and if it is false then the execution breaks out of the loop. After the loop is
successfully executed the execution again starts from the Loop entry and again
checks for the Test condition, and this keeps on repeating.

=> The sequence of statements to be executed is kept inside the curly braces {} known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When thecondition check returns false, the loop body is not executed, and execution breaks out of the loop.


=> The simplest of all the looping structures in C is the while statement. We may use
while in many of our programs. The basic format of while statement is:

        while (test condition)
        {
                body of the loop;
        }

=> The while is an entry-controlled (Pre Tested) loop statement. The test-condition is evaluated (checked) and if the condition is true, then the body of the loop is executed. After execution of the body, the test-condition is once again evaluated (checked) and if it is true, the body of the loop is executed once again. This process of repeated execution of the body continues until the test-condition becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop. 

=>The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice
to use braces even if the body has only one statement. 

=> We can write the program of the sum of 1 to n numbers as follows:

        sum = 0;

        n = 1; /* Initialization */

        while(n <= 10) /* Testing */

        {

                sum = sum + n;

                n = n + 1; /* Incrementing */

        }

        printf(“Sum =%d\n”, sum);

      

=>  The body of the loop is executed 10 times for n = 1, 2, 3,…10, each time adding the value of n, which is incremented inside the loop. The test condition may also be written as n < 11, the result would be the same. This is a typical example of counter-controlled loop. The variable n is called counter or control variable.


____________________________________________________________________________________________


for loop with syntax and example.

  The for loop is another entry-controlled (Pre Tested) loop that provides a more concise (brief, short) loop control structure. The general from of the for loop is:

    for ( Initialization ; Test-Condition ; Increment / Decrement )

    {

                body of the loop;

    }


=> The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment statements such as a=1 or count = 0. The variables a and count are known as loopcontrol variables.

2. The value of the control variable is tested using the test-condition. The testcondition is a relational expression, such as a<=10 that determines when the loop will exit. If the condition is true, the body of the loop is executed, otherwise the loop is terminated and the execution continues with the statement that immediately follows the for loop.

3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such as a=a+1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test-condition.


Consider the following segment of a program:

    for (x = 1 ; x <= 10; x = x + 1)

    {

            printf(“\n%d”, x);

    }

    printf(“\nEnd of the Loop”);


=> This for loop is executed 10 times and prints the digits 1 to 10 on new line. The three sections enclosed within parentheses must be separated by semicolons. Note that there is no semicolon at the end of the increment / decrement section, x = x + 1.


=> The for statement allows for negative increments. For example, the loop discussed above can be written as follows:

    for (x =10; x >= 1; x=x-1)

            printf(“\n%d”,x);

    

    printf(“\nEnd of the loop”);


=> This loop is also executed 10 times, but the output would be from 10 to 1 instead of 1 to 10. Note that braces are optional when the body of the loop contains only one statement. Since the conditional test is always performed at the beginning of the loop, the body of the loop may not be executed at all, if the condition fails at the start. For example:

            for (x = 10; x < 10; x = x-1 )

                        printf(“%d”, x);


=> will never be executed because the test condition fails at the very beginning itself. Let us consider the problem of sum of integers. This problem can be coded using the for statement as follows:

            sum = 0;

            for (n = 1; n <= 10; n = n + 1)

            {

                            sum = sum + n;

            }

            printf(“Sum = %d\n”, sum);

    

=> The body of the loop

            sum = sum + n;

        

            is executed 10 times for n=1,2,….10 each time incrementing the sum by the value of n.


=> One of the important points about the for loop is that all the three actions, namely initialization, testing, and incrementing, are placed in the for statement itself, thus making them visible to the programmers and users, in one place.


____________________________________________________________________________________________


do...while loop with syntax and example.

 The while and for loop constructs make a test of condition before the loop is executed. Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. This takes the form:


                do

                {

                                body of the loop;

                }

                while ( test-condition );


=> On reaching the do statement, the program processed to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated (checked). If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes (transfers) to the statement that appears immediately after the while statement.

=>  Since the test-condition is evaluated at the bottom of the loop, the do…while construct provides an exit-controlled (Post Tested) loop and therefore the body of the loop is always executed at least once. A simple example of a do….while loop is:

                do

                {

                            printf(“Input a number \n”);

                            scanf(“%d”, &number);

                } while (number > 0 ) ;


=> This segment of a program reads a number from the keyboard until a zero or a negative number is entered, and assigned to the variable number. The test conditions may have compound relations as well. For instance, the statement

                    while ( number > 0 && number < 100 );


=> In the above example would cause the loop to be executed as long as the number keyed in lies between 0 and 100.

                I = 1; /* Initializing */

                sum = 0;

                do

                {

                            Loop sum = sum +I;

                            I = I + 2; /* Incrementing */

                } while(sum < 40 || I < 10); /* Testing */

                printf(“\n%d \t %d”, I, sum);


=> The loop will be executed as long as one of the two relations is true.


____________________________________________________________________________________________


What is infinite loop?

                A loop becomes an infinite loop if a condition never becomes false.


____________________________________________________________________________________________

nested loop.

 Nesting of loops, that is, one for statement within another for statement is allowed in C. 

=> For example, two loops can be nested as follows:

for ( a = 1 ; a < 10 ; ++a)

{                                                                                                        //Outer loop

            statements ;

            for ( b = 1 ; b ! = 5; ++b)

            {                                                                                            // Inner loop 

                        statements;

            }

            statements;

}


=> The nesting may continue up to any desired level. The loops should be properly indented so as to enable the reader to easily determine which statements are continued within each for statement.

=> The program to print the multiplication table can be written more concisely using nested for statements as follows:

for (row = 1; row <= ROWMAX ; ++row)

{

            for (column = 1; column <= COLMAX ; ++column)

            {

                        y = row * column ;

                        printf(“%4d”, y);

            }

            printf(“\n”);

}


=> The outer loop controls the rows while the inner loop controls the columns

____________________________________________________________________________________________

break jumping statement with example.

              Break statement terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

=> When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.



____________________________________________________________________________________________

goto jumping statement with example.

             Goto statement Transfers control to the labeled statement.

=>  So far we have discussed ways of controlling the flow of execution based on certain specified conditions. Like many other languages, C supports the goto statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use the of goto might be desirable.

=> The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label are shown below:


=> The label: can be anywhere in the program either before or after the goto label; statement. During running of a program when a statement like 

                goto begin; 

            is met, the flow of control will jump to the statement immediately following the label begin:. This happens unconditionally.


=> Note that a goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as a backward jump.


=> On the other hand, if the label: is placed after the goto label; some statements will be skipped and the jump is known as a forward jump.

=> A goto is often used at the end of a program to direct the control to go to the input statement, to read further data. Consider the following example:

main( )

{

        double x, y;

        read:

        scanf( “%f ”, &x );

        if (x < 0) go to read;

        y = sqrt(x);

        printf(“%f %f \n”, x ,y);

       go to read


=> This program is written to evaluate the square root of a series of numbers read from the terminal. The program uses two goto statements, one at the end, after printing the results to transfer the control back to the input statement and the other to skip any further computation when the number is negative.

=> Due to the unconditional goto statement at the end, the control is always transferred back to the input statement. In fact, this program puts the computer in a permanent loop known as an infinite loop. The computer goes round and round until we take some special steps to terminate the loop. Such infinite loops should be avoided. Example following illustrates how such infinite loops can be eliminated.

Example :-

            Another use of the goto statement is to transfer the control out of a loop (or nested loops) when certain peculiar conditions are encountered. Example:


-------------

while (-----)

{

            for (-----)

            {

               ----------

               if (-----) goto end_of_program;

                ----------

            }

            -----------

            -----------

}

end_of_program:


=> We should try to avoid using goto as far as possible. But there is nothing wrong, if we use it to enhance the readability of the program or to improve the execution speed.

____________________________________________________________________________________________

What is array? How to declare an array? How to initialize an array?

            An array is a collection of data items, all of the same type, accessed using a common name.

Example where arrays are used,

     to store list of Employee or Student,

     to store marks of students,

     or to store list of numbers or characters etc.


Declaring an Array :-

             Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.

             Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.

            

            Like any other variable, arrays must be declared before they are used. General form of array declaration is,

                                            data-type array-name[array-size];

            Example of array declaration

                                            int arr[10];


Initialization of an Array:-

            After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime.


Compile time Array initialization

            Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is,

                                            data-type array-name[size] = { list of values };

                                            int marks[4]={ 67, 87, 56, 77 }; // integer array initialization

                                            float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization

____________________________________________________________________________________________

Explain different types of arrays.

            Arrays are Set of Elements having same data type or we can Say that Arrays are Collection of Elements having same name and same data type But Always Remember Arrays are Always Start From its index value and the index of array is start From 0 to n-1.

            Suppose we wants to Access 5th Element of array then we will use 4th Element Because Arrays are Start From 0 and arrays are always stored in Continuous Memory Locations The Number of Elements and Types of array are Identified by Subscript of array Elements. The Various types of Array

those are provided by c as Follows:-

1. Single Dimensional Array

2. Two Dimensional Array

3. Three Dimensional array

4. Character Array or Strings.



1) Single Dimensional Array :-

            A dimensional is used representing the elements of the array for example int a[5];

            The [] is used for dimensional or the sub-script of the array that is generally used for declaring the elements of the array For Accessing the Element from the array we can use the Subscript of the Array like this a[3]=100

            This will set the value of 4th element of array

            So there is only the single bracket then it called the Single Dimensional Array

            This is also called as the Single Dimensional Array

2) Two Dimensional Array or the Matrix :-

            The Two Dimensional array is used for representing the elements of the array in the form of the rows and columns and these are used for representing the Matrix A Two Dimensional Array uses the two subscripts for declaring the elements of the Array Like this

                                                        int a[3][3];


            So This is the Example of the Two Dimensional Array In this first 3 represents the total number of Rows and the Second Elements Represents the Total number of Columns The Total Number of elements are judge by Multiplying the Numbers of Rows * Number of Columns in The Array in the above array the Total Number of elements are 9

3) Multidimensional or the Three Dimensional Array :- 

            The Multidimensional Array are used for Representing the Total Number of Tables of Matrix A Three dimensional Array is used when we wants to make the two or more tables of the Matrix Elements for Declaring the Array Elements we can use the way like this

                                        int a[3][3][3];

            In this first 3 represents the total number of Tables and the second 3 represents the total number of rows in the each table and the third 3 represents the total number of Columns in the Tables

            So this makes the 3 Tables having the three rows and the three columns

            The Main and very important thing about the array that the elements are stored always in the Contiguous in the memory of the Computer

4) Character Array of String: -

            Like an integer characters are also be in the Array The Array of Characters are called as the Strings They are Generally used for representing the Strings Always Remember that a String is Terminated with the \0 or Null Character There are the built in string Operation those are provided by the C Language in the String.h Header file Like

i) strLen For Getting the Length or Total Numbers of Characters in String

ii) strcat This is Used for Joining the two Strings or This function is used for Concatenating the two Strings.

iii) strRev This Function is used for obtaining the Reverse of the String

iv) strcmp This Function is used for Comparing the Two Strings and it gives us the Result as follows after comparing the Two Strings

___________________________________________________________________________________

What is structure? How to declare and initialize structure?

            Structure is a group of variables of different data types represented by a single name. Let’s take an example to understand the need of a structure in C programming.

            Let’s say we need to store the data of students like student name, age, address, id etc. One way of doing this would be creating a different variable for each attribute, however when you need to store the data of multiple students then in that case, you would need to create these several variables again for each student. This is such a big headache to store data in this way.

            We can solve this problem easily by using structure. We can create a structure that has members for name, id, address and age and then we can create the variables of this structure for each student. This may sound confusing, do not worry we will understand this with the help of example.

How to create a structure in C Programming

            We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type.

struct struct_name {

    DataType member1_name;

    DataType member2_name;How to declare variable of a structure?

struct struct_name var_name;

or

struct struct_name {

    DataType member1_name;

    DataType member2_name;

    DataType member3_name;

    DataType member3_name;

    

};

            Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.

            First we will see the syntax of creating struct variable, accessing struct members etc and then we will see a complete example.

How to declare variable of a structure?

struct struct_name var_name;

or

struct struct_name {

    DataType member1_name;

    DataType member2_name;

    DataType member3_name;

    

} var_name;

How to access data members of a structure using a struct variable?

var_name.member1_name;

var_name.member2_name;

How to assign values to structure members?

There are two ways to do this.

1) Using Dot(.) operator

var_name.memeber_name = value;

2) All members assigned in one statement

struct struct_name var_name =

{value for memeber1, value for memeber2 …so on for all the members}

___________________________________________________________________________________

Explain array within structure with example.

            C permits use of arrays are structure members. Similarly, we can use singledimension or multi-dimensional arrays of type int or float or char or any type as member variables in a structure. Let’s see how to declare Arrays within Structures.

For example, the following structure declaration is valid.

struct{

    int num;

    float sub[3]; //Array within structure

}student[2]={0,{0,0,0}}; //Initialize Array within Structure

Accessing Arrays within Structures

            Here, the member sub contains three elements, sub[0], sub[1] and sub[2]. Now, student[1].sub[2]; will refer to the marks obtained by the second student in the third subject.

Arrays within Structures Example

#include <stdio.h>

void main()

{

        struct

{

int sub[3]; //Declaring Array within Structure

int total;

}student[3]; //Declaring Array of Structure

int a;

clrscr();

printf("Enter student marks :\n");

for(a=0;a<3;a++)

{

printf("\nStudent %d\n",a+1);

printf("Subject 1 : ");

scanf("%d",&student[a].sub[0]);

printf("Subject 2 : ");

scanf("%d",&student[a].sub[1]);

printf("Subject 3 : ");

scanf("%d",&student[a].sub[2]);

student[a].total=student[a].sub[0] + student[a].sub[1] + student[a].sub[2];

}

printf("\nTotal marks :\n");

printf("Student 1 : %d\n",student[0].total);

printf("Student 2 : %d\n",student[1].total);

printf("Student 3 : %d\n",student[2].total);

getch();

}

___________________________________________________________________________________

Explain array of structure with example.

            Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.

Let's take an example:

struct car

{

    char make[20];

    char model[30];

    int year;

};

Here is how we can declare an array of structure car.

struct car arr_car[10];


            Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to store 10 structure variables of type struct car. To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.) operator as usual.

arr_stu[0] : points to the 0th element of the array.
arr_stu[1] : points to the 1st element of the array.
and so on. Similarly,
arr_stu[0].name : refers to the name member of the 0th element of the
array.
arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the
array.
arr_stu[0].marks : refers to the marks member of the 0th element of the
array.
#include<stdio.h>
#include<string.h>
#define MAX 2
struct student

{

char name[20];

int roll_no, i;

float marks;

};

int main()

{

struct student arr_student[MAX];

int i;

for(i = 0; i < MAX; i++ )

{

printf("\nEnter details of student %d\n\n", i+1);

printf("Enter name: ");

scanf("%s", arr_student[i].name);

printf("Enter roll no: ");

scanf("%d", &arr_student[i].roll_no);

printf("Enter marks: ");

scanf("%f", &arr_student[i].marks);

}

printf("\n");

printf("Name\tRoll no\tMarks\n");

for(i = 0; i < MAX; i++ )

{

printf("%s\t%d\t%.2f\n",

arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks);

}

// signal to operating system program ran fine

return 0;

}

___________________________________________________________________________________

Explain Nested structure.

            When a structure is within another structure, it is called Nested structure. A structure variable can be a member of another structure and it is represented

as

struct student

{

    int rollno;

    struct marks

    {

        int m1, m2, m3;

    }var1;

}var2;


It is possible to define structure outside & declare its variable inside other structure.

struct marks

{

    int m1, m2, m3;

};

struct student

{

    int rollno;

    struct marks var1;

}var2;


___________________________________________________________________________________

What is union? Write difference between structure and union.

            Union is derived data type contains collection of different data type or different elements. All definition declaration of union variable and accessing member is similar to structure, but instead of keyword struct the keyword union is used, the

main difference between union and structure is

            Each member of structure occupy the memory location, but in the unions members share memory. Union is used for saving memory and concept is useful when it is not necessary to use all members of union at a time.

            Where union offers a memory treated as variable of one type on one occasion where (struct), it read number of different variables stored at different place of memory.

Syntax of union:

union union_name

{

    datatype member1;

    datatype member2;

};

___________________________________________________________________________________

What is function? Explain different types of functions.

            A function is a self-contained block of code that performs a particular task. 

            C functions can be classified into two categories namely library functions and user defined functions. The main distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program.

            Whenever we develop our program we write main() function. This is a user defined function. Every program must have a main function to indicate where the program has to begin its execution.

The general form of the function is:

Return_type function_name (argument-list)

{

    local variable declaration;

    executable statements;

    return (expression);

}

            Argument list and argument declaration are optional, it depends on the calling function. Local variable declaration is required only when any local variable are used in the function. A function may or may not send back any value to the calling function. If it does, it does it through the return statement. While it is possible to pass to the called function, any number of values, the called function can return one value per call at the most. The return statement can take the following form

                return (expression);

            The above statement returns the value of the expression to the calling function.

            The return statement is the mechanism for returning a value to the calling function.

            This is also an optional statement and its absence indicates that no value is being returned to the calling function.

Each function has the following parts:

Function prototype

            A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.

            A function prototype gives information to the compiler that the function maylater be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2,...);

            The function prototype is not needed if the user-defined function is defined before the main() function.

Calling a function

            Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

            functionName(argument1, argument2, ...);

Function definition

            Function definition contains the block of code to perform a specific task.

Syntax of function definition

returnType functionName(type1 argument1, type2 argument2, ...)

{

//body of the function

}

            When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.

___________________________________________________________________________________

Explain different types of User Defined Functions.

Category of user defined functions:

            Depending on the conditions like whether the arguments are passed to the called function and whether the called function is returning the value back to the calling function, the functions are categorized into following categories.

(i) Functions without arguments and without any return value.

            In this the calling function is not passing any arguments to the called function and the called function is not returning back any value to the calling function.

Example:

#include<stdio.h>

void main ( )

{

    void message();

    printf ("I am in MGM College\n");

    message ( );

}

void message ( )

{

    printf ("I am in C class \n');

}

            In the above program the function message() is called from main(). The function main() is not passing any value to the function message() and function message() is also not returning back any value to the function main().

(ii) Function without arguments and with Return value

            In this method, We don’t pass any arguments to the function while defining, declaring or calling the function. This type of functions will return one value when we call the function from main() or any sub function. Data Type of the return value will depend upon the return type of function declaration. For instance, if the return type is int then return value will be int.

#include<stdio.h>

void main ()

{

    int ans;

    int multi();

    ans = multi();

    printf ("Result is %d", ans);

}

int multi ()

{

    int x,y,z;

    x=5;

    y=6;

    z = x*y;

    return z;

}

            In this program, We are going to calculate the multiplication of 2 integer values using the user defined function without arguments and return keyword.

(iii) Functions with arguments and without any return value.

            In this, the calling function is passing one or more arguments to the called function and the called function is not returning back any values to the calling function.

#include<stdio.h>

void main ()

{

    int a, b;

    void add();

    a = 5;

    b = 6;

    add(a,b);

}

void add (int x, int y)

{

    int z;

    z = x+y;

    printf ("Result is %d \n", z);

}

            In the above program the function main() passes two arguments a and b to the function add(). But the function add() does not return any value back to the function main().

Note :

In the above example add() is called function and main() is the calling function.

(iv) Functions with arguments and with return value.

            In this the calling function is passing one or more arguments to the called function and the called function will return back one value to the calling function.

# include <stdio.h>

void main ( )

{

    int a, b, c;

    int add();

    a = 5;

    b = 6;

    c = add (a, b);

    printf ("In main %d\n",c);

}

add (int x, int y)

{

    int z;

    z = x+y;

    printf ("Result in function %d\n",z);

    return (z);

}

                In the above program the function main() passes two arguments a and b to function add() and the values are received in the function add() through the variables x and y. The variable z is local to the function add(). The function add() returns the result back to the main() through the variable z and it is received at the function main() though the variable c.

Note:

In the above program, the arguments a and b are known as actual arguments and arguments x and y are known as formal arguments. The values of actual arguments are copied to formal arguments when the functions is called.

Note:

Wherever function is not returning any value back to the main function we have used the return type as void.

___________________________________________________________________________________

Explain call by value and call by reference.

Functions

            We often write large programs and it is a good idea to split large progrmas into smaller procedures. These small procedure blocks are known as functions. Functions are often required to do repetitive jobs. We can define a function and call them from anywhere we need. This is a good choice for code reuse and code size optimization.

Arguments

            Functions are generally written for a particular operation with one or more inputs. Like we write a function to check if the number is prime or not. Here we write a logic which is not dependent on any specific number but can be used for any positive integers. We reuse this logic by providing an input number. This input is called function argument.

Function call and return

            Arguments are small set of variables, temporarily stored in current context of stack. Compiler passes these arguments to calling function by pushing the variables to the stack from right side to left side. Passing variables are similar to coping the variables to a temporary place. Stack grows as compiler pushes more arguments. Finally it pushes the return address and jumps to the function. Now function can do its operation and return from the context. Return statement causes microprocessor to pop the return address from the stack and jumps back to caller. Compiler further shrinks the stack and rewinds to caller context.

Call by value

            In call by value mechanism, the called function creates a new set of variables in stack and copies the values of the arguments into them.

Example: Program showing the Call by Value mechanism.

Call by value source code

void swap(int x, int y)

{

    int z;

    z = x;

    x = y;

    y = z;

    printf("Swapped values are a = %d and b = %d", x, y);

}

int main (int argc, char *argv[])

{

    int a = 7, b = 4;

    printf("Original values are a = %d and b = %d", a, b);

    swap(a, b);

    printf("The values after swap are a = %d and b = %d", a, b);

}

Output

Original Values are a = 7 and b = 4

Swapped values are a = 4 and b = 7

The values after swap are a = 7 and b = 4

            This happens because when function swap() is invoked, the values of a and b gets copied onto x and y. The function actually swaps x and y while the values of the original variables a and b remain intact.

Call by value flow diagram

            Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (a, b) can be split into some assembly steps like-

1. push value of b

2. push value of a

3. save return address

4. call function


            Here one point to note is x and y are in stack. Value of a and b will be copied to x and y. Inside swap() value of x and y will be interchanged but it will not affect a and b in the main(). Please note a and b are located at the context of main() whereas x and y located at the context of swap(). When swap() function returns, this context of x and y will be lost and it will again come back to the context of a and b.

Call by reference
            In call by reference mechanism, instead of passing values to the function being called, references/pointers to the original variables are passed. Example: Program interchange values of two variables by call by reference
mechanism.
Call by reference source code
void swap(int *x, int *y)
{
    int z;
    z = *x;
    *x = *y;
    *y = z;
    printf("Swapped values are a = %d and b = %d", *x, *y);
}
int main (int argc, char *argv[])
{
    int a = 7, b = 4;
    printf("Original values are a = %d and b = %d", a, b);

    swap(&a, &b);

    printf("The values after swap are a = %d and b = %d", a, b);

}

Output

Original Values are a = 7 and b = 4

Swapped values are a = 4 and b = 7

The values after swap are a = 4 and b = 7

            This happens because when function swap() is invoked, it creates a reference for the first incoming integer a in x and the second incoming integer b in y. Hence the values of the original variables are swapped.

Call by reference flow diagram

            Here is the flow diagram describing disassembly steps, call stack and argument variables. Calling swap (&a, &b) can be split into some assembly steps like- 

1. push address of b

2. push address of a

3. save return address

4. call function


            Here one point to note is x and y are pointers. Address of a and b will be copied to x and y. Inside swap() values of pointers will be interchanged. Dereferencing "x" which is same as accessing "a" and the same is true for y. Dereferencing addresses at x and y is same as accessing a and b accordingly. Thus values of a and b will be interchanged after the return of swap().

What is the difference between Call by Value and Call by Reference?

            When using Call by Value, you are sending the value of a variable as parameter to a function, whereas Call by Reference sends the address of the variable. Also, under Call by Value, the value in the parameter is not affected by whatever operation that takes place, while in the case of Call by Reference, values can be affected by the process within the function.

___________________________________________________________________________________

Explain recursion with an example.

            Recursive function is that function which calls itself inside its body. In computer science recursion is very necessary for solving a problem which has the recursive nature.

            Take for example we want to calculate the factorial of a positive integer. In mathematics

                        Factorial (n) = 1 * 2 * 3 .. n; Factorial (n) = n * Factorial (n -1);

            Here the problem of factorial of an integer has a problem domain of factorial (n-

1) inside it. To solve this recursive nature of this problem we can we can call the function itself inside the function body of factorial calculation. Code:

unsigned int factorial(unsigned int n )

{

    if ( n <= 1 )

    {

            return 1;

    }

    else

    {

            return n * factorial(n - 1);/*Call itself*/

    }

}

Advantages and Limitation:

One major advantage of recursion is that it reduces the code complexity. It reduces loop statements and makes code easy to understand.

 However it has a major limitation regarding the stack usage. Every call inside the function takes extra stack frames. When inner call goes further inside, call stack grows accordingly.

___________________________________________________________________________________

Explain different storage classes.

            Every variable in C programming has two properties: type and storage class.

            Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable.

There are 4 types of storage class:

1. automatic

2. external

3. static

4. register

Local Variable (automatic)

            The variables declared inside the function are automatic or local variables. The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed.

int main()

{

    int n; // n is a local variable to main() function

    ... .. ...

}

void func()

{

    int n1; // n1 is local to func() function

}

            In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.

Global Variable (external)

            Variables that are declared outside of all functions are known as external variables. External or global variables are accessible to any function.

Example : External Variable

#include <stdio.h>

void display();

int n = 5; // global variable

int main()

{

++n; // variable n is not declared in the main() function

display();

return 0;

}

void display()

{

    ++n; // variable n is not declared in the display() function

    printf("n = %d", n);

}

Output

n = 7

            Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the compiler will complain. To solve this problem, keyword extern is used infile2 to indicate that the external variable is declared in another file.

Register Variable

            The register keyword is used to declare register variables. Register variables were supposed to be faster than local variables. However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster. Unless you are working on embedded system where you know how to optimize code for the given application, there is no use of register variables.

Static Variable

            A static variable is declared by using keyword static. For example;

static int i;

The value of a static variable persists until the end of the program.

Example : Static Variable

#include <stdio.h>

void display();

int main()

{

    display();

    display();

}

void display()

{

    static int c = 0;

    printf("%d ",c);

__c += 5;

}

Output

0 5

During the first function call, the value of c is equal to 0. Then, it's value is

increased by 5.

During the second function call, variable c is not initialized to 0 again. It's

because c is a static variable. So, 5 is displayed on the screen.

_________________________________________________________________________________

Explain passing an array to a User Defined Function (UDF) with example

            To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

                                                                functionName(arrayname); //passing array

            There is following way to declare function that has array as argument.

return_type function(dataType [])

C language passing array to a function example

#include<stdio.h>

int minarray(int arr[],int size)

{

    int min=arr[0];

    int i=0;

    for(i=1;i<size;i++)

    {

        if(min>arr[i])

        {

            min=arr[i];

        }

    }//end of for

    return min;

}//end of function

void main()

{

    int i=0,min=0;

    int numbers[]={4,5,7,3,8,9};//declaration of array

    min=minarray(numbers,6);//passing array with size

    printf("minimum number is %d \n",min);

}

Pass Entire array

 Here entire array can be passed as a argument to function .

 Function gets complete access to the original array .

 While passing entire array Address of first element is passed to function , any changes made inside function , directly affects the Original value .

 Function Passing method : “Pass by Address“

_________________________________________________________________________________

Explain passing a structure to a User Defined Function (UDF) with example.

            You can pass a structure as a function argument in the same way as you pass any other variable or pointer.

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

 Structure should be declared outside the main function. So, this structure will be visible to all the functions in a C program.

Example:

#include <stdio.h>

#include <string.h>

struct Books

{

    char title[50];

    char author[50];

    char subject[100];

    int book_id;

};

void main( )

{

    void printBook( struct Books book );

    struct Books Book1; /* Declare Book1 of type Book */

    strcpy( Book1.title, "C Programming");

    strcpy( Book1.author, "Y. Kanetkar");

    strcpy( Book1.subject, "C Programming Tutorial");

    Book1.book_id = 14235;

    printBook( Book1 );

    getch();

}

void printBook( struct Books book )

{

    printf( "Book title : %s\n", book.title);

    printf( "Book author : %s\n", book.author);

    printf( "Book subject : %s\n", book.subject);

    printf( "Book book_id : %d\n", book.book_id);

}

_________________________________________________________________________________

What are header files and what are its uses in C programming?

            Header files are also known as library files. They contain two essential things: the definitions and prototypes of functions being used in a program. Simply put, commands that you use in C programming are actually functions that are defined from within each header files. Each header file contains a set of functions. For example: stdio.h is a header file that contains definition and prototypes of commands like printf and scanf.

_________________________________________________________________________________

Explain following library functions:Strcpy, strcmp, ceil, pow, sqrt, clock, time, initgraph, circle, getchar, puts, isdigit, toupper, abs, atol, malloc, realloc

char *strcpy(char *dest, const char *src)

Copies the string pointed to, by src to dest.


int strcmp(const char *str1, const char *str2)

Compares the string pointed to, by str1 to the string pointed to by str2.


double ceil(double x)

Returns the smallest integer value greater than or equal to x.


double pow(double x, double y)

Returns x raised to the power of y.


double sqrt(double x)

Returns the square root of x.


clock_t clock(void)

Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program).


time_t time(time_t *timer)

        Calculates the current calender time and encodes it into time_t format.


struct tm *localtime(const time_t *timer)

The value of timer is broken up into the structure tm and expressed in the local

time zone.


void far initgraph(int far *graphdriver, int far *graphmode, char far

*pathtodriver);

Initializes the graphics system


void far circle(int x, int y, int radius);

circle draws a circle


int getchar(void)

Gets a character (an unsigned char) from stdin.


int puts(const char *str)

Writes a string to stdout up to but not including the null character. A newline

character is appended to the output.


int isdigit(int c)

This function checks whether the passed character is decimal digit.


int toupper(int c)

This function converts lowercase letters to uppercase.


int abs(int x)

Returns the absolute value of x.


long int atol(const char *str)

Converts the string pointed to, by the argument str to a long integer (type long

int).


void *malloc(size_t size)

Allocates the requested memory and returns a pointer to it.


void *realloc(void *ptr, size_t size)

Attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

__________________________________________________________________________________

What is pointer? How can we declare and initialize it?

            A Pointer in C language is a variable which holds the address of another variable of same data type.

            Pointers are used to access memory and manipulate the address.

            Pointers are one of the most distinct and exciting features of C language. It provides power and flexibility to the language.

Declaration of Pointer variable

General syntax of pointer declaration is,

            datatype *pointer_name;


            Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing.

Here are a few examples:

    int *ip // pointer to integer variable

    float *fp; // pointer to float variable

    double *dp; // pointer to double variable

    char *cp; // pointer to char variable

Initialization of Pointer variable

            Pointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable. The & (immediately preceding a variable name) returns the address of the variable associated with it.

#include<stdio.h>

void main()

{

    int a = 10;

    int *ptr; //pointer declaration

    ptr = &a; //pointer initialization

}

Pointer variables always point to variables of same datatype.

Using the pointer or Dereferencing of Pointer

Once a pointer has been assigned the address of a variable, to access the value of the variable, pointer is dereferenced, using the indirection operator or dereferencing operator *.

#include <stdio.h>

void main()

{

    int a, *p; // declaring the variable and pointer

    a = 10;

    p = &a; // initializing the pointer

    printf("%d", *p); //this will print the value of 'a'

    printf("%d", *&a); //this will also print the value of 'a'

    printf("%u", &a); //this will print the address of 'a'

    printf("%u", p); //this will also print the address of 'a'

    printf("%u", &p); //this will print the address of 'p'

    getch();

}

Points to remember while using pointers:

1. While declaring / initializing the pointer variable, * indicates that the variable is a pointer.

2. The address of any variable is given by preceding the variable name with Ampersand &.

3. The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value. It means that a is going to contain the address of a variable storing integer value.

4. To access the value of a certain address stored by a pointer variable, * is used. Here, the * can be read as 'value at'.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

 Normal variable stores the value whereas pointer variable stores the address of the variable.

 The content of the C pointer always be a whole number i.e. address.

 Always C pointer is initialized to null, i.e. int *p = null.

 The value of null pointer is 0.

 & symbol is used to get the address of the variable.

 * symbol is used to get the value of the variable that the pointer is pointing to.

 If a pointer in C is assigned to NULL, it means it is pointing to nothing.

 Two pointers can be subtracted to know how many elements are available between these two pointers.

 But, Pointer addition, multiplication, division are not allowed.

 The size of any pointer is 2 byte (for 16 bit compiler).

Advantages of using pointers in C programming

1. Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2. It makes you able to access any memory location in the computer's memory.

3. Pointers are more efficient in handling arrays and data tables.

4. Pointers can be used to return multiple values from a function via function arguments.

5. Pointers allow passing a function as argument to other functions.

6. The use of pointer arrays to character strings results in saving of data storage space in memory.

7. Pointers allow C to support dynamic memory management.

8. Pointers provide an efficient way for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees.

9. Pointers increase the execution speed and thus reduce the program execution time.

___________________________________________________________________________________

Explain pointer to an array with example.

            When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e. address of the first element of the array is also allocated by the compiler.

Suppose we declare an array arr,

int arr[5] = { 1, 2, 3, 4, 5 };

            Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows:



            Here variable arr will give the base address, which is a constant pointer pointing to the first element of the array, arr[0]. Hence arr contains the address of arr[0] i.e. 1000. In short, arr has two purposes - it is the name of the array and it acts as a pointer pointing towards the first element in the array.

arr is equal to &arr[0] by default

We can also declare a pointer of type int to point to the array arr.

int *p;

p = arr;

// or,

p = &arr[0]; //both the statements are equivalent.

Now we can access every element of the array arr using p++ to move from one element

to another.

Example of Pointer to Array

As studied above, we can use a pointer to point to an array, and then we can use that

pointer to access the array elements. Let’s have an example,

#include <stdio.h>

void main()

{

int i;

int a[5] = {1, 2, 3, 4, 5};

int *p = a; // same as int*p = &a[0]

for (i = 0; i < 5; i++)

{

printf("%d", *p);

p++;

}

getch();

}

In the above program, the pointer *p will print all the values stored in the array one by

one.

___________________________________________________________________________________

Explain pointer to structure with example.

            You can define pointers to structures in very similar way as you define pointer to any other variable as follows: 

struct Book *pointer_name;

            Now you can store the address of a structure variable in the above defined pointer variabe. To find the address of a structure variable, place the & operator before the structure variable's name as follows:

struct_pointer = &Book1;


To access the members of a structure using a pointer to that structure, you must use

the -> operator as follows:

Pointer_name->title;


Let us write the complete program for pointer to structure:

#include <stdio.h>

#include <conio.h>

#include <string.h>

struct Book

{

    int book_id;

    char title[50];

};

void main( )

{

    struct Book Book1; /* Declare Book1 of type Book */

    struct Book *ptr; /* Declare pointer of type Book */

    ptr = &Book1; //assign address of Book1 to pointer ptr

    Book1.book_id = 1521;

    strcpy( Book1.title, "C Programming");

    printf( "Book book_id : %d\n", ptr->book_id);

    printf( "Book title : %s\n", ptr->title);

    getch();

}

___________________________________________________________________________________

Explain passing pointer to a function with example.

            We are passing a pointer to a function. When we pass a pointer as an argument instead of a variable then the address of the variable is passed instead of the value. So any change made by the function using the pointer is permanently made at the address of passed variable. This technique is known as call by reference in C.

Example: Swapping two numbers using Pointer

#include <stdio.h>

void main()

{

    void swap(int *a, int *b);

    int m = 10, n = 20;

    printf("m = %d\n", m);

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

    swap(&m, &n); //passing address of m and n to the swap function

    printf("After Swapping:\n\n");

    printf("m = %d\n", m);

    printf("n = %d", n);

    getch();

}

/*

pointer 'a' and 'b' holds and

points to the address of 'm' and 'n'

*/

void swap(int *a, int *b)

{

    int c;

    c = *a;

    *a = *b;

    *b = c;

}

Output:

m = 10

n = 20

After Swapping:

m = 20

n = 10

___________________________________________________________________________________

Explain Array of pointer with an example.

            We can also have array of pointers. Pointers are very helpful in handling character array with rows of varying length.

char *name[3] = {

    "Adam",

    "chris",

    "Deniel"

};

//Now let’s see same array without using pointer

char name[3][20] = {

    "Adam",

    "chris",

    "Deniel"

};


            In the second approach memory wastage is more, hence it is preferred to use pointer in such cases.

            When we say memory wastage, it doesn't means that the strings will start occupying less space, no, characters will take the same space, but when we define array of characters, a contiguous memory space is located equal to the maximum size of the array, which is a wastage, which can be avoided if we use pointers instead.

___________________________________________________________________________________

6 Explain pointer to pointer with example.    

            In C, pointer to pointer concept, a pointer refers to the address of another pointer.

            In c language, a pointer can point to the address of another pointer which points to the address of a variable. Let's understand it by the diagram given below:


Let's see the syntax of pointer to pointer.

int **p2;

pointer to pointer example

            Let's see an example where one pointer points to the address of another pointer.


As you can see in the above figure, p2 contains the address of p (fff2) and p contains

the address of number variable (fff4).

#include<stdio.h>

void main()

{

    int number=50;

    int *p; //pointer to int

    int **p2; //pointer to pointer

    p=&number; //stores the address of number variable

    p2=&p;

    printf("Address of number variable is %x \n",&number);

    printf("Address of p variable is %x \n",p);

    printf("Value of *p variable is %d \n",*p);

    printf("Address of p2 variable is %x \n",p2);

    printf("Value of **p2 variable is %d \n",*p);

    getch();

}

Output

Address of number variable is fff4

Address of p variable is fff4

Value of *p variable is 50

Address of p2 variable is fff2

Value of **p variable is 50

___________________________________________________________________________________

Write difference between static memory allocation and dynamic memory allocation.

-----------------------------------------------------------------------------------------------------------------------------

    Static Memory Allocation                                 |            Dynamic Memory Allocation

-----------------------------------------------------------------------------------------------------------------------------

memory is allocated at compile time.                  |           memory is allocated at run time.

-----------------------------------------------------------------------------------------------------------------------------

memory can't be increased while                          |          memory can be increased while executing

executing program.                                              |             program.

-----------------------------------------------------------------------------------------------------------------------------

used in array.                                                       |           used in pointer (linked list).

-----------------------------------------------------------------------------------------------------------------------------

Memory locations are fixed at compile              |             Memory locations are not fixed means

time.                                                                    |                changed during run time.

-----------------------------------------------------------------------------------------------------------------------------

Static allocation memory is never freed.             |           Dynamic allocation memory is freed when

                                                                             |              the compound statement is exited.

-----------------------------------------------------------------------------------------------------------------------------

This allocation wastes memory                            |             This allocation saves memory.

-----------------------------------------------------------------------------------------------------------------------------

___________________________________________________________________________________

What is FILE? Explain different file modes.

    A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. FILE is a ready-made structure. 

=> Different file modes are given below:

=========================================================================

File Mode                                 Description

=========================================================================

                                                opens a text file in reading mode

-----------------------------------------------------------------------------------------------------------------------------

                                               opens or create a text file in writing mode.

-----------------------------------------------------------------------------------------------------------------------------

                                                opens a text file in append mode

-----------------------------------------------------------------------------------------------------------------------------

r+                                               opens a text file in both reading and writing mode

-----------------------------------------------------------------------------------------------------------------------------

w+                                             opens a text file in both reading and writing mode

-----------------------------------------------------------------------------------------------------------------------------

a+                                              opens a text file in both reading and writing mode

=========================================================================

___________________________________________________________________________________

Explain different file handling functions.

 Different file handling functions are as below:

=========================================================================

Function      Description

=========================================================================

fopen()          create a new file or open a existing file

-----------------------------------------------------------------------------------------------------------------------------

fclose()          closes a file

-----------------------------------------------------------------------------------------------------------------------------

getc()            reads a character from a file

-----------------------------------------------------------------------------------------------------------------------------

putc()            writes a character to a file

-----------------------------------------------------------------------------------------------------------------------------

getw()           reads an integer from a file

-----------------------------------------------------------------------------------------------------------------------------

putw()           writes an integer to a file

-----------------------------------------------------------------------------------------------------------------------------

fscanf()         reads a set of data from a file

-----------------------------------------------------------------------------------------------------------------------------

fprintf()        writes a set of data to a file

-----------------------------------------------------------------------------------------------------------------------------

fwrite()         writes structure variable to a file

-----------------------------------------------------------------------------------------------------------------------------

fread()         reads structure variable from a file

=========================================================================

___________________________________________________________________________________

What is command line argument? Explain with an example.

            Command line argument is a parameter supplied to the program when it is invoked. Command line argument is an important concept in C programming. It is mostly used when you need to control your program from outside. Command line arguments are passed to the main() method.

Syntax:

void main(int argc, char *argv[])

            Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.

Example for Command Line Argument

#include <stdio.h>

#include <conio.h>

void main(int argc, char *argv[])

{

    int i;

    if( argc >= 2 )

    {

        printf("The arguments supplied are:\n");

        for(i = 1; i < argc; i++)

        {

            printf("%s\t", argv[i]);

        }

    }

    else

    {

        printf("argument list is empty.\n");

    }

    getch();

}

            Remember that argv[0] holds the name of the program and argv[1] points to the first command line argument and argv[n] gives the last argument. If no argument is supplied, argc will be 1.


No comments:

Post a Comment