Back to Study material
PPS

Unit 1 Introduction Q1) Explain C language?C language was developed by Dennis Ritchie at bell laboratory in year 1972. Most of the features of C language were derived from B language. Due to flexibility of C language, UNIX operating system which was initially written in assembly language was again rewritten in C language.Features of C languageC language follows structure oriented programming approach.C is a procedure oriented language.In C language, complete program is composed of various functions and procedures.C language follows Top-Down approach in program design. In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming Language” and commonly known as K&R C.Advantages of C languageReliability: C language allows low level access to data and commands and maintains the syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs.Flexibility: C is a powerful and flexible language which provides fast program execution.Modularity: C language provides features like Functions, Structures, Unions and Built-in Library functions which support code reusability.Efficiency and Effectiveness: The programs of C language are less complex and do not require any special programming language platform other than compiler. C language plays vital role in hardware programming Q2) Explain constants , variables and keywords? Constant:

  
  • Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
  • Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
  • Constants are treated just like regular variables except that their values cannot be modified after their definition.
  •  In C/C++ program we can define constants in two ways as shown below:
  • Using #define preprocessor directive
  • Using a const keyword
  •  Variables: Variables are the names you give to computer memory locations which are used to store values in a computer program.Here are the following three simple steps
  • Create variables with appropriate names.
  • Store your values in those two variables.
  • Retrieve and use the stored values from the variables.
  •  When creating a variable, we need to declare the data type it contains. Programming languages define data types differently. For example, almost all languages differentiate between ‘integers’ (or whole numbers, eg 12), ‘non-integers’ (numbers with decimals, eg 0.24), and ‘characters’ (letters of the alphabet or words).
  • char – a single 16-bit Unicode character, such as a letter, decimal or punctuation symbol.
  • boolean – can have only two possible values: true (1) or false (0). This data type is useful in conditional statements.
  • byte - has a minimum value of -128 and a maximum value of 127 (inclusive).
  • short– has a minimum value of -32,768 and a maximum value of 32,767
  • int: – has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
  • long – has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
  • float – a floating point number with 32-bits of precision
  • double – this is a double precision floating point number.
  •  Keywords:Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:Here int is a keyword that indicates money is variable of type int (integer) . As C is case sensitive language all keywords must be written in lowercase.Example:int money;

     Q3) Explain the type of C constants? C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined.Constants refer to fixed values. They are also called as literalsConstants may be belonging to any of the data type.Syntax:const data_type variable_name; (or) const data_type *variable_name; Types of constantInteger constantsReal or Floating point constantsOctal & Hexadecimal constantsCharacter constantsString constantsBackslash character constants. Q4) Explain the rule for constructing integer constants? Integer ConstantAn integer constant must have at least one digit.It must not have a decimal point.It can either be positive or negative.No commas or blanks are allowed within an integer constant.If no sign precedes an integer constant, it is assumed to be positive.The allowable range for integer constants is -32768 to 32767. Q5) Explain the rule for constructing real constants? Real ConstantA real constant must have at least one digitIt must have a decimal pointIt could be either positive or negativeIf no sign precedes an integer constant, it is assumed to be positive.No commas or blanks are allowed within a real constant. Q6) Explain the rule for constructing character constants? Character and String constant: A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes.The maximum length of a character constant is 1 character.String constants are  enclosed within double quotes. Q7) Explain the types of c variables? The Programming language C has two main variable typesLocal VariablesGlobal VariablesLocal VariablesLocal variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself.When execution of the block starts the variable is available, and when the block ends the variable 'dies'. Check following example's output   main()   {      int i=4;      int j=10;       i++;       if (j > 0)      {          /* i defined in 'main' can be seen */         printf("i is %d\n",i);       }       if (j > 0)      {         /* 'i' is defined and so local to this block */         int i=100;          printf("i is %d\n",i);            }/* 'i' (value 100) dies here */       printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/   }    This will generate following output   i is 5   i is 100   i is 5Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1;You will see -- operator also which is called decremental operator and it decrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1; Global VariablesGlobal variable is defined at the top of the program file and it can be visible and modified by any function that may reference it.Global variables are initalised automatically by the system when you define them!Data Type Initialserint 0char '\0'float 0pointer NULLIf same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.    int i=4;          /* Global definition   */   main()   {       i++;          /* Global variable     */       func();       printf( "Value of i = %d -- main function\n", i );   }   func()   {       int i=10;     /* Local definition */       i++;          /* Local variable    */       printf( "Value of i = %d -- func() function\n", i );   }   This will produce following result   Value of i = 11 -- func() function   Value of i = 5 -- main functioni in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global. Q8) Explain the rules for constructing variable names? Rules for constructing variable names
    1) A Variable name consists of any combination of alphabets, digits and underscores. Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters. 2) The first character of the variable name must either be alphabet or underscore. It should not start with the digit.3) No commas and blanks are allowed in the variable name.4) No special symbols other than underscore are allowed in the variable name.

    We need to declare the type of the variable name before making use of that name in the program. Type declaration can be done as follows:
    To declare a variable as integer, follow the below syntax:
    int variable_name;
    Here int is the type of the variable named variable_name. ‘int’ denotes integer type.
    Following are the examples of type declaration statements:
    E.g.: int p, n;
    float r; Q9) Explain the comments in C program? A well-documented program is a good practice as a programmer. It makes a program more readable and error finding become easier. One important part of good documentation is Comments.
  • In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program
  • Comments are statements that are not executed by the compiler and interpreter.
  •  In C/C++ there are two types of comments :
  • Single line comment
  • Multi-line comment
  •  // single line comment /*                                       */ multiline comment Q10) Explain type declaration instruction? Type Declaration Instruction
  • This instruction is used to declare the type of variables being used in the program.
  • Any variable used in the program must be declared before using it in any statement.
  • The type declaration statement is written at the beginning of main( ) function.
  • Example :int bas ;
    float rs, grosssal ;
    char name, code ;
  • While declaring the type of variable we can also initialize it as shown below.
  • int i = 10, j = 25 ;
    float a = 1.5, b = 1.99 + 2.4 * 1.44 ;
  • The order in which we define the variables is sometimes important sometimes not.
  • int i = 10, j = 25 ;
    is same as
    int j = 25, i = 10 ;However,float a = 1.5, b = a + 3.1 ;
    is alright, but
    float b = a + 3.1, a = 1.5 ;is not. This is because here we are trying to use a even before defining it.
  • The following statements would work.
  • int a, b, c, d ;
    a = b = c = 10 ;However, the following statement would not work.int a = b = c = d = 10 ;Once again we are trying to use b (to assign to a) before defining it.Q11) Explain type conversions in assignment? Type conversions depend on the specified operator and the type of the operand or operators. Type conversions are performed in the following cases:
  • When a value of one type is assigned to a variable of a different type or an operator converts the type of its operand or operands before performing an operation
  • When a value of one type is explicitly cast to a different type
  • When a value is passed as an argument to a function or when a type is returned from a function
  • A character, a short integer, or an integer bit field, all either signed or not, or an object of enumeration type, can be used in an expression wherever an integer can be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise, it is converted to unsigned int. This process is called "integral promotion." Integral promotions preserve value.  Q12) Explain the data types integers, long and short? Integer is defined as a number which has no fractional component. Numbers which have a fractional component is known floating point numbers. Despite the fact that floating point numbers can represent numbers accurately, integers have their own place in the world of computing due to:
  • Integers consumes significantly less space than Floating point numbers
  • Calculations using integers are much faster (over 2 times) due to hardware architecture
  • In C programming language, integer data is represented by its own datatype known as int. It has several variants which differs based on memory consumption includes:
  • int
  • long
  • short
  • long long
  •  Integer is defined as a number which has no fractional component. Numbers which have a fractional component is known floating point numbers. Despite the fact that floating point numbers can represent numbers accurately, integers have their own place in the world of computing due to: Integers consumes significantly less space than Floating point numbersCalculations using integers are much faster (over 2 times) due to hardware architectureIn C programming language, integer data is represented by its own datatype known as int. It has several variants which differs based on memory consumption includes:intlongshortlong long In C, one can define an integer variable as:

      Signed and unsigned version:As the range of numbers determined by a datatype like int is limited and both negative and positive numbers are required, we have two options:
  • signed integers: range is equally divided among negative and positive numbers (including 0)
  • unsigned integers: range starts from 0 to the upper positive number limit
  • Hence, unsigned integers are used when:
  • negative numbers are not required
  • increase the range of positive number by double
  • One can defined an unsigned integer by placing the keyword unsigned before the usual declaration/ initialization like: 

      The default declaration is the signed version signed.Hence, there are 8 possible types for integer:
  • int
  • unsigned int
  • short
  • unsigned short
  • long
  • unsigned long
  • long long
  • unsigned long long
  • Format specifierTo print a value in C using printf, one needs to specify the datatype of the data to be printed. The format specifier of each variant of integer datatype is different in C.For instance, int datatype has %d as the format specifier.Following code demonstrates the idea:

      Range and memory consumptionOne can find the memory consumed by a data type as follows:

     Q13) Explain signed and unsigned char? The signed char type when converted to integer type can represent both -ve and +ve values,but unsigned type can represent only +ve value.In signed type the left most bit is reserve to store either 1 or 0 bit to represent -ve and +ve sign leaving only 7 bits to represent the actual value.So, it can represent an integer between -27 to (27 – 1) (-128 to 127). In case of unsigned type no such allocation is made so it can represent an integer between 0 and (28-1)(0 to 255).In the pictorial representation below the range of integer value they can represent is shown on the number line.

     Q14) Explain signed and unsigned float and double ? Float - It is used to store single precision floating point number.Double - It is used to store a double precision floating point number.The double type provides more precision than the float type. It simply means that the double- type provides more digits to the right of decimal point than the float type. To be precise, the float provides 6 digits of precision, while the double provides 14 digits of precision.It is important to note that the float and double represents the same type - floating point numbers. The only difference is in the number of precision.Q15) Explain the types of console I/O ? Console simply means screen and keyboard. There are two types of a console I/O functions:
  • Formatted input-output function
  • Unformatted input-output function
  • The major difference is that formatted function allows us to format the input from the keyboard and the output to be displayed on the screen.

    c programming input output functions : printf and scanf

     printf()  is the standard library function that is used for precise output formatting.syntax of printf( ) function:printf(format-control-string, other -arguments );Format control string in printf( ) function describes the output format which consists of conversion specifiers, precisions, flags, field widths and literal characters.Each conversion specifier starts with % sign and ends with a conversion specifier.Keyboard and screen together called console. This is the behind the name of these functions. Console I/O functions further classified into
  • Formatted Input/Output Functions
  • Unformatted Input/Output Functions
  •   Q16) Explain formatted console I/O operation? Formatted Input/Output Functions in Cprintf() and scanf() functions comes under this category. They provide the flexibility to receive the input in some fixed format and to give the output in desired formatsprintf() and sscanf() FunctionThese formatted console I/O functions works a bit different to printf() and scanf() functions. sprintf() function is quite similar to printf() function but instead of printing the output on screen, it stores it in the character array. Consider below example to understand this. 

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    #include<stdio.h>

     

    void main()

    {  

     int j=32;  

     char cha='p';

     float a=123.2;  

     char str[20];    

     sprintf(str,"%d %c %f",j,cha,a);

     printf("%sn",str);

      

    }


    sscanf() is the counter part of sprintf() function. It allows the programmer to store the characters of string in some other variable. These two functions are used very rarely in C. Q17) Explain unformatted console I/O operation? Unformatted Input/Output Functions in CFunctions like getch(), getche() and getchar() comes under this category. These functions store only one character. Till now we have used scanf() function to store values. Unfortunately we have to press enter key while using scanf() function to store the values in memory. In a condition when we have to store only one character these unformatted function comes very handy.The header file used for these three functions is conio.h.getch() functionThis function is used to store only one character in memory. It does not echo or display that character on the screen while program execution.getche() functionThis function works similar to getch function. However it just echo or display that character on screen.getchar() functionThis function works entirely similar to getche function. It stores one character and display it on the screen. But we have to press the enter key to store one character while using this function.Consider below example to understand these functions.   

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    #include<stdio.h>                                            

    #include<conio.h>                                            

                                                                  

    void main()                                                  

    {                                                            

     char ch1,ch2,ch3;                                            

     ch1=getch(); // it does not echo the character on screen    

     ch2=getche(); //echo's character on screen                  

     ch3=getchar();   // Use Enter to store the value            

                                                                  

            printf("%c %c %cn",ch1,ch2,ch3);                            

                                                                  

    }

                 
    Output 

    Console Input/Output Functions in C

       Q18) Explain if statement? This statement permits the programmer to allocate condition on the execution of a statement. If the evaluated condition found to be true, the single statement following the "if" is execute. If the condition is found to be false, the following statement is skipped. Syntax of the if statement is as follows

                     if (condition)

                     statement1;

                     statement2;

    In the above syntax, “if” is the keyword and condition in parentheses must evaluate to true or false. If the condition is satisfied (true) then compiler will execute statement1 and then statement2. If the condition is not satisfied (false) then compiler will skip statement1 and directly execute statement2.  Q19) Explain the use of logical operator ? 
  • Logical operators are used to compare logical values of two operands. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
  • Sr. No.

    Operator

    Description

    Example

    1.

    &&

    This is logical AND, it returns true when both the values are non zero

    Result of (A&&B) is true

    2.

    ||

    This is logical OR, it returns true when any of two value is non zero

    Result of (A||B) is true

    3.

    !

    This is logical NOT operator, it is used to reverse the logical state of operand 

    Result of !(A&&B) is false

    Example:#include<stdio.h>#include<conio.h>void main(){ int a,b,c; clrscr(); printf("Enter two numbers"); scanf("%d %d",&a,&b); printf("\n Result of logical and operator of  %d and  %d is %d",a,b,a&&b); printf("\n Result of logical or  operator of %d and %d is %d",a,b,a||b); printf("\n Result of logical not operator of %d and and %d is %d",a,b,!(a&&b)); getch();}Output:Enter two numbers53Result of logical and operator of 5 and 3 is 1Result of logical or operator of 5 and 3 is 1Result of logical not operator of 5 and 3 is 0 Q20) Explain the else if clause ? General Syntax of else if clause is given below.if (condition)
    {
    Statement 1
    Statement 2 and so on
    }else if (condition)
    {
    Statement 1
    Statement 2 and so on
    }else if (condition)
    {
    Statement 1
    Statement 2 and so on
    }else
    {
    Statement 1
    Statememt 2 and so on
    }

      Q21) Explain conditional operator? The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.As conditional operator works on three operands, so it is also known as the ternary operator.Syntax of a conditional operatorExpression1? expression2: expression3;  The pictorial representation of the above syntax is shown below:Conditional Operator in CMeaning of the above syntax. In the above syntax, the expression1 is a Boolean condition that can be either true or false value.If the expression1 results into a true value, then the expression2 will execute.The expression2 is said to be true only when it returns a non-zero value.If the expression1 returns false value then the expression3 will execute.The expression3 is said to be false only when it returns zero value.#include <stdio.h>  int main()  {      int age;  // variable declaration      printf("Enter your age");      scanf("%d",&age);   // taking user input for age variable      (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));  // conditional operator      return 0;  }  In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting)otherwise, statement2 will execute, i.e., (printf("not eligible for voting")