0% found this document useful (0 votes)
23 views36 pages

Chapter 2

Uploaded by

Priyansh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views36 pages

Chapter 2

Uploaded by

Priyansh Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

PPS (3110003)

CHAPTER 2
Fundamentals of C

Q.1 Distinguish the data types provided by C programming language. OR

Explain the different data types of C language (PPS WIN2019) (CPU_WIN_2017)


(CPU_WIN_2014)

There are some common data types in C :


• int − Used to store an integer value.
• char − Used to store a single character.
• float − Used to store decimal numbers with single precision.
• double − Used to store decimal numbers with double precision.
Data Types can also be classified as :Primitive, Derived and User Defined.

• Primitive data types are the first form – the basic data types (int,char,float,double).
• Derived data types are a derivative of primitive data types known as arrays, pointer and
function.
• User defined data types are those data types which are defined by the user/programmer
himself.

Q.2 Implement a C Program to convert temperature from Fahrenheit to Celsius and vice
versa. (PPS_WIN2019)

CKPCET, SURAT 1
PPS (3110003)

#include <stdio.h>

int main()

float fh,cl;

int choice;

printf("\n1: Convert temperature from Fahrenheit to Celsius.");

printf("\n2: Convert temperature from Celsius to Fahrenheit.");

printf("\nEnter your choice (1, 2): ");

scanf("%d",&choice);

if(choice ==1){

printf("\nEnter temperature in Fahrenheit: ");

scanf("%f",&fh);

cl= (fh - 32) / 1.8;

printf("Temperature in Celsius: %.2f",cl);

else if(choice==2){

printf("\nEnter temperature in Celsius: ");

scanf("%f",&cl);

fh= (cl*1.8)+32;

printf("Temperature in Fahrenheit: %.2f",fh);

else{

printf("\nInvalid Choice !!!");

CKPCET, SURAT 2
PPS (3110003)

return 0;}

Output

First Run:

1: Convert temperature from Fahrenheit to Celsius.

2: Convert temperature from Celsius to Fahrenheit.

Enter your choice (1, 2): 1

Enter temperature in Fahrenheit: 98.6

Temperature in Celsius: 37.00

Second Run:

1: Convert temperature from Fahrenheit to Celsius.

2: Convert temperature from Celsius to Fahrenheit.

Enter your choice (1, 2): 2

Enter temperature in Celsius: 37.0

Temperature in Fahrenheit: 98.60

Third Run:

1: Convert temperature from Fahrenheit to Celsius.

2: Convert temperature from Celsius to Fahrenheit.

Enter your choice (1, 2): 3

Invalid Choice !!!

Q.3 Explain different types of constants.(PPS_WIN_2019)

TYPES OF C CONSTANT:

1. Integer constants
2. Real or Floating point constants

CKPCET, SURAT 3
PPS (3110003)

3. Octal & Hexadecimal constants


4. Character constants
5. String constants
6. Backslash character constants

1.INTEGER CONSTANTS IN C:

• An integer constant must have at least one digit.


• It must not have a decimal point.
• It can either be positive or negative.
• No commas or blanks are allowed within an integer constant.
• If no sign precedes an integer constant, it is assumed to be positive.
• The allowable range for integer constants is -32768 to 32767.

2. REAL CONSTANTS IN C:

• A real constant must have at least one digit


• It must have a decimal point
• It could be either positive or negative
• If no sign precedes an integer constant, it is assumed to be positive.
• No commas or blanks are allowed within a real constant.

3. CHARACTER AND STRING CONSTANTS IN C:

• A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single quotes.
• The maximum length of a character constant is 1 character.
• String constants are enclosed within double quotes.

4. BACKSLASH CHARACTER CONSTANTS IN C:

• There are some characters which have special meaning in C language.


• They should be preceded by backslash symbol to make use of special function of
them.

Q.4 Explain getch(), getchar(), gets().(PPS_WIN_2019)

getch ():getch () function reads character from keyboard.

getchar():The C library function int getchar(void) gets a character (an uns igned char)
from stdin.

Syntax:

int getchar(void);

CKPCET, SURAT 4
PPS (3110003)

gets():The C library function char *gets(char *str) reads a line from stdin and stores it
into the string pointed to by str.

Syntax:

char *gets(char *str)

Q.5 Explain various Operators used in C language. OR


List out the operators used in C language and explain any three with
example.(PPS_WIN_2019) (PPS_WIN_18) .(CPU_WIN_2017) (CPU_WIN_2015)
(CPU_WIN_2014) (CPU_WIN_2013)
C operators can be classified into following types:

• Arithmetic operators
• Relational operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Special operators

Arithmetic operators

C supports all the basic arithmetic operators. The following table shows all th e 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.

CKPCET, SURAT 5
PPS (3110003)

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

&& Logical AND

|| Logical OR

! Logical NOT
Q.6 Write a program to find sum of first N odd numbers. Ex. 1+3+5+7+………..+N
(PPS_WIN_2019) . (CPU_WIN_2013)

#include <stdio.h>

void main()

int i,n,sum=0;

printf("Input number of terms : ");

scanf("%d",&n);

printf("\nThe odd numbers are :");

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

CKPCET, SURAT 6
PPS (3110003)

printf("%d ",2*i-1);

sum+=2*i-1;

printf("\nThe Sum of odd Natural Number upto %d terms : %d \n",n,sum);

Q.7 Show the important of stdio.h header file.(PPS_WIN_2019)

stdio.h is a header file used in c language for input output operations. It is a header file or
library for Standard Input and Output as it shows by name std(Standard)-i(input)-o(output).
The function printf, Scanf, gets, puts etc will not work and will not be able to provide any
input to program or get output from the program. This is useful for getting the input from
the user(Keyboard) and output result text to the monitor(screen).

Q.8 What is various types of operator available in C. .(CPU_WIN_2019)


Operator in C
An operator is a symbol that tells the compiler to perform specific mathematical or logical
calculations on operands(variables).
Types of operators available in C
• Assignment operator
• Arithmetic / Mathmetical operator
• Increment Decrement operator
• Relational operator
• Logical operator
• Conditional or Ternary operator
• Binary operator
• Unary operator
Arithmetic Operators are used to performing mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%)
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

CKPCET, SURAT 7
PPS (3110003)

Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or -x and x−−means x=x-1
Operator Description
++ Increment
−− Decrement
Relational operators are used to comparing two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
C provides three logical operators when we test more than one condition to make decisions. These
are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).
Operator Description
&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to False, the result is
False)
|| Or operator. It performs a logical disjunction on two expressions. (if either or both
expressions evaluate to True, the result is True)
! Not operator. It performs logical negation on an expression.

C provides a special operator for bit operation between two variables.


Operator Description
<< Binary Left Shift Operator
>> Binary Right Shift Operator
~ Binary Ones Complement Operator
& Binary AND Operator
^ Binary XOR Operator
| Binary OR Operator

CKPCET, SURAT 8
PPS (3110003)

Assignment operators applied to assign the result of an expression to a variable. C has a collection
of shorthand assignment operators.
Operator Description
= Assign
+= Increments then assign
-= Decrements then assign
*= Multiplies then assign
/= Divides then assign
%= Modulus then assign
<<= Left shift and assign
>>= Right shift and assign
&= Bitwise AND assign
^= Bitwise exclusive OR and assign
|= Bitwise inclusive OR and assign
C offers a ternary operator which is the conditional operator (?: in combination) to construct
conditional expressions.
Operator Description
?: Conditional Expression
Binary operator
Binary operators are those operators that works with at least two operands such as (Arithmetic
operators) +, -, *, /, %.
Unary operator
Unary operators are those operators that works with singal operands such as (Increment or
Decrement operators) ++ and --.
C supports some special operators
Operator Description
sizeof() Returns the size of a memory location.
& Returns the address of a memory location.
* Pointer to a variable.

CKPCET, SURAT 9
PPS (3110003)

Q.9 What is difference between keywords and identifiers? Explain rules for naming an
identifier.(CPU_WIN_2019) (CPU_SUM_2015)

BASIS FOR
KEYWORD IDENTIFIER
COMPARISON

Basic Keywords are the reserved Identifiers are the user defined names of
words of a language. variable, function and labels.

Use Specify the type/kind of entity. Identify the name of a particular entity.

Format Consider only letters. Consider letters, underscore, digits.

Case Use only lowercase. Lower and upper cases, both are allowed.

Symbol No special symbol, No punctuation or special symbol except


punctuation is used. 'underscore' is used.

Classification Keywords are not further Identifier are classified into 'external
classified. name' and 'internal name'.

Starting letter It always starts with a First character can be a uppercase,


lowercase letter. lowercase letter or underscore.

CKPCET, SURAT 10
PPS (3110003)

BASIS FOR
KEYWORD IDENTIFIER
COMPARISON

Example int, char, if, while, do, class Test, count1, high_speed, etc.
etc.

Rules for an Identifier


• An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
• The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore (_).
• Identifiers are also case sensitive in C. For example name and Name are two different
identifiers in C.
• Keywords are not allowed to be used as Identifiers.
• No special characters, such as semicolon, period, whitespaces, slash or comma are
permitted to be used in or as Identifier.
Q.10 (a) Distinguish between the following pairs: .(CPU_WIN_2019) (CPU_WIN_2016)
1) getchar and scanf functions
scanf is a C function to read input from the standard input until encountering whitespace,
newline or EOF while getchar is a C function to read a character only from the standard input
stream(stdin), which is the keyboard.
2) %s and %c specifications for reading.
%c is used for reading one character. Like ‘a’, ‘b’, ‘1’, ‘2’
But %s is used for reading a set of character. “a”, “abcdefgh”
3) %s and %[ ] specifications for reading.
%[^\n] is for reading string until hit to \n or EOF. Whitespaces can be included in the string.
%s is for reading string until hit to whitespace or EOF.
Q.11 Describe local and global variable with example.
Global variables are declared outside any function, and they can be accessed (used) on any
function in the program.
Local variables are declared inside a function, and can be used only inside that function. It is
possible to have local variables with the same name in different functions. Even the name is
the same, they are not the same. It's like two people with the same name. Even the name is the
same, the persons are not.

CKPCET, SURAT 11
PPS (3110003)

EXAMPLE
// Global variable
float a = 1;
void my_test()
{
// Local variable called b.
// This variable can't be accessed in other functions
float b = 77;
println(a);
println(b);
}
void setup()
{
// Local variable called b.
// This variable can't be accessed in other functions.
float b = 2;
println(a);
println(b);
my_test();
println(b);
}

Q.12 Describe precedence and associativity of operators with example. (PPS_WIN_18)


(CPU_WIN_2015)
Precedence of operators
If more than one operators are involved in an expression, C language has a predefined rule of
priority for the operators. This rule of priority of operators is called operator precedence.
In C, precedence of arithmetic operators( *, %, /, +, -) is higher than relational operators(==, !=,
>, <, >=, <=) and precedence of relational operator is higher than logical operators(&&, || and !).
Example of precedence
(1 > 2 + 3 && 4)

CKPCET, SURAT 12
PPS (3110003)

This expression is equivalent to:


((1 > (2 + 3)) && 4)
i.e, (2 + 3) executes first resulting into 5
then, first part of the expression (1 > 5) executes resulting into 0 (false)
then, (0 && 4) executes resulting into 0 (false)
Output
0
Associativity of operators
If two operators of same precedence (priority) is present in an expression, Associativity of
operators indicate the order in which they execute.
Example of associativity
1 == 2 != 3
Here, operators == and != have same precedence. The associativity of both == and != is left to
right, i.e, the expression on the left is executed first and moves towards the right.
Thus, the expression above is equivalent to :
((1 == 2) != 3)
i.e, (1 == 2) executes first resulting into 0 (false)
then, (0 != 3) executes resulting into 1 (true)
Output
1
Q.13 What do you mean by type conversion? Give example. (PPS_WIN_18)
.(CPU_WIN_2017)
The type conversion process in C is basically converting one type of data type to other to perform
some operation. The conversion is done only between those datatypes wherein the conversion is
possible eg:char to int and vice versa.
1) Implicit Type Conversion
This type of conversion is usually performed by the compiler when necessary without any
commands by the user. Thus it is also called "Automatic Type Conversion".
EXAMPLE:
#include<stdio.h>
int main()
{

CKPCET, SURAT 13
PPS (3110003)

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
2) Explicit Type Conversion
Explicit type conversion rules out the use of compiler for converting one data type to another
instead the user explicitly defines within the program the datatype of the operands in the
expression.
EXAMPLE:
#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
Q.14 Write a program that reads two numbers from key board and gives their addition,
subtraction, multiplication, division and modulo. (CPU_WIN_2016)
#include<stdio.h>
#include<conio.h>
void main()
{

CKPCET, SURAT 14
PPS (3110003)

int value1, value2, addition, subtraction, multiply;


float divide,mod;
printf("\n Enter the value1: ");
scanf("%d",&value1);
printf("\n Enter the value2: ");
scanf("%d",&value2);
addition = value1 + value2;
subtraction = value1 - value2;
multiply = value1 * value2;
divide = value1 / (float)value2;
mod = value1 % value2;
printf("\n Addition = %d + %d = %d",value1,value2,addition);
printf("\n Subtraction = %d - %d = %d",value1,value2,subtraction);
printf("\n Multiplication = %d * %d = %d",value1,value2,multiply);
printf("\n Division = %d / %d = %.0f",value1,value2,divide);
printf("\n Modulo = %d MOD %d = %.0f",value1,value2,mod);
}
OUTPUT:
Enter the value1: 20
Enter the value2: 20
Addition = 20+20=40
Subtraction =20-20=0
Multiplication =20*20=400
Division =20/20=1
Modula =20 MOD 20=0
Q.15 Develop an application program to convert and print distance between two cities in
meters, feet, inches & centimeters. The distance between two cities (In KM) is input through
key board. (CPU_WIN_2016)
#include<stdio.h>
int main()

CKPCET, SURAT 15
PPS (3110003)

{
float km, m, cm, f, in;
printf("Enter distance in kilometers: ");
scanf("%f", &km);
/* calculate the conversion */
m = km * 1000;
cm = km * 1000 * 100;
f = km * 3280.84;
in = km * 39370.08;
printf("The distance in Feet: %f\n", f);
printf("The distance in Inches: %f\n", in);
printf("The distance in Meters: %f\n", m);
printf("The distance in Centimeters: %f\n", cm);
return (0);
}
OUTPUT
Enter distance in kilometers: 2
The distance in Feet: 6561.680176
The distance in Inches: 78740.156250
The distance in Meters: 2000.000000
The distance in Centimeters: 200000.000000
Q.16 Describe the four basic data types. How could we extend the range of values they
represent? (CPU_WIN_2016)
The basic four data types are:
Data Type
Integer Type Character Type Floating Point Type Void Type
signed unsigned
int unsigned int char float
short int unsigned short int signed char double
long int unsigned long int unsigned char long double
Integer Type:
An integer occupies 2 bytes memory space and its value is limited to the range -32768 to +32767.
Character Type:

CKPCET, SURAT 16
PPS (3110003)

A single character can be defined as a character type data characters are usually stored in 8 bits of
internal storage while unsigned chars have values between 0 and 225, signed chars have values
from -128 to +127.
Floating Point Type:
Float occupies 4 bytes memory space and its value is limited to the range -3.4e38 to +3.4e38
Void Type:
The void type has no values. This is usually used to specify the type of function. The type of
function. The type of a function is said to be void when it does not return any value.

Q.17 Write a program to find sum of first N odd numbers. Ex. 1+3+5+7+………..+N.
(CPU_WIN_2016)
#include <stdio.h>

void main()

int i,n,sum=0;

printf("Input number of terms : ");

scanf("%d",&n);

printf("\nThe odd numbers are :");

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

printf("%d ",2*i-1);

sum+=2*i-1;

printf("\nThe Sum of odd Natural Number upto %d terms : %d \n",n,sum);

Q.18 Distinguish between the following functions: (CPU_WIN_2016)


(I) “getc” and “getchar” (II) “printf” and “fprintf” (III) “feof” and “ferror”.
The key difference between getc and getchar is that the getc is used to read a character from an
input stream such as a file or standard input while getchar is to read a character from standard

CKPCET, SURAT 17
PPS (3110003)

The key difference between printf and fprintf is that printf is a C function used to print a formatted
string to a standard output stream which is the computer screen, while fprintf is a C function to
print a formatted string to a file.
The difference feof(): and ferror():
feof():
It checks ending of a file. It continuously return zero value until end of file not come and return
non zero value when end of file comes.
ferror():
It checks error in a file during reading process. If error comes ferror returns non zero value. It
continuously returns zero value during reading process.
Q.19 List the header files used in c Programing with their properties. (CPU_WIN_2015)
A header file has a .h extension that contains C function declarations and macro definition.
Basically, header files are of 2 types:
• Standard library header files: These are the pre-existing header files already available in
the C compiler.
• User-defined header files: Header files starting #define can be designed by the user.
1. #include<stdio.h> (Standard input-output header)
Used to perform input and output operations in C like scanf() and printf().
2. #include<string.h> (String header)
Perform string manipulation operations like strlen and strcpy.
3. #include<conio.h> (Console input-output header)
Perform console input and console output operations like clrscr() to clear the screen and getch() to
get the character from the keyboard.
4. #include<stdlib.h> (Standard library header)
Perform standard utility functions like dynamic memory allocation, using functions such as
malloc() and calloc().
5. #include<math.h> (Math header )
Perform mathematical operations like sqrt() and pow(). To obtain the square root and the power of
a number respectively.
6. #include<ctype.h>(Character type header)
Perform character type functions like isaplha() and isdigit(). To find whether the given character
is an alphabet or a digit respectively.
7. #include<time.h>(Time header)

CKPCET, SURAT 18
PPS (3110003)

Perform functions related to date and time like setdate() and getdate(). To modify the system date
and get the CPU time respectively.

Q. 20 Explain primary data types used in C. (CPU_SUM_2014)


Primary (Fundamental) data types in C programming includes the 4 most basic data types, that is:

• int: It is responsible for storing integers. The memory it occupies depends on the compiler
(32 or 64 bit). In general, int data type occupies 4 bytes of memory when working with a 32-
bit compiler.
• float: It is responsible for storing fractions or digits up to 7 decimal places. It is usually
referred to as a single-precision floating-point type. It occupies 4 bytes of memory
• char: It can be used to store a set of all characters which may include alphabets, numbers and
special characters. It occupies 1 byte of memory being the smallest addressable unit of a
machine containing a fundamental character set.
• double: It is responsible for storing fractions or digits up to 15-16 decimal places. It is usually
referred to as a double-precision floating-point type.
• void (Null) data type: It indicates zero or no return value. It is generally used to assign the
null value while declaring a function.

Q. 21 Explain different type of operators used in c language with their precedence and
associativity. (CPU_SUM_2015)
Precedence of operators
If more than one operators are involved in an expression then, C language has predefined rule of
priority of operators. This rule of priority of operators is called operator precedence.
In C, precedence of arithmetic operators (*,%,/,+,-) is higher than relational is higher than logical
operators (&&,||and!).
Associativity of operators
Associativity indicates in which order two operators of same precedence (priority) executes. Let
us suppose an expression:
a==b!=c
Here, operators == and != have same precedence. The associativity of both == and != is left to
right, i.e, the expression in left is executed first and execution take place towards right. Thus,
a==b!=c equivalent to: (a==b)!=c
The table below shows all the the operators in c with precedence and associativity.
Category Operator Associativity
Postfix ()[]->.++-- Left to right
Unary +-!~++--(type)*&sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right

CKPCET, SURAT 19
PPS (3110003)

Shift << >> Left to right


Relational <<=>>= Left to right
Equality = = != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR || Left to right
Conditional ?: Right to left

Assignment =+=- Right to left


=*=/=%=>>=<<=&=^=|=
Comma , Left to right

Q.22 What do you mean by type conversion? Why is it necessary? (CPU_SUM_2015)


Typecasting is converting one data type into another one. It is also called as data conversion or
type conversion.
An example of typecasting is converting an integer to a string. This might be done in order to
compare two numbers, when one number is saved as a string and the other is an integer. For
example, a mail program might compare the first part of a street address with an integer. If the
integer "123" is compared with the string "123" the result might be false. If the integer is first
converted to a string, then compared with the number in the street address, it will return true.
Another common typecast is converting a floating point number to an integer. This might be used
to perform calculations more efficiently when the decimal precision is unnecessary.
Q. 24 Discuss the important of stdio.h header file. (CPU_SUM_2016)
stdio.h
The header file stdio.h stands for Standard Input Output. It has the information related to
input/output functions.
Here is the table that displays some of the functions in stdio.h in C language,

Sr.No. Functions & Description

1 printf()
It is used to print the strings, integer, character etc on the output screen.

2 scanf()
It reads the character, string, integer etc from the keyboard.

3 getc()
It reads the character from the file.

CKPCET, SURAT 20
PPS (3110003)

4 putc()
It writes the character to the file.

5 fopen()
It opens the file and all file handling functions are defined in stdio.h header file.

6 fclose()
It closes the opened file.

7 remove()
It deletes the file.

8 fflush()
It flushes the file.

Q. 25 Explain Derive data types (CPU_SUM_2016)


Derived data types are nothing but primary datatypes but a little twisted or grouped together like
array, stucture, union and pointer.
-- An array type describes a contiguously allocated nonempty set of objects with a particular
member object type, called the element type. Array types are characterized by their element type
and by the number of elements in the array. An array type is said to be derived from its element
type, and if its element type is T, the array type is sometimes called array of T. The construction
of an array type from an element type is called array type derivation.
-- A structure type describes a sequentially allocated nonempty set of member objects (and, in
certain circumstances, an incomplete array), each of which has an optionally specified name and
possibly distinct type.
-- A union type describes an overlapping nonempty set of member objects, each of which has an
optionally specified name and possibly distinct type.
-- A function type describes a function with specified return type. A function type is characterized
by its return type and the number and types of its parameters. A function type is said to be derived
from its return type, and if its return type is T , the function type is sometimes called function
returning T. The construction of a function type from a return type is called function type
derivation.
-- A pointer type may be derived from a function type, an object type, or an incomplete type, called
the referenced type. A pointer type describes an object whose value provides a reference to an
entity of the referenced type. A pointer type derived from the referenced type T is sometimes called

CKPCET, SURAT 21
PPS (3110003)

pointer to T. The construction of a pointer type from a referenced type is called pointer type
derivation.
These methods of constructing derived types can be applied recursively.
Q. 26 Briefly discuss about scope of variable. (CPU_SUM_2016)
A scope is a region of a program. Variable Scope is a region in a program where a variable is
declared and used. So, we can have three types of scopes depending on the region where these are
declared and used –
1. Local variables are defined inside a function or a block
2. Global variables are outside all functions
Local Variables
Variables that are declared inside a function or a block are called local variables and are said to
have local scope. These local variables can only be used within the function or block in which
these are declared. We can use (or access) a local variable only in the block or function in which
it is declared. It is invalid outside it. Local variables are created when the control reaches the block
or function contains the local variables and then they get destroyed after that.
Global Variables
Variables that are defined outside of all the functions and are accessible throughout the program
are global variables and are said to have global scope. Once declared, these can be accessed and
modified by any function in the program. We can have the same name for a local and a global
variable but the local variable gets priority inside a function.

Q. 27 List the data types provided by C programming language. (CPU_SUM_2017)


The data-type in a programming language is the collection of data with values having fixed
meaning as well as characteristics. Some of them are an integer, floating point, character, etc.
Usually, programming languages specify the range values for given data-type.
C Data Types are used to:
• Identify the type of a variable when it declared.
• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.
ANSI C provides three types of data types:
Primary(Built-in) Data Types:
• void, int, char, double and float.
Derived Data Types:
• Array, References, and Pointers.
User Defined Data Types:

CKPCET, SURAT 22
PPS (3110003)

• Structure, Union, and Enumeration.

Q. 28 Write code to find out largest of 2 numbers using ternary operator. (CPU_SUM_2017)

#include < stdio.h >

int main()

int a, b, big;

printf("Enter 2 numbers\n");

scanf("%d%d", &a, &b);

(a > b) ? (big = a) : (big = b);

printf("Biggest of %d and %d is %d\n", a, b, big);

return 0;

Output:

Enter 2 numbers

Biggest of 5 and 6 is 6

Q. 29 Describe the four basic data types. How could we extend the range of values they
represent? (CPU_SUM_2018)
The basic four data types are:
Data Type
Integer Type Character Type Floating Point Type Void Type
signed unsigned char float
int unsigned int signed char double

CKPCET, SURAT 23
PPS (3110003)

short int unsigned short int unsigned char long double


long int unsigned long int

Integer Type:
Integer are whole number with a range of values supported by a particular machine. Integer occupy
one word of storage and since the word sizes of machines size of an integer that can be stored
depends on the computer.Generally an integer occupies 2 bytes memory space and its value is
limited to the range -32768 to +32767.
General form:
int<variable name>;
int num1;
short int num2;
long int num3;
Example:
450, 45, 45000.
Character Type:
A single character can be defined as a character type data characters are usually stored in 8
bits of internal storage while unsigned chars have values between 0 and 225, signed chars
have values from -128 to +127.
General form:
char<variable name>;
char ch=’a’;
Example:
a,b,M,R,m;
Floating Point Type:
Floating point number are stored in 32 bits, with 6 digit of precision. Floating point numbers are
denoted by the keyword float. Float number is not sufficient, the type double can be used to define
the number. A double data type number uses 64 bits giving a precision of 14 digits. To extend the
precision further, we may use long double which uses go bits.
Generally float occupies 4 bytes memory space and its value is limited to the range -3.4e38 to
+3.4e38

General form:

CKPCET, SURAT 24
PPS (3110003)

float<variable name>;
float num1;
double num2;
long double num3;
Example:
450.45, 45.45, 45000.45
Void Type:
The void type has no values. This is usually used to specify the type of function. The type of
function. The type of a function is said to be void when it does not return any value. The role of a
generic type.

Q. 30 Define variable and constant. Explain different types of constants. (CPU_SUM_2018)


A variable is a named memory location which temporarily stores data that can change while the
program is running.
A constant is a named memory location which temporarily stores data that remains the same
throughout the execution of the program.
There are two simple ways in C to define constants −
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;

Q. 31 Describe assignment, sizeof( ) and ternary operator with example. (CPU_SUM_2019)


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

CKPCET, SURAT 25
PPS (3110003)

“=”: This is the simplest assignment operator. This operator is used to assign the value on the right
to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a += b) can be written as (a = a + b)
“-=”This operator is combination of ‘-‘ and ‘=’ operators.
(a -= b) can be written as (a = a - b)
“*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a *= b) can be written as (a = a * b)
“/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable on
the left.
Example:
(a /= b) can be written as (a = a / b)
sizeof( ) :
Sizeof is a much used operator in the C t is a compile time unary operator which can be used to
compute the size of its operand. The result of sizeof is of unsigned integral type which is usually
denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer
and floating-point types, pointer types, or compound datatypes such as Structure, union etc.
sizeof() operator is used in different way according to the operand type.
1. When operand is a Data Type.
When sizeof() is used with the data types such as int, float, char… etc it simply returns the amount
of memory is allocated to that data types.
#include <stdio.h>
int main()

CKPCET, SURAT 26
PPS (3110003)

{
printf("%lu\n", sizeof(char));
printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}
Output:
1
4
4
8
Ternary operator :
The conditional operator is kind of similar to the if-else statement as it does follow the same
algorithm as of if-else statement but the conditional operator takes less space and helps to write
the if-else statements in the shortest way possible.
The conditional operator is of the form
variable = Expression1 ? Expression2 : Expression3
// C program to find largest among two
// numbers using ternary operator

#include <stdio.h>

int main()
{
// variable declaration
int n1 = 5, n2 = 10, max;

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;

CKPCET, SURAT 27
PPS (3110003)

// Print the largest number


printf("Largest number between"
" %d and %d is %d. ",
n1, n2, max);

return 0;
}
Output :
Largest number between 5 and 10 is 10.

Q. 32 Describe Enumerated data type with example. (CPU_SUM_2019)


Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, the names make a program easy to read and maintain.
enum State {Working = 1, Failed = 0};
The keyword ‘enum’ is used to declare new enumeration types in C
enum flag{constant1, constant2, constant3, ....... };
Variables of type enum can also be defined. They can be defined in two ways:
enum week{Mon, Tue, Wed};
enum week day;

// Or

enum week{Mon, Tue, Wed}day;


Example:
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;

CKPCET, SURAT 28
PPS (3110003)

day = Wed;
printf("%d",day);
return 0;
}
Output:
2

Q. 33 What are header files? Name at least 3 with its usage. (PPS_SUM_2019)
A header file is a file with extension . h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the files
that the programmer writes and the files that comes with your compiler.
1. #include<stdio.h> (Standard input-output header)
Used to perform input and output operations in C like scanf() and printf().

2. #include<string.h> (String header)


Perform string manipulation operations like strlen and strcpy.

3. #include<conio.h> (Console input-output header)


Perform console input and console output operations like clrscr() to clear the screen and getch() to
get the character from the keyboard.

4. #include<stdlib.h> (Standard library header)


Perform standard utility functions like dynamic memory allocation, using functions such as
malloc() and calloc().
Q. 34 What is formatted output? Using printf() statement explain it. (PPS_SUM_2019)
Formatted Output. Several library functions help you convert data values from encoded internal
representations to text sequences that are generally readable by people. You provide a format string
as the value of the format argument to each of these functions, hence the term formatted output.
The C library function int printf(const char *format, ...) sends formatted output to stdout.

Declaration

int printf(const char *format, ...)

CKPCET, SURAT 29
PPS (3110003)

Example :
#include <stdio.h>
int main () {
int ch;
for( ch = 75 ; ch <= 100; ch++ ) {
printf("ASCII value = %d, Character = %c\n", ch , ch );
}
return(0);
}
Q. 35 What are command line arguments? Explain with suitable example. (PPS_SUM_2019)
Command line argument is a parameter supplied to the program when it is invoked. Command
line argument is an important concept in C programming. It is mostly used when you need to
control your program from outside. Command line arguments are passed to the main() method.
Syntax:
int main(int argc, char *argv[])
Example :
#include <stdio.h>
#include <conio.h>

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


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}

CKPCET, SURAT 30
PPS (3110003)

else
{
printf("argument list is empty.\n");
}
return 0;
}

MCQ

(CPU_WIN_2019)
Q. The statements between a function body are indicated by:
(a) { } (b) “ ” (c) \n (d) /**/

Q. Which is a legal ‘C’ expression?


(a) a = [b + c]; (b) a = {(b + c)}; (c) a = (b + c); (d) a = {b*c};

Q. What will the output of following C code be?


# include <stdio.h>
int main()
{
int x = 1, y =1, z;
z = x++ +y;
printf (“%d, %d”, x, y);
}
(a) x = 2, y = 2 (b) x = 2, y = 1 (c) x = 1,y = 1 (d) x = 1, y = 2

Q. How many operands does the conditional operator (?:) takes?


(a) Four (b) Two (c) One (d) Three

Q. What is the value of expression 4/9 in C?


a) 1 b) 0 c) 0.444 d) Error

Q. A declaration float a, b; occupies how much memory?


a) 2 bytes b) 4 bytes c) 8 bytes d) 16 bytes

CKPCET, SURAT 31
PPS (3110003)

Q. To round off x, which is a float, to an int value, which one is correct?


a) y = (int)(x+0.5); b) y = int(x+0.5); c) y = (int)x+0.5;
d) y = (int)((int)x+0.5);

Q.What is the output of following C code?


int k;
for(k=1;k>=10;k++);
printf(“Hello”);
a) prints “Hello” 10 times b) prints nothing c) prints “Hello” infinite times
d) prints “Hello” 1 time

Q. What is the output of 16>>2?


a) 4 b) 32 c) 8 d) 64

(CPU_WIN_2017)
Q. What is the output of following code:
void main()
{
enum day{Mon,Tues,Wed,Thu,Fri,Sat,Sun};
printf("%d",Fri);
getch();
}
a) 5 b)Error c) 4 d) Fri

Q. Which data type allows storage of same data type?


a) Array b) Union c) Void d) both a and b

(CPU_WIN_2016)
Q. Any C program

CKPCET, SURAT 32
PPS (3110003)

(a) Must contain at least one function. (b) Need not contain any function. (c) Needs input data.
(d) None of the above.

Q. Which is a correct ‘C’ expression?


(a) z = (x+y); (b) z = [x+y]; (c) z = {x+y}; (d) z = {(x+y)};

Q. If we want to increment the value of sum by 1. Which of following should be used?


(a) sum++; (b) sum = sum+1; (c) sum+ = 1; (d) all of above.

Q. Which of following is not a valid assignment expression?


(a) y = 22 ; (b) s = x; (c) y % = 6; (d) z = 5 = 3;

Q. What should be written in the program to get newline on the screen?


(a) printf(“\n”); (b) echo “\\n”; (c) printf(‘\n’); (d) printf(“ \\n “);

CPU_WIN_2013
Q. What are the different types of real data types in C?
(A) float, double. (B) short int, double, long int. (C) double, long int, float
(D) float, double, long double.

Q. Which of the following is a symbol for AND operator?


(A) II (B) & (C) && (D) $$

Q. Which of the following is a correct statement?


(A) Variable name must start with underscore (B) Variable name must have digit
(C) Variable name must have white space character (D) Keyword cannot be a variable name

Q. What will be the output of following code.


{
int x = 10, y=15;

CKPCET, SURAT 33
PPS (3110003)

x = x++;
y = ++y;
printf(“%d, %d \n” , x, y);
}
(A) 10, 15 (B) 10, 16 (C) 11, 16 (D) 11, 15

(CPU_SUM_2014)
Q. Which header file is essential for using printf() function ?
a) text.h b) strings.h c) stdio.h d) strcmp.h

(CPU_SUM_2016)
Q. Which of the following is ternary operator?
(a) ?? (b) :? (c) ?: (d) ::

Q. Which header file is essential for using scanf() function?


(a) ctype.h (b) string.h (c) conio.h (d) stdio.h

Q. A declaration float sum, value; occupies _____ of memory?


(a) 2 byte (b) 4 byte (c) 6 byte (d) 8 byte

(CPU_SUM_2016)
Q. Default value of global variable is
(a) 0 (b) 1 (c) Garbage value (d) Depend on data type

Q. Default value of local variable is


(a) 0 (b) 1 (c) Garbage value (d) Depend on data type

(CPU_SUM_2017)
Q. A float requires ______bytes in memory
(a)2 bytes (b)1 byte (c)8 bytes (d)4 bytes

CKPCET, SURAT 34
PPS (3110003)

Q. Which header file is necessary for strlen() function?


(a)conio.h (b)strings.h (c)string.h (d)stdio.h

Q. When a key is pressed on keyboard, which standard is used for converting the keystroke into
the corresponding bits
(a) ANSI (b) ASCII (c) EBCDIC (d) ISO

Q. C is a ___ language
(a) Machine Level (b) Low Level (c) Middle Level (d)High Level

(CPU_SUM_2018)
Q. What should be written in the program to get newline on the screen?
(a) printf(“\n”); (b) echo “\\n”; (c) printf(‘\n’); (d) printf(“ \\n “);

Q. Which of these have highest precedence?


(a) ( ) (b) ++ (c) * (d) >>

Q. File manipulation functions in C are available in which header file?


(a) streams.h (b) stdio.h (c) stdlib.h (d) files.h

Q. What will be the output of following code.


{
int x = 10, y=15;
x = x++;
y = ++y;
printf(“%d, %d \n” , x, y);
}
(a) 10, 15 (b) 10, 16 (c) 11, 16 (d) 11, 15

CKPCET, SURAT 35
PPS (3110003)

(CPU_SUM_2019)
Q. C-Language is ____________________.
(a) Machine Dependent (c) Machine Independent
(b) Partially Machine Dependent (d) None of above.

Q. Which of the following is correct C statement to print variable a?


(a) printf(“a”); (b) printf(“%d”); (c) printf(“%d”, a); (d) printf(“%a”);

Q. Which one is invalid variable name?


(a) int_a (b) case_c (c) temp1 (d) 1temp

Q. Which one of following statement doesn’t increment variable a?


(a) a++ (b) ++a (c) a += 1 (d) a = +1

Q. What is output of following program ?


void main( )
{
int z = 10;
float z = 10;
printf(“%d”,z);
}
(a) 10.00 (b) 10 (c) Compile time error (d) Run time error

CKPCET, SURAT 36

You might also like