Chapter 2
Chapter 2
CHAPTER 2
Fundamentals of C
• 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;
scanf("%d",&choice);
if(choice ==1){
scanf("%f",&fh);
else if(choice==2){
scanf("%f",&cl);
fh= (cl*1.8)+32;
else{
CKPCET, SURAT 2
PPS (3110003)
return 0;}
Output
First Run:
Second Run:
Third Run:
TYPES OF C CONSTANT:
1. Integer constants
2. Real or Floating point constants
CKPCET, SURAT 3
PPS (3110003)
1.INTEGER CONSTANTS IN C:
2. REAL CONSTANTS IN C:
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:
• 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
% remainder of division
Relational operators
CKPCET, SURAT 5
PPS (3110003)
Operator Description
> Check if operand on the left is greater than operand on the right
Logical operators
Operator Description
|| 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;
scanf("%d",&n);
for(i=1;i<=n;i++)
CKPCET, SURAT 6
PPS (3110003)
printf("%d ",2*i-1);
sum+=2*i-1;
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).
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.
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.
Case Use only lowercase. Lower and upper cases, both are allowed.
Classification Keywords are not further Identifier are classified into 'external
classified. name' and 'internal name'.
CKPCET, SURAT 10
PPS (3110003)
BASIS FOR
KEYWORD IDENTIFIER
COMPARISON
Example int, char, if, while, do, class Test, count1, high_speed, etc.
etc.
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);
}
CKPCET, SURAT 12
PPS (3110003)
CKPCET, SURAT 13
PPS (3110003)
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)
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;
scanf("%d",&n);
for(i=1;i<=n;i++)
printf("%d ",2*i-1);
sum+=2*i-1;
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.
• 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)
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.
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.
CKPCET, SURAT 22
PPS (3110003)
Q. 28 Write code to find out largest of 2 numbers using ternary operator. (CPU_SUM_2017)
int main()
int a, b, big;
printf("Enter 2 numbers\n");
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)
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.
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;
CKPCET, SURAT 27
PPS (3110003)
return 0;
}
Output :
Largest number between 5 and 10 is 10.
// Or
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().
Declaration
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>
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) /**/
CKPCET, SURAT 31
PPS (3110003)
(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
(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.
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.
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) ::
(CPU_SUM_2016)
Q. Default value of global 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. 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 “);
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.
CKPCET, SURAT 36