Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 59

Unit -1

Short Answer Questions:

1. Give the use of break and continue with an example. 3M


ANSWER:
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.

In such cases, break and continue statements are used.

break Statement
The break statement terminates the loop (for, while and do...while loop) immediately
when it is encountered. The break statement is used with decision making statement such
as if...else.

Syntax of break statement


break;
Example: break statement
// Program to calculate the sum of maximum of 10 numbers
// Calculates sum until user enters positive number

# include <stdio.h>
int main()
{
inti;
double number, sum = 0.0;

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


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output:

Enter a n1: 2.4


Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of maximum of 10 numbers. It's because, when the user
enters negative number, the break statement is executed and loop is terminated.

In C programming, break statement is also used with switch...case statement.

continue Statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.

Syntax of continue Statement


continue;

Example: continue statement


// Program to calculate sum of maximum of 10 numbers
// Negative numbers are skipped from calculation

# include <stdio.h>
int main()
{
inti;
double number, sum = 0.0;

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


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}

Output:

Enter a n1: 1.1


Enter a n2: 2.2
Enter a n3: 5.5
Enter a n4: 4.4
Enter a n5: -3.4
Enter a n6: -45.5
Enter a n7: 34.5
Enter a n8: -4.2
Enter a n9: -1000
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated using sum +=
number; statement.

When the user enters negative number, the continue statement is executed and skips the
negative number from calculation.

2. Write the size and range of basic data types.4M


ANSWER:

Data type specifies the set of values and the type of data that can be stored in a variable.
They allow the programmer to select the type appropriate to the needs of application.
Types :
1) Primary data types (or) Basic data types (or)Fundamental data types
2) Derived data types
3) User – defined data types
1. Primary data types
‘C’ compilers support 4 fundamental data types
They are
1) integer
2) character
3) Floating – point
4) Double precision floating point
Primrary Data Types

Integral Type

Integer
character
Signed Unsigned
signed char
int unsigned int
short int unsigned short int unsigned char
long int unsigned long int

Floating point type


float double long double

1. Integral data type


 Integral data types are used to store whole numbers and characters
 It is further classified into
a) integer data type
b) character data type

a) Integer data type


 This data type is used to store whole numbers
 It has 3 classes of integer storage namely, short int, int and long int in both signed and
unsigned forms

Integer Data type


Type size (in bytes) Range Control string
Short int (or) 1 -128 to 127 %h
signed short int
Unsigned short int 1 0 to 255 % uh
int (or) signed int 2 -32768 to 32767 % d or %i
unsigned int 2 0 to 65535 %u
Long int (or) signed 4 -2147483648 to %ld
long int 2147483647
Unsigned long int 4 0 to 4294967295 %lu
b) character data type
 This data type is used to store characters
 These characters are internally stored as integers
 Each character has an equivalent ASCII value
eg: ‘A’ has ASCII value 65

Character data type


Type Size (in bytes) Range Control string
Char (or) signed 1 - 128 to +127 %c
char
Unsigned char 1 0 to 255 %c

2. Floating – point Data types


 It is used to store real numbers (i.e., decimal point numbers).
 For 6 digits of accuracy, ‘float’ is used.
 For 12 digits of accuracy, ‘double' is used.
 For more than 12 digits of accuracy, ‘long double’ is used..

Floating point data type


Type Size (in bytes) Range Control string
float 4 3.4 E – 38 to 3.4 E + 38 %f
double 8 1.7 E – 308 to 1.7 E +308 %lf
long double 10 3.4 E – 4932 to 1.1 E +4932 %lf

3. What are the basic input and output functions used in C? 4M


ANSWER:
C Input and Output

 Storing a value into memory is called ‘ input operation’.


 After executing the computations, the results are stored in memory and the results can be
displayed to the user by ‘output operation’.
 All input / output operations in ‘C’ are performed using input / output functions.
 The most common I/O functions are supplied as part of the ‘C’ standard I/O library through
the preprocessor directive # include<stdio.h>.
 Most commonly used I/O functions are
a) printf ( )
b) scanf ( )
a) printf ( ) function:
Syntax:
printf(“format string”, print list);
e.g.: printf (“average of 3 numbers = %f”,avg);
* The printf ( ) function displays the value of its format string after substituting the values of
the expressions in the print list.
* It also replaces the escape sequences such as ‘\n’ by their meanings.
b) scanf ( ) function:
Syntax:
scanf (“format string”,& input list);
e.g.: scanf (“%d %f”, &a, &b);
 The scanf ( ) function copies into memory data typed at the keyboard by the program user
during program execution.
 The input list must be preceded by ampersand ( &)
4. Define high level language and low level language. 3M
ANSWER:
High level languages:
 A set of languages which are very close to our native languages are called “ high-level
languages”.
 High level languages have control structures, I/O facilities, hardware independence
 eg: FORTRAN, COBOL, PASCAL, C, C++ etc..
Advantage :
 Machine independence i.e. programs are “Portable” i.e. programs can be moved from one
system to another
 Easy to learn and understand
 Takes less time to write programs
Disadvantage :
 High level language programs needs a translator for conversion into machine language
 ‘Compilers’ (or) ‘Interpreters’ are used for converting high level language program into
machine language..

Compiler /
High level language program Machine Language code
Interpreter

 Compiler converts entire statements in the program at a time.


 Interpreter converts one statement at a time.
Machine languages
 Computer is a machine and since its memory can store only 1’s and 0’s, instructions must be
given to the computer in streams of 1’s and 0’s i.e. binary code.
 These are easily understandable by the machine.
 It is also called as low level language.
 Programs written in binary code can be directly fed to computer for execution and it is known
as machine language.
Advantage :
 Execution is very fast since there is no need of conversion
Disadvantage :
 Writing and reading programs in machine language is very difficult
 Machine instructions are difficult to remember
5. Explain about the break and continue with example 4M
ANSWER: same as 1 answer

6. Differentiate between compiler and interpreter. 3M


ANSWER:

The difference between an interpreter and a compiler is given below:

Interpreter Compiler

Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.

It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall the source code but the overall execution
execution time is slower. time is comparatively faster.

Generates intermediate object code


No intermediate object code is
which further requires linking, hence
generated, hence are memory efficient.
requires more memory.

Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.

Programming language like Python, Programming language like C, C++ use


Ruby use interpreters. compilers.

7. What is nested if? Give examples. 4M


ANSWER:
Nested If in C Language
Placing If Statement inside another IF Statement is called Nested If in C Programming. If
Else statement in C allows us to print different statements depending upon the expression
result (TRUE, FALSE). Sometimes we have to check further even when the condition is
TRUE. In these situation, we can use Nested IF statements but be careful while using it.
For example, every person is eligible to work if he is 18 years old or above else he is not
eligible but companies will not give job to every person. So, we use another IF Statement
(Also called as Nested If Statement) to check his education qualifications or any specific
company requirements.
Nested If in C Syntax
The Nested If in C Programming language Syntax is as follows:
if ( test condition 1)
{
//If the test condition 1 is TRUE then these it will check for test condition 2
if ( test condition 2)
{
//If the test condition 2 is TRUE then these statements will be executed
Test condition 2 True statements;
}
else
{
//If the c test condition 2 is FALSE then these statements will be executed
Test condition 2 False statements;
}
else
{
//If the test condition 1 is FALSE then these statements will be executed
Test condition 1 False statements;
}

EXAMPLE PROGRAM FOR NESTED IF STATEMENT IN C:

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
OUTPUT:
m is greater than n

8. Differentiate between switch and else-if. 3M


ANSWER:
Difference between switch case and else if ladder:
So, after going through the two control statements in brief, here are the main difference
between switch case and else if ladder:

 In else if ladder, the control goes through the every else if statement until it finds
true value of the statement or it comes to the end of the else if ladder. In case
of switch case, as per the value of the switch, the control jumps to the
corresponding case.
 The switch case is more compact than lot of nested else if. So, switch is considered
to be more readable.
 The use of break statement in switch is essential but there is no need of use of
break in else if ladder.
 The variable data type that can be used in expression of switch is integer only
where as in else if ladder accepts integer type as well as character.
 Another difference between switch case and else if ladder is that
the switch statement is considered to be less flexible than the else if ladder,
because it allows only testing of a single expression against a list of discrete
values.
 Since the compiler is capable of optimizing the switch statement, they are
generally considered to be more efficient. Each case in switch statement is
independent of the previous one. In case of else if ladder, the code needs to be
processed in the order determined by the programmer.
 Switch case statement work on the basis of equality operator whereas else if
ladderworks on the basis of true false( zero/non-zero) basis.

9. Differentiate between compiling and linking. 3M


ANSWER:

Compiling :
 “Compiler” is a software that translates the source file into machine language.
 The ‘C’ compiler is actually 2 separate programs
a) Preprocessor
b) Translator
a) Preprocessor
 It reads the source code and prepares it for the translator.
 It scans for special instructions known as ‘preprocessor’ commands which start with ‘ #’
symbol.
 These commands tell the preprocessor to look for special code libraries and make
substitutions.
 The result of preprocessing is called ‘translation’ unit.

Source File Preprocessor translation unit

b) Translator
 It does the actual work of converting the program into machine language.
 It reads the translation unit and results in ‘object module’ i.e., code in machine language.
 But it is not yet executable because it does not have the ‘C’ and other functions included.
Translator
Translation unit Object Module .obj file
00110 100
10101 010
Linking :
 ‘Linker’ assembles input /output functions, mathematical library functions and some of the
functions that are part of source program into final executable program.
 It is called as executable file that it is ready for execution.
.exe file
Linker
Object file executable file 1011001100
110111011
1100101010

10. Write a program to find the 2n value. 4M


ANSWER:

PROGRAM CODE:
#include <stdio.h>
#include <math.h> // Used for pow() function

int main()
{
double base, expo, power;

/* Input two numbers from user */


printf("Enter base: ");
scanf("%lf", &base);
printf("Enter exponent: ");
scanf("%lf", &expo);

/* Calculates base^expo */
power = pow(base, expo);

printf("%.2lf ^ %.2lf = %.2lf", base, expo, power);

return 0;
}

Input:
Enter base: 2
Enter exponent: 2

Output: 2 ^ 2 = 4
11. What is preprocessor? 3

ANSWER:

 It reads the source code and prepares it for the translator.


 It scans for special instructions known as ‘preprocessor’ commands which start with ‘ #’
symbol.
 These commands tell the preprocessor to look for special code libraries and make
substitutions.
 It must be the first nonblank character, and for readability, a preprocessor directive
should begin in the first column.

 The following section lists down all the important preprocessor directives −

Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
Issues special commands to the compiler, using a standardized method.

12. Define algorithm and flowchart. 3M

ANSWER:

ALGORITHM:
 It is a step – by – step procedure for solving a problem
Properties of an Algorithm
An algorithm must possess the following 5 properties. They are
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into program
statements

FLOW CHART
Graphical representation of an algorithm is called flow chart.
Advantages of flow chart
 It is very easy to understand because the reader follows the process quickly from the
flowchart instead of going through the text.

 It is the best way of representing the sequence of steps in an algorithm.


 It gives a clear idea about the problem.

 Various symbols are used for representing different operations.

 Arrows are used for connecting the symbols and show the flow of execution.

Symbols used in flowchart:

Name Symbol Purpose


Terminal Start /stop/begin/end

oval
Input / output Input/output of data

Parallelogram
Process Any processing to be
performed can be represented

Rectangle
Decision box Decision operations that
determine which of the
alternative paths to be
Diamond followed
Connector Used to connect different parts
of flowchart
Circle
Flow Joins 2 symbols and also
represents flow of execution
Arrows
Pre defined process Modules (or)subroutines
specified else where

Double sided rectangle


Page connector Used to connect flowchart in 2
different pages

Pentagon
For loop symbol Shows initialization, condition
and incrementation of loop
variable.
Hexagon
Document Shows the data that is ready
for printout

Printout
Example : Write an algorithm and draw a flowchart on to print 1 to 20 numbers.

Algorithm:

Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.

Flowchart:
13. How to compile a given file in linux? Explain with one example. 2M
ANSWER:
Writing Your First C Program Under a Linux / UNIX-like system

Use a text editor such as vi or gedit or nano to create a C program called first.c:
$ vi first.c
Type the following lines (program):

#include <stdio.h>
int main(void){
printf("My first C program\n");
return 0;
}

How Do I Compile My C Program?

To compile C program first.c, and create an executable file called first, enter:
$ gcc first.c -o first
OR
$ cc first.c -o first
To execute program first, enter:
$ ./first

Output:

My first C program

14. Explain about break and continue 4M


ANSWER: SAME AS 1 ANSWER

15. Explain about static keyword with an example 4M


ANSWER:

Definition

The static keyword in C is a storage-class specifier. It has different meanings, depending


on the context. Inside a function it makes the variable to retain its value between multiple
function calls. Outside of a function it restrains the visibility of the function or variable to the
current file (compilation unit).

Syntax

The syntax of the static keyword in C is very simple. When defining a variable or function,
write the static modifier before the type or name.

These two are equivalent:


static <variable’s type><variable’s name>
<variable’s type> static <variable’s name>

And these are equivalent, too:

static <function’s type><function’s name>()


<function’s type> static <function’s name>()

Simple syntax examples

Here are two examples of static variables:

int static callCount = 0;


static int callCount = 0;

Here are two examples of static functions:

static void count()


{
...
}

void static count()


{
...
}

16. Which of the following expressions are valid? Give reasons.


(i) +a +b (ii) a++ - - b (iii) a % 10 / - b (iv) a++ + ++b 4M
ANSWER:
(i) +a +b: Invalid expression because ‘+’ is binary operator .
(ii) a++ --b: Valid expression as ++,-- are unary operators.
(iii) a%10/-b: Valid expression as per precedence and associativity rules.
(iv) a++ + ++b: Valid expression as ++ is unary operator.

17. What are the values of control variables and number of the iterations in the
following forloops?
(i)for( x=1.0 ; x>=0.5; x - = 0.1) (ii) for( ch= ‘A’ ; ch != ‘F’ ; ++ch) 4M
ANSWER:
(i) for( x = 1.0; x >= 0.5; x- = 0.1 )
x=1.0
x=0.9
x=0.8
x=0.7
x=0.6
x=0.5
no.of iterations = 6.
(ii) for( ch= ‘A’ ; ch != ‘F’ ; ++ch)
ch=A
ch=B
ch=C
ch=D
ch=E
ch=F
no.of iterations = 6.

18. Write an algorithm for finding biggest of among given three no’s. 4M
ANSWER:

 Algorithm :
o Step 1 : Start
o Start 2 : Input a, b, c
o Start 3 : if a > b goto step 4, otherwise goto step 5
o Start 4 : if a > c goto step 6, otherwise goto step 8
o Start 5 : if b > c goto step 7, otherwise goto step 8
o Start 6 : Output "a is the largest", goto step 9
o Start 7 : Output "b is the largest", goto step 9
o Start 8 : Output " c is the largest", goto step 9
o Start 9 : Stop

19. What is a flowchart? Explain with one example. 3M


ANSWER:
Read from 13 question.

20. Discuss about switch statement with an example. 4 M


ANSWER:
Switch statement
 It is used to select one among multiple decisions.
 ‘switch’ successively tests a value against a list of integer (or) character constant.
 When a match is found, the statement (or) statements associated with that value are
executed.

 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.

 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.

 A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
Syntax
switch (expression)
{
case value1 : stmt1;
break;
case value2 : stmt2;
break;
------
default :stmt ;
}
Statement-x;

Flow chart

Switch
(expressio
n)

Exp =value1 Stmt1

Exp =value2
| Stmt2

default Stmt

Program
#include<stdio.h>
#include<conio.h>
Statement-X
void main()
{
int n;
clrscr();
printf (“enter a number”);
scanf (“%d”, &n);
switch (n)
{
case 0 : printf (“zero”)
break;
case 1 : printf (‘one”);
break;
default :printf (‘wrong choice”);
}
}

Input
enter a number 1
Output
one

21. Is there any difference between pre-increment and post-increment? Explain 4M

C – Increment/decrement Operators
 Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
 Example:

Increment operator : ++ i ; i ++ ;

Decrement operator: ––i; i––;

Difference between pre/post increment & decrement operators in C:


o Below table will explain the difference between pre/post increment and decrement
operators in C.

S.no Operator type Operator Description

Value of i is incremented before assigning it to


1 Pre increment ++i
variable i.

Value of i is incremented after assigning it to variable


2 Post-increment i++
i.
Value of i is decremented before assigning it to
3 Pre decrement – –i
variable i.

Value of i is decremented after assigning it to variable


4 Post_decrement i– –
i.

22. Explain about nested if. 4 M


Same as 8 answer

23. What is identifier? What are the rules for identifier? 4M


ANSWER:

In C language identifiers are the names given to variables, constants, functions and user-
define data. These identifier are defined against a set of rules.

Rules for an Identifier

1. An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
2. The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore (_).
3. Identifiers are also case sensitive in C. For example name and Name are two different
identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.

24. What is the output of the following code, Justify your answer. 3M
int main()

{
int x=1, y=5;
printf(“%d”, ++x +y);
return 0;
}

ANSWER: 7

Justification:
x=1
++x increments x by 1. So, x=2
y=5
++x + y=7(2+5)

25. What is the meaning of 3<j &&j<5? Is it equivalent to (3<j) && (j<5)? 4M
ANSWER:
3<j && j<5 means first condition 3<j is checked then after j && j condition is checked then
j<5 condition is checked which has no meaning for output of those conditions
(3<j) && (j<5) means first (3<j) condition is checked and (j<5) condition is checked then
both results are considered for && condition to get result either true or false.
26. Explain why the following identifiers are invalid? 4M
(a) %age marks (b) x.y (c) amount_in_$ (d) marks(1)
ANSWER:
(a) %age marks:-Invalid because identifier should start with alphabet or underscore(_),
and no space is allowed in identifier.
(b) x.y:-is invalid because no period operator(.) is allowed in identifier.
(c) amount_in_$ :- is invalid because no special character is allowed in identifier.
(d) marks(1) :- is invalid because no special character ‘()’ is allowed in identifier.

27.Write code to output the numbers from 1 to 10 using for loop 4M


ANSWER:
#include<stdio.h>
void main()
{
inti,n;
printf(“\n numbers from 1 to 10 are:”);
for(i=1;i<=10;i++)
printf(“\n %d”,i);
}

28.What are formatted input and output statements in C? Give suitable examples. 4M
ANSWER: same as 3 answer

29.Difference between do-while and while-do constructs 4M


ANSWER:
The most important difference between While and Do-While is that in Do-While, the block
of code is executed at least once.
i.e., the Do-While loop runs at least once, even though the condition given is false
To put it in a different way :
In While the condition is at the begin of the loop block, and makes possible to never enter the
loop.
In While loop, the condition is first tested and then the block of code is executed if the test
result is true.
----------------------------------------------------------------
In Do- While the condition is at the end of the loop block, and makes obligatory to enter the
loop at least one time.
In Do-While, the code is first executed and then the condition is checked. The next iteration
is executed if the test result is true.
------------------------------------------------------------------
While is Entry Controlled and Do-While is Exit Controlled.

Syntax:
//while
while(condition is true)
{
Group of statements;
}
//do-while
do
{
Group of statements;
}while(condition is true);

EXAMPLE :-

Program on while loop:


#include<stdio.h>
#include<conio.h> Input:
void main() enter the value of n=5
{ Output
int i=1,n; i=1
clrscr(); i=2
printf(”enter the value of n=”);
scanf(”%d”,&n); i=3
while( i<=n) i=4
{
printf (”\ni=%d”,i); i=5
i++;
}
getch();
}

Program on do-while loop:


#include<stdio.h>
#include<conio.h> Input:
void main() enter the value of n=5
{ Output
int i=1,n; i=1
clrscr(); i=2
printf(”enter the value of n=”);
scanf(”%d”,&n); i=3
do i=4
{
printf (”\ni=%d”,i); i=5
i++;
}while(i<=n);
getch();
}

30.What is a flowchart? Explain with one example. 3M


ANSWER: same as 12 answer

31. Discuss about switch statement with an example. 4M


ANSWER: same as 20 answer
32. How to compile a given file in linux? Explain with one example. 2M
ANSWER: same as 13 answer

33. Explain about break and continue. 4M


ANSWER: same as 1 answer

34. Is there any difference between pre-increment and post-increment? Explain. 4M


ANSWER: same as 21 answer

35. Explain about nested if. 4M


ANSWER: same as 8 answer

36. Write an algorithm for finding biggest of among given three no’s. 4M
ANSWER:

ALGORITHM:
 It is a step – by – step procedure for solving a problem
Properties of an Algorithm
An algorithm must possess the following 5 properties. They are
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
Input: An algorithm must have zero (or) more number of inputs
Output: Algorithm must produce one (or) more number of outputs
Finiteness: An algorithm must terminate in countable number of steps
Definiteness: Each step of the algorithm must be stated clearly
Effectiveness: Each step of the algorithm must be easily convertible into program
statements

Algorithm for finding biggest of among given three no’s :

 Algorithm :
o Step 1 : Start
o Start 2 : Input a, b, c
o Start 3 : if a > b goto step 4, otherwise goto step 5
o Start 4 : if a > c goto step 6, otherwise goto step 8
o Start 5 : if b > c goto step 7, otherwise goto step 8
o Start 6 : Output "a is the largest", goto step 9
o Start 7 : Output "b is the largest", goto step 9
o Start 8 : Output " c is the largest", goto step 9
o Start 9 : Stop

37.What is identifier? What are the rules for identifier? 4M


ANSWER: same as 23 answer
LONG ANSWERS
3. Explain with a neat diagram about the digital computer organization and each of its
unit?
ANSWER:

Computer:
It is a high speed electronic device that accepts and stores input data and instructions, processes the
data and produces the desired output.

Input Output
(raw data / Instructions) (Informationi.e. processed data)

* It is made up of 2 major components


COMPUTER
* They are : 1) Hardware SYSTEM
2) Software

HARDWARE SOFTWARE

Computer Hardware :
 These are the physical components of a computer
 It consists of 5 Parts
1) Input Devices 4) Primary Storage
2) Output Devices 5) Secondary Storage
3) CPU
Block diagram of a Computer

ALU CU

Input Output
Devices Devices
Primary Memory

Secondary Memory
Input Devices
(e) These are used to enter data and programs into the computer
(f) These are for man to machine communication
(g) egs: Keyboard, mouse, scanner, touch screen, audio input.

Output Devices
 These are used to get the desired output from the computer
 These are for machine to man communication
 egs: Printer, Monitor, Speakers
 If the output is shown on monitor then it is called “Soft copy”
 If the output is printed on a paper using printer then it is called “hard copy”

CPU (Central Processing Unit)


 It is responsible for processing the instructions
 It consists of 3 parts
1) ALU – Arithmetic &Logic Unit
2) CU- Control Unit
3) Memory
 ALU: performs arithmetic operations like addition,subtraction,multiplication,division and
logical operations like comparisons among data
 CU: is responsible for movement of data inside the system
 Memory: is used for storage of data and programs. It is divided into 2 parts.
1) Primary Memory/ Main Memory
2) Secondary Memory / Auxilary Memory

1) Primary Memory
 It is also called main memory
 Data is stored temporarily i.e. data gets erased when computer is turned off
 Eg: RAM

2) Secondary Memory
 It is also called as auxilary memory
 Data is stored permanently so that user can reuse the data even after power loss.
 Eg: Hard disk, CD, DVD, Floppy etc.
5. Describe the various control structures available in ’C’?

ANSWER:
Control Structure
A statement that is used to control the flow of execution in a program is called control
structure. It combines instruction into logical unit. Logical unit has one entry point and one
exit point.

Types of control structures


1. Sequence
2. Selection
3. Repetition
4. Function call

1. Sequence: Statements are executed in a specified order. No statement is skipped and no


statement is executed more than once.

Flowchart:

For Example:
#include<stdio.h>
void main()
int a;
{
int a=5;
printf(“Square of a = %d”,a);
}

2. Selection:
It selects a statement to execute on the basis of condition. Statement is executed when the
condition is true and ignored when it is false e.g if, if else, switch structures.
Flowchart:

For Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int y;
clrscr();
printf("Enter a year:");
scanf("%d",&y);
if (y % 4==0)
printf("%d is a leap year",y);
elseprintf("%d is not a leap year".y)
getch();
}

3. Repetition:
In this structure the statements are executed more than one time. It is also known as iteration
or loop e.g while loop, for loop do-while loops etc.

Flow chart:
For Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
clrscr();
while(a<=5)
{
printf(“I Love Pakistan\n”);
a++;
} //end of while
} //end of main

4. Function call:
It is used to invite or call a piece of code or statement. In this case control jumps from main
program to that piece of code and then returns back to main program.

Flow chart:
8. Explain about different bit-wise operators with examples?

ANSWER:

Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand).

Operator Description

& Bitwise AND


Bit wise logical operators | Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
Bit wise shift operators
~ One’s complement

Bitwise AND Bitwise OR Bitwise XOR

a b a &b a b a|b a b a ^b
0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0

eg: let a= 12, b=10

a&b a|b

8 4 2 1 8 4 2 1
a =12 1 1 0 0 a =12 1 1 0 0
b =10 1 0 1 0 b =10 1 0 1 0
a &b 1 0 0 0 a|b 1 1 1 0

a&b = 8 a | b = 14
a^b

8 4 2 1
a =12 1 1 0 0
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6

Program
#include<stdio.h>
void main()
{
int a= 12, b = 10;
Output:
printf (“\n(a&b)= %d”,(a&b));
a&b=8
printf (“ \n(a|b)=%d”,(a|b)); a|b=14
printf (“\n(a^b)= %d”,(a^b)); a^b=6

Left Shift
 If the value of a variable is left shifted one time, then its value gets doubled
 eg: a = 10 then a<<1 = 20

32 16 8 4 2 1
a=10
1 0 1 0

a<<1 1 0 1 0 0 Fill it with zero

a<<1 = 20
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original value.
 eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0

a>>1 0 Discard it
1 0 1

a>>1 = 5
One’s complement
 It converts all ones to zeros and zeros to ones
 Eg: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1

~a
0 1 0

~a = 2
Program
#include<stdio.h>
void main()
{
int a= 20, b = 10,c=10;
printf (“ \n(a<<1)=%d”, a<<1);
printf (“ \n(b>>1)=%d”, b>>1);
printf (“\n(~c)= %d”, ~c);
}
Signed
1’s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1’s complement = [65535 – given no]

10. Explain any four basic types of constants with an example each?
ANS:
There are many different types of data values that are implicitly declared as constants in C.
The value of a constant cannot be changed during execution of the program, neither by the
programmer nor by the computer. The character 'A' is a constant having numerical value
equal to 65 in decimal number system.

Similarly 'B', 'C', etc., are other constant values, for instance, 'B'= 66, 'C' = 67, etc. In
any C program, the value of character 'A' cannot be changed. Similarly, a sequence of
characters enclosed between double quotes such as "Morning" is a string constant. Also, the
characters "\n" and "\t' are constants, which have special meaning for compiler, and are
known as escape sequences.

The digits or sequence of digits are also constants. These may be decimal digits (base 10),
octal digits (base 8), or hexadecimal digits (base 16). Sequences of digits of base 10 are
called decimal constants. Similarly, digital sequences of base 8 are called octal constants
and sequences of hexadecimal digits are called hexadecimal constants. Different codes are
used for their identification. The octal numbers are preceded by zero (0), and the hexadecimal
numbers are preceded by 0x or 0X. Therefore, a decimal sequence of digits should not start
with 0, because, in that case, it would be taken as octal number by the computer. C supports
several types of constants.

Integer Constants:

An integer constant is a sequence of digits from 0 to 9 without decimal points or fractional


part or any other symbols. There are 3 types of integers namely decimal integer, octal
integers and hexadecimal integer.
1). Decimal Integers:consists of a set of digits 0 to 9 preceded by an optional + or - sign.
Spaces, commas and non digit characters are not permitted between digits. Example for valid
decimal integer constants are
int y=123; //here 123 is a decimal integer constant.

2). Octal Integers:constant consists of any combination of digits from 0 through 7 with a O at
the beginning. Some examples of octal integers are

int X=O123; // here 0123 is a octal integer constant.

3). Hexadecimal integer:constant is preceded by OX or Ox, they may contain alphabets from
A to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of valid
hexadecimal integers are

int x=Ox12 // here Ox12 is a Hexa-Decimal integer constant

Real Constants:

Real Constants consists of a fractional part in their representation. Integer constants are
inadequate to represent quantities that vary continuously. These quantities are represented by
numbers containing fractional parts like 26.082.
Example of real constants are:

float x = 6.3; //here 6.3 is a double constant.


float y = 6.3f;//here 6.3f is a float constant.
float z = 6.3 e + 2; //here 6.3 e + 2 is a exponential constant.
float s = 6.3L ;//here 6.3L is a long double constant

Real Numbers can also be represented by exponential notation. The general form for
exponential notation is mantissa exponent. The mantissa is either a real number expressed in
decimal notation or an integer. The exponent is an integer number with an optional plus or
minus sign.

Single Character Constants:

A Single Character constant represent a single character which is enclosed in a pair of


quotation symbols.

Example for character constants are:

char p ='ok' ; // p will hold the value 'O' and k will be omitted
char y='u'; //y will hold the value 'u'
char k ='34' ; // k will hold the value '3, and '4' will be omitted
char e =' '; // e will hold the value ' ' , a blank space
chars ='\45';// swill hold the value ' ' , a blank space

All character constants have an equivalent integer value which are called ASCII Values.

String Constants:

A string constant is a set of characters enclosed in double quotation marks. The characters in
a string constant sequence may be a alphabet, number, special character and blank space.
Example of string constants are

"VISHAL" "1234" "God Bless" "!.....?"

Backslash Character Constants [Escape Sequences]

Backslash character constants are special characters used in output functions. Although they
contain two characters they represent only one character. Given below is the table of escape
sequence and their meanings.

Constant Meaning

'\a' .Audible Alert (Bell)

'\b' .Backspace
'\f' .Formfeed

'\n' .New Line

'\r' .Carriage Return

'\t' .Horizontal tab

'\v' .Vertical Tab

'\'' .Single Quote

'\"' .Double Quote

'\?' .Question Mark

'\\' .Back Slash

'\0' .Null

11. Describe the various types of operators available in ‘C’?


ANSWER:

C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform a certain mathematical or logical manipulation. Operators are used in
programs to manipulate data and variables.

C operators can be classified into following types:

(i) Arithmetic operators


(ii) Relational operators
(iii) Logical operators
(iv) Bitwise operators
(v) Assignment operators
(vi) Conditional operators
(vii) Special operators
(viii) Increment and decrement operators
Arithmetic operators:

C supports all the basic arithmetic operators. The following table shows all the basic
arithmetic operators.

Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one

Relational operators:

The following table shows all relation operators supported by C.

Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Logical operators:

C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

Bitwise operators:

Bitwise operators perform manipulations of data at bit level. These operators also perform
shifting of bits from right to left. Bitwise operators are not applied to float or double(These
are datatypes, we will learn about them in the next tutorial).

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

The bitwise shift operator, shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value have
to be shifted. Both operands have the same precedence.

Example:

a = 0001000
b=2
a << b = 0100000
a >> b = 0000010

Assignment Operators:

Assignment operators supported by C language are as follows.

Operator Description Example


= assigns values from right side operands to left side operand a=b
adds right operand to the left operand and assign the result to a+=b is same as
+=
left a=a+b
subtracts right operand from the left operand and assign the a-=b is same as
-=
result to left operand a=a-b
mutiply left operand with the right operand and assign the a*=b is same as
*=
result to left operand a=a*b
divides left operand with the right operand and assign the a/=b is same as
/=
result to left operand a=a/b
calculate modulus using two operands and assign the result to a%=b is same as
%=
left operand a=a%b

Conditional operator:

The conditional operators in C language are known by two more names

“Ternary Operator” and“? : Operator”


It is actually the if condition that we use in C language decision making, but using
conditional operator, we turn the if condition statement into a short and simple operator.

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3;

Explanation:

 The question mark "?" in the syntax represents the if part.


 The first expression (expression 1) generally returns either true or false, based on
which it is decided whether (expression 2) will be executed or (expression 3)
 If (expression 1) returns true then the expression on the left side of " : "i.e
(expression 2) is executed.
 If (expression 1) returns false then the expression on the right side of " : "i.e
(expression 3) is executed.

Special operator:
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
* Pointer to a variable *x ; will be pointer to a variable x

Increment and decrement operators:

a) Increment operator (++):


 It is used to increment the value of a variable by 1.
 2 types : i) pre increment
ii) post increment
 increment operator is placed before the operand in preincrement and the value is first
incremented and then operation is performed on it.

eg: z = ++a; a= a+1


z=a

 increment operator is placed after the operand in post increment and the value is
incremented after the operation is performed
eg: z = a++; z=a
a= a+1

b) Decrement operator : (- -)
 It is used to decrement the values of a variable by 1.
2 types : i) pre decrement ii) post decrement
 decrement operator is placed before the operand in predecrement and the value is first
decremented and then operation is performed on it.

eg: z = - - a; a= a-1
z=a

 decrement operator is placed after the operand in post decrement and the value is
decremented after the operation is performed

eg: z = a--; z=a


a= a-1

16.Explain about the logical and shift operators with examples?


ANSWER:
Logical Operators
 These are used to combine 2 (or) more expressions logically
 They are logical AND (&&) logical OR ( || ) and logical NOT (!)
Logical AND (&&)

exp1 exp2 exp1&&exp2


T T T
T F F
F T F
F F F

Logical OR( || )

exp1 exp2 exp1||exp2


T T T
T F T
F T T
F F F

Logical NOT (!)

exp !(exp)
T F
F T

Operator Description Example a =10, b=20,c=30 output


&& logical AND (a>b) && (a<c) (10>20) && (10<30) 0
|| logical OR (a>b) | | (a<c) (10>20) ||(10<30) 1
! logical NOT ! (a>b) ! (10>20) 1
Program:
#include<stdio.h>
void main()
{ Input: enter the values of a&b= 10 20

inta,b; Output:
printf(“Enter the values of a&b=”); (a>b) && (a<b)=0
(a>b) || (a<b) =1
scanf(“%d%d”,&a,&b); !(a>b)=1
printf (“\n(a>b) && (a<c)=%d”, (a>b) && (a<b));
printf (“\n(a>b) || (a<b)%d”, (a>b) || (a<b));
printf (“\n!(a>b)=%d”, !(a>b));
}

Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand).

Operator Description

& Bitwise AND


Bit wise logical operators | Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
Bit wise shift operators
~ One’s complement

Left Shift
 If the value of a variable is left shifted one time, then its value gets doubled
 eg: a = 10 then a<<1 = 20

32 16 8 4 2 1
a=10
1 0 1 0

a<<1 1 0 1 0 0 Fill it with zero

a<<1 = 20
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original value.
 eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0

a>>1 0 Discard it
1 0 1

a>>1 = 5
One’s complement
 It converts all ones to zeros and zeros to ones
 Eg: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1

~a
0 1 0

~a = 2
Program
#include<stdio.h>
void main()
{
int a= 20, b = 10,c=10;
printf (“ \n(a<<1)=%d”, a<<1);
printf (“ \n(b>>1)=%d”, b>>1);
printf (“\n(~c)= %d”, ~c);
}
Signed
1’s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1’s complement = [65535 – given no]
17. Explain about relational and logical operators with examples
ANSWER:

Relational operators:
 These are used for comparing two expressions.

Operator Description Examble a =10, b=20 output


< less than a<b 10<20 1
<= less than (or) equal a<=b 10< = 20 1
to
> greater than a>b 10>20 0
>= greater than (or) a>=b 10> =20 0
equal to
== equal to a= =b 10 = = 20 0
!= not equal to a! = b 10 ! =20 1
 The output of a relational expression is either true (1) (or) false (0)
 Program
#include<stdio.h>
void main()
{inta,b;
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
Input: enter the values of a&b= 10 20
printf (“ \n(a<b)=%d”, a<b);
printf (“\n(a<=b)= %d”, a<=b); Output:
(a<b)=1
printf (“\n(a>b)=%d”, a>b); (a<=b)=1
printf (“\n(a>=b)=%d”, a>=b); (a>b)=0
(a>=b)=0
printf (“\n(a==b)=%d”, a==b); (a==b)=0
printf (“\n(a!=b)=%d”, a!=b); (a!=b)=1
}
Logical Operators:
 These are used to combine 2 (or) more expressions logically
 They are logical AND (&&) logical OR ( || ) and logical NOT (!)
Logical AND (&&)

exp1 exp2 exp1&&exp2


T T T
T F F
F T F
F F F
Logical OR( || )

exp1 exp2 exp1||exp2


T T T
T F T
F T T
F F F

Logical NOT (!)

exp !(exp)
T F
F T

Operator Description Example a =10, b=20,c=30 output


&& logical AND (a>b) && (a<c) (10>20) && (10<30) 0
|| logical OR (a>b) | | (a<c) (10>20) ||(10<30) 1
! logical NOT ! (a>b) ! (10>20) 1

Program:
#include<stdio.h>
void main()
{ Input: enter the values of a&b= 10 20

inta,b; Output:
printf(“Enter the values of a&b=”); (a>b) && (a<b)=0
(a>b) || (a<b) =1
scanf(“%d%d”,&a,&b); !(a>b)=1
printf (“\n(a>b) && (a<c)=%d”, (a>b) && (a<b));
printf (“\n(a>b) || (a<b)%d”, (a>b) || (a<b));
printf (“\n!(a>b)=%d”, !(a>b));
}
18. Explain about arithmetic and relational operators with examples.

ANSWER:

Arithmetic operator:
 These operators are used for numerical calculations (or) to perform arithmetic operations
like addition, subtraction etc.

Operator Description Example a =20, b=10 output


+ Addition a+b 20+10 30
- Subtraction a-b 20-10 10
* Multiplication a*b 20*10 200
/ Division a/b 20/10 2 (quotient)
% Modular division a%b 20%10 0 (remainder)

 Program:
#include<stdio.h>
void main()
{
inta,b;
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
Input: enter the values of a&b= 10 20
printf (“ \n(a+b)=%d”, a+b);
printf (“\n(a-b)= %d”, a-b); Output:
(a+b)=30
printf (“\n(a*b)=%d”, a*b); (a-b)=-10
printf (“\n(a/b)=%d”, a/b); (a*b)=20
(a/b)=0
printf (“\n(a%b)=%d”, a%b); (a%b)=10
}
Relational operators:
 These are used for comparing two expressions.

Operator Description Examble a =10, b=20 output


< less than a<b 10<20 1
<= less than (or) equal a<=b 10< = 20 1
to
> greater than a>b 10>20 0
>= greater than (or) a>=b 10> =20 0
equal to
== equal to a= =b 10 = = 20 0
!= not equal to a! = b 10 ! =20 1
 The output of a relational expression is either true (1) (or) false (0)
 Program
#include<stdio.h>
void main()
{inta,b;
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
Input: enter the values of a&b= 10 20
printf (“ \n(a<b)=%d”, a<b);
printf (“\n(a<=b)= %d”, a<=b); Output:
(a<b)=1
printf (“\n(a>b)=%d”, a>b); (a<=b)=1
printf (“\n(a>=b)=%d”, a>=b); (a>b)=0
(a>=b)=0
printf (“\n(a==b)=%d”, a==b); (a==b)=0
printf (“\n(a!=b)=%d”, a!=b); (a!=b)=1
}

19. Give the detail explanation about data types.


Data Types:
 Data type specifies the set of values and the type of data that can be stored in a variable.
 They allow the programmer to select the type appropriate to the needs of application.
Types :
1). Primary data types
2). Derived data types
3). User defined data types
1. Primary data types
‘C’ compilers support 4 fundamental data types
They are
5) integer
6) character
7) Floating – point
8) Double precision floating point
Primrary Data Types

Integral Type

Integer
character
Signed Unsigned
signed char
int unsigned int
short int unsigned short int unsigned char
long int unsigned long int

Floating point type

float double long double

1. Integral data type


 Integral data types are used to store whole numbers and characters
 It is further classified into
c) integer data type
d) character data type
a) Integer data type
 This data type is used to store whole numbers
 It has 3 classes of integer storage namely, short int, int and long int in both signed and
unsigned forms

Integer Data type


Type size (in bytes) Range Control string
Short int (or) 1 -128 to 127 %h
signed short int
Unsigned short int 1 0 to 255 % uh
int (or) signed int 2 -32768 to 32767 % d or %i
unsigned int 2 0 to 65535 %u
Long int (or) signed 4 -2147483648 to %ld
long int 2147483647
Unsigned long int 4 0 to 4294967295 %lu
b) character data type
 This data type is used to store characters
 These characters are internally stored as integers
 Each character has an equivalent ASCII value
eg: ‘A’ has ASCII value 65
Character data type
Type Size (in bytes) Range Control string
Char (or) signed 1 - 128 to +127 %c
char
Unsigned char 1 0 to 255 %c

2. Floating – point Data types


 It is used to store real numbers (i.e., decimal point numbers).
 For 6 digits of accuracy, ‘float’ is used.
 For 12 digits of accuracy, ‘double' is used.
 For more than 12 digits of accuracy, ‘long double’ is used..

Floating point data type


Type Size (in bytes) Range Control string
float 4 3.4 E – 38 to 3.4 E + 38 %f
double 8 1.7 E – 308 to 1.7 E +308 %lf
long double 10 3.4 E – 4932 to 1.1 E +4932 %lf

2). Derived data types:


 Those data types which are derived from fundamental data types are called derived data types.
 There are basically three derived data types .

(i). Array: A finite collection of data of same types or homogenous data type.
(ii). String: An array of character type.
(iii). Structure: A collection of related variables of the same or different or heterogeneous data types.

3). User defined data types:

 By using a feature known as "type definition" that allows user to define an identifier that
would represent a data type using an existing data type.
 We can create user-defined data types in two ways:

(i). By using the “typedef” keyword - The “typedef” keyword can be used to
declare an identifier as a user-defined data type.
(ii). By using the “enum” keyword - The “enum” is used to declare identifiers
as user-defined data types. Such data types are also called as
enumerations.

 Advantage :

1. Main advantage of typedef is that we can create meaningful data type


names for increasing the readability of the program.
27. Explain about type conversions. Why there is a need to have them? Explain with
suitable example

ANSWER:

 A type cast is basically a conversion from one type to another.


 There are two types of type conversion :
 IMPLICIT TYPE CONVERSION(automatic type conversion)
 EXPLICIT TYPE CONVERSION(type casting)

Implicit Conversions:

 Also known as ‘automatic type conversion’.


 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is present.
In such condition type conversion (type promotion) takes place to avoid lose of
data.
 All the data types of the variables are upgraded to the data type of the variable
with largest data type.
 The following rules have to be followed while converting the expression from one
type to another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
 It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).

Example of Type Implicit Conversion:


#include<stdio.h>
int main()
{ int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII value of 'a' is 97


x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}

Output: x = 107, z = 108.000000

Explicit Conversions:
 This process is also called type casting and it is user defined. Here the user can type
cast the result to make it of a particular data type.
 The syntax in C: ( type ) expression
Here, type indicated the data type to which the final result is converted.

Example of Explicit Type Casting Conversion:

#include<stdio.h>
int main()
{ double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

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


return 0;
}

Output: sum = 2

Advantages of Type Conversion:


 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps us to compute expressions containing variables of different data types.

39. Explain about C Preprocessor with an example

ANSWER:
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives −

Sr.No. Directive & Description


#define
1
Substitutes a preprocessor macro.
#include
2
Inserts a particular header from another file.
#undef
3
Undefines a preprocessor macro.
#ifdef
4
Returns true if this macro is defined.
#ifndef
5
Returns true if this macro is not defined.
#if
6
Tests if a compile time condition is true.
#else
7
The alternative for #if.
#elif
8
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.
#pragma
11
Issues special commands to the compiler, using a standardized method.

Preprocessors Examples

Analyze the following examples to understand various directives.

#define MAX_ARRAY_LENGTH 20

This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#define for constants to increase readability.

#include <stdio.h>
#include "myheader.h"

These directives tell the CPP to get stdio.h from System Libraries and add the text to the
current source file. The next line tells CPP to get myheader.h from the local directory and
add the content to the current source file.

#undef FILE_SIZE
#define FILE_SIZE 42

It tells the CPP to undefine existing FILE_SIZE and define it as 42.

#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif

It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.

#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you
pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define
DEBUG, so you can turn debugging on and off on the fly during compilation.

47. How is data type promotion done in an expression?

ANSWER:

Data types can be classified into groups of related data types. Within such groups, a
precedence order exists where one data type is considered to precede another data type.

You use the rules of precedence to allow the promotion of one data type to a data type later in
the precedence ordering.
Numeric type promotion:
Numeric datatypes are promoted in expressions according to the following rules:
Table 1. Numeric type promotion
Largest type in expression Resulting type
DOUBLE DOUBLE
REAL DOUBLE
DECIMAL DECIMAL
BIGINT BIGINT
INTEGER INTEGER
SMALLINT INTEGER

Numeric expressions that involve DECIMAL datatypes can result in a value of a


different scale and precision than the operands of the expression.

Numeric type casting:


When you explicitly cast values between numeric datatypes, be aware of the
following guidelines:

 You can generate an error if you try to cast a value that is too large to be
represented by the target datatype.
 When you store floating point or decimal values in an integer datatype, the
result is a silent truncation of the fractional part of the value.
 You can convert integer datatypes to decimal values, but there might be a loss
of precision.

48. Illustrate the use of special control constructs goto, break, continue and return.

ANSWER:

break, continue and goto statements

The break; continue; and goto; statements are used to alter the normal flow of a program.

Loops perform a set of repetitive task until text expression becomes false but it is sometimes
desirable to skip some statement/s inside loop or terminate the loop immediately without
checking the test expression. In such cases, break and continue statements are used.

break statement:

In C programming, break statement is used with conditional if statement.


The break is used in terminating the loop immediately after it is encountered.
it is also used in switch...case statement. which is explained in next topic.

Syntax: break;

The break statement can be used in terminating loops like for, while and do...while
Example:

//Write a C Program Which use of break statement.

#include<stdio.h>
void main()
{
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");

scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n")
}

sum=sum+num;
}
printf("Total is %d",sum);
}

Output:

Command Prompt
Note: Enter Zero for break loop!
Enter Number of inputs
5
Enter num1: 5
Enter num2: 10
Enter num3: 0
Loop Breaked
Total is 15

continue statement:
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statement is used.

Syntax: continue;

Just like break, continue is also used with conditional if statement.


Example:

//Write a C Program Which use of continue statment.

#include<stdio.h>
void main(){
inti, n=20;
for(i=1;i<=n;++i){
if(i % 5 == 0) {
printf("pass\n");
continue; /*this continue the execution of loop if i % 5 == 0 */
}
printf("%d\n",i);
}
}

Output:
Command Prompt
1
2
3
4
pass
6
7
8
9
pass
11
12
13
14
pass
16
17
18
19
Pass
goto statement:

In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.

Syntax:

goto label;
.............
.............
.............
label:
statement;

In this syntax, label is an identifier.

When, the control of program reaches to goto statement, the control of the program will jump
to the label: and executes the code below it.

Example:

//Write a C Program Which Print 1 To 10 Number Using goto statement.


#include<stdio.h>
void main()
{
inti=1;
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
}

Output:
Command Prompt
1
2
3
4
5
6
7
8
9
10

NOTE:
Though goto statement is included in ANSI standard of C, use of goto statement should
be reduced as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled.
In modern programming, goto statement is considered a harmful construct and a bad
programming practice.
The goto statement can be replaced in most of C program with the use of break and
continue statements.
In fact, any program in C programming can be perfectly written without the use of goto
statement.
All programmer should try to avoid goto statement as possible as they can.

50.What is the purpose of the comma operator? Within which control statement does
the comma operator usually appear?

ANSWER:
C Programming Comma Operator

#include<stdio.h>
void main() {
int num1 = 1, num2 = 2;
int res;
res = (num1, num2);
printf("%d", res);
}

Explanation:

Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated at
last.
Comma operator returns the value of the rightmost operand when multiple comma
operators are used inside an expression.
Comma Operator Can acts as –
Operator : In the Expression
Separator : Declaring Variable , In Function Call Parameter List

Usage of Comma Operator


Consider above example –
Comma as Separator

int num1 = 1, num2 = 2;

It can acts as Seperator in –

Function calls
Function definitions
Variable declarations
Enum declarations

Comma as Operator

res = (num1, num2);

In this case value of rightmost operator will be assigned to the variable. In this case value of
num2 will be assigned to variable res.
Examples of comma operator :

Comma Operator have lowest priority in C Programming Operators. All possible operations
that can be performed on comma operator are summarized below –

Verity 1 : Using Comma Operator along with Assignment

#include<stdio.h>
int main()
{
inti;
i = 1,2,3;
printf("i:%d\n",i);
return 0;
}

Output :

i:1

Explanation :

i = 1,2,3;

Above Expression contain 3 comma operator and 1 assignment operator.


If we check precedence table then we can say that “Comma” operator has lowest
precedence than assignment operator
So Assignment statement will be executed first .
1 is assigned to variable “i”.
Verity 2 : Using Comma Operator with Round Braces

#include<stdio.h>
int main()
{
int i;
i = (1,2,3);
printf("i:%d\n",i);
return 0;
}

Output : i:3

Explanation :

i = (1,2,3);

Bracket has highest priority than any operator.


Inside bracket we have 2 comma operators.
Comma operator has associativity from Left to Right.
Comma Operator will return Rightmost operand

i = (1,2,3)
==> 1,2 will return 2
==> 2,3 will return 3
==>means (1,2,3) will return 3
==> Assign 3 to variable i.

Verity 3 : Using Comma Operator inside printf statement

#include<stdio.h>
void main()
{
printf("Computer","Programming");
}

Output : Computer

You might feel that answer of this statement should be “Programming” because comma
operator always returns rightmost operator, in case of printf statement once comma is read
then it will consider preceding things as variable or values for format specifier.

Verity 4 : Using Comma Operator inside Switch cases.


#include<stdio.h>
void main()
{
int choice = 2 ;
switch(choice)
{
case 1,2,1: printf("\nAllas");
break;
case 1,3,2: printf("\nBabo");
break;
case 4,5,3: printf("\nHurray");
break;
}
}

Output : Babo

Verity 5 : Using Comma Operator inside For Loop

#include<stdio.h>
int main()
{
int i,j;

for(i=0,j=0;i<5;i++)
{
printf("\nValue of J : %d",j);
j++;
}
return(0);
}

Output :
Value of J : 0
Value of J : 1
Value of J : 2
Value of J : 3
Value of J : 4

Verity 6 : Using Comma Operator for multiple Declaration

#include<stdio.h>
int main()
{
int num1,num2;
int a=10,b=20;
return(0);
}

You might also like