Professional Documents
Culture Documents
Give The Use of Break and Continue With An Example. 3M Answer
Give The Use of Break and Continue With An Example. 3M Answer
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.
# include <stdio.h>
int main()
{
inti;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
Output:
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.
continue Statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
# include <stdio.h>
int main()
{
inti;
double number, sum = 0.0;
printf("Sum = %.2lf",sum);
return 0;
}
Output:
When the user enters negative number, the continue statement is executed and skips the
negative number from calculation.
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
Compiler /
High level language program Machine Language code
Interpreter
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.
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.
#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
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.
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.
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
PROGRAM CODE:
#include <stdio.h>
#include <math.h> // Used for pow() function
int main()
{
double base, expo, power;
/* Calculates base^expo */
power = pow(base, expo);
return 0;
}
Input:
Enter base: 2
Enter exponent: 2
Output: 2 ^ 2 = 4
11. What is preprocessor? 3
ANSWER:
The following section lists down all the important preprocessor directives −
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.
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.
Arrows are used for connecting the symbols and show the flow of execution.
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
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;
}
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
Definition
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.
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
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 =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
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 ++ ;
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.
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.
28.What are formatted input and output statements in C? Give suitable examples. 4M
ANSWER: same as 3 answer
Syntax:
//while
while(condition is true)
{
Group of statements;
}
//do-while
do
{
Group of statements;
}while(condition is true);
EXAMPLE :-
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 :
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
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)
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”
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.
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
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
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 = 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:
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
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
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:
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.
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
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
'\b' .Backspace
'\f' .Formfeed
'\0' .Null
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 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:
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:
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
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:
Conditional operator:
Explanation:
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 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
Logical OR( || )
exp !(exp)
T F
F T
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
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 = 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.
exp !(exp)
T F
F T
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.
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.
Integral Type
Integer
character
Signed Unsigned
signed char
int unsigned int
short int unsigned short int unsigned char
long int unsigned long int
(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.
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 :
ANSWER:
Implicit Conversions:
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.
#include<stdio.h>
int main()
{ double x = 1.2;
Output: sum = 2
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 −
Preprocessors Examples
#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
#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.
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
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:
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:
Syntax: break;
The break statement can be used in terminating loops like for, while and do...while
Example:
#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;
#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;
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:
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
Function calls
Function definitions
Variable declarations
Enum declarations
Comma as Operator
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 –
#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;
#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);
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.
#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.
Output : Babo
#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
#include<stdio.h>
int main()
{
int num1,num2;
int a=10,b=20;
return(0);
}