0% found this document useful (0 votes)
15 views80 pages

Unit 1 Notes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 80

Unit – I: BASICS OF C PROGRAMMING

Introduction to programming paradigms.

 Programming paradigms are a way to classify programming languages based on their


features.

over view of flow diagarm in programming paradigms

Types of programming paradigms.


 Imperative paradigm
 Functional paradigm
 Logic paradigm
 Object-oriented paradigm
Imperative paradigm.
 The 'first do this, next do that' is a short phrase which really in a nutshell describes the
spirit of the imperative paradigm.
Digital hardware technology and the ideas of Von Neumann
 Language representatives(Fortran, Algol, Pascal, Basic, C).

Functional paradigm.

 Functional programming is in many respects a simpler and more clean programming


paradigm than the imperative one.
Used to Mathematics and the theory of functions.
Logic paradigm.

 The logical paradigm seems less natural in the more general areas of computation.
 Automatic proofs within artificial intelligence.

Object-oriented paradigm.
 An object-oriented program is constructed with the outset in concepts.
 The theory of concepts, and models of human interaction with real world
phenomena
Imperative paradigmprogramming
Characteristics:

 Discipline and idea


 Digital hardware technology and the ideas of Von Neumann
 Incremental change of the program state as a function of time.
 Execution of computational steps in an order governed by control structures
 We call the steps for commands
 Straightforward abstractions of the way a traditional Von Neumann computer works
 Similar to descriptions of everyday routines, such as food recipes and car repair
 Typical commands offered by imperative languages
 Assignment, IO, procedure calls
 Language representatives
 Fortran, Algol, Pascal, Basic, C
 The natural abstraction is the procedure
 Abstracts one or more actions to a procedure, which can be called as a single
command.
 "Procedural programming"

Functional paradigm.

Characteristics:

 Discipline and idea


 Mathematics and the theory of functions
 The values produced are non-mutable
 Impossible to change any constituent of a composite value
 As a remedy, it is possible to make a revised copy of composite value
 Atemporal
 Time only plays a minor role compared to the imperative paradigm
 Applicative
 All computations are done by applying (calling) functions

Logic paradigm.

Characteristics:

 Discipline and idea


 Automatic proofs within artificial intelligence
 Based on axioms, inference rules, and queries.
 Program execution becomes a systematic search in a set of facts, making use of a set
of inference rules.

Object-oriented paradigm.

Characteristics:

 Discipline and idea


 The theory of concepts, and models of human interaction with real world
phenomena
 Data as well as operations are encapsulated in objects
 Information hiding is used to protect internal properties of an object
 Objects interact by means of message passing
 A metaphor for applying an operation on an object
 In most object-oriented languages objects are grouped in classes
 Classes represent concepts whereas objects represent phenomena

History of C Language
• All modern computer languages are started through the ALGOL language in 1960.
• After, the COBOL was being used for commercial applications.
• FORTRAN was developed for scientific applications.
• A committee was formed to develop a new language called Combined Programming
Language (CPL) at Cambridge University.
• Basic CPL was derived by BCPL. BCPL was developed by Martin Richards at
Cambridge University by 1967.
• At the same time a language called ‘B’ was developed by Ken Thomson at AT & T’s
Bell labs in 1970.
• Then C language is developed by Dennis Ritchie in 1972 with some additional
features of BCPL and B which is very simple.
• ANSI C (American National Standard Institute) has begun to work on a standardized
definition of the ‘C’ language that makes it still powerful.

Types of Languages
• Low Level Language (Or) Machine Language
• High Level Language
o Normal English, Human Understandable Language, Machine Independent, C,
C++, etc…
• Middle Level Language
o C Language is also called as Middle Level Language because ‘C’ stands in
between Low Level Language (nor) High Level Language (i.e) it performs task
of low level languages as well as high level language.
Structure of C Program
Discuss about the structure of C program in detail.

Documentation Section
• It consists of set of comment lines used to specify the name of the program, the author
and other details, etc.
Comments
• Comments are very helpful in identifying the program features and underlying logic
of the program.
• The lines begins with ‘/*’ and ending with ‘*/’ are known as comments lines.
• These lines are not executable. There are two types of comment lines,
o Single Comment Line eg., //ABCD….
o Nested Comment Line (or) Multiple Comment Line

e.g, /*……..

……..*/

Preprocessor Section
• It is used to link system library files for defining the macros and for defining the
conditional inclusion.
• C program depends upon some header file for function definition that is used in
program.
• Header file is extended with ‘.h’.
• This file should be included using #.
• Eg., #include<stdio.h>, #define A 10, #if def, #endif…
Global Declaration Section
• This section declares some variables that are used in more than one function
throughout the program.
• These variables must be declared outside of the main function. So these variables are
known as global variables.
Main Function
• Every C program must contain main function.
• Without main function that is not a C program.
• After main function empty parenthesis are necessary.
• Main () is the starting point of every ‘C’ program.
• The execution always begin with the main function
• The execution starts with opening brace ‘{’ & closing brace ‘}’
• In between these braces the programmer should write executable and declaration part.
o Executable part - It contains a set of statements or a single statement. These
statements are enclosed between the braces.
o Declaration part - It declares the entire variables that are used in executable
part. Variable initialization is done in declaration section.
Sub Program Section (Or) User Defined Function
• These section defined by user are called user defined functions.
• These functions are defined after the main function (Or) before the main function.
Programming Rules
While writing a program, a programmer should follow the following rules.
• All statements should be written in lowercase letters.
• Uppercase letters are only used for symbolic constants.
• Blank space may be inserted between the words. But blank space is not used while
declaring a variable, keyword, constant and function.
• The programmers can write the statement anywhere between the two braces.
• We can write one or more statements in a same line by separating each statement in a
same line with semicolon (:).
• The opening and closing braces should be balanced.
Constants, Variables and Data Types
C Character Set
• Character set are the set of alphabets, letters and some special characters that are valid
in C language.
• It is used to represent information.

Two types of Character Set


• Source Character Set
• Executable Character Set
Source Character Set
• It is used to construct the statements in the source program.
• Source character set is classified into,
o Alphabets - A to Z and a to z
o Digits - 0 to 9
o Special Characters - +, -, ?, /, (, ), *, &, ^, $, #, @, !, <, >, :, ;, ’, ”, _, =
o White Spaces - Blank Space, Horizontal Tabs, Vertical Tab, New Line, Form
Feed.

Executable Character Set


• It is used at the time of execution.
• Execution character set is also called as non-graphic character (or) Escape sequence.
• Escape sequence are invisible and cannot be printed (or) displayed on the output
screen.
• Escape sequence are always represented by a back slash (\) followed by a character.
Escape
Character Result
Sequence
Bell (Alert) \a Beep Sound
Back Space \b Moves Previous Position
Horizontal Tab \t Moves next horizontal tab
Vertical Tab \v Moves next vertical tab
Newline (line \n Moves next line
feed)
Form feed \f Moves initial position next
page
Carriage return \r Moves beginning of the next
line
Question mark \? Present Question mark
Backslash \\ \\ Present Back slash mark
NULL \0 NULL

C Tokens
• Token is defined as the collection of entities such as identifiers, keywords, constants,
strings, operators and special symbols.
• A token is source-program text that the compiler does not break down into component
elements.
Identifiers
• Identifier is a combination of alphanumeric characters.
• An identifier is used for any variable, function, data definition, etc.
• Eg., STDNAME, _SUB, TOT_MARKS – Valid Identifiers
• Eg., Return, STD NAME - Invalid Identifiers
Rules for Naming an Identifier
 It consists of letters (uppercase & lowercase), digits and underscore ( _ ) only.
• The first letter of an identifier should be either a letter or an underscore.
• No space and special symbols are allowed between the identifier.

• The identifier cannot be a keyword.

Storage Class
Explain the different types of storage classes in detail. (Or) What is storage class? List
and explain with example. (Dec/Jan 2014) (Or) Write short notes on register storage
class. (Nov/Dec 2014) (Or) Explain the various storage classes in C. (April/May 2015)
(Nov/Dec 2015) (May/June 2016) (Or) Explain various storage classes used in C with
example (April / May 2017)
• A storage class defines the scope (visibility) and life time of variables and/or functions
within a C program.
• There are following storage classes which can be used in a C program.
o auto
o register
o static
o extern
auto - Storage Class
• auto is the default storage class for all local variables.
{
int Count;
auto int Month;
}

• The example above defines two variables with the same storage class. auto can only
be used within functions, i.e. local variables.
register - Storage Class
• register is used to define local variables that should be stored in a register instead of
RAM.
• This means that the variable has a maximum size equal to the register size (usually
one word) and can’t have the unary '&' operator applied to it (as it does not have a
memory location).
{
register int Miles;
}
• Register should only be used for variables that require quick access - such as counters.
It should also be noted that defining 'register' goes not mean that the variable will be
stored in a register. It means that it MIGHT be stored in a register - depending on
hardware and implementation restrictions.
static - Storage Class
• static is the default storage class for global variables. The two variables below (count
and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
• static variables can be 'seen' within all functions in this source file. At link time, the
static variables defined here will not be seen by the object modules that are brought
in.
• static can also be defined within a function. If this is done the variable is initalized at
run time but is not reinitalized when the function is called. This inside a function static
variable retains its value during vairous calls.

void func(void);
static count=10; /* Global variable - static is the default */
main(){
while (count--){
func();} }
void func( void ){
static i = 5;
i++;
printf("i is %d and count is %d\n", i, count);
}
This will produce following result
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
extern - Storage Class
• extern is used to give a reference of a global variable that is visible to ALL the
program files.
• When you use 'extern' the variable cannot be initialized as all it does is point the
variable name at a storage location that has been previously defined.
• When you have multiple files and you define a global variable or function which will
be used in other files also, then extern will be used in another file to give reference of
defined variable or function.

File 1: main.c

int count=5;
main()
{
write_extern();
}

File 2: write.c

void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n", count); }
• Here extern keyword is being used to declare count in another file.

Constants
What are Constants? Explain the various types of constants in C. (April/May 2015)
• Constants are the entity whose values can't be changed during the execution of a
program.
• Eg: x=3, Here 3 is a constant.
• Constants are classified into two types. They are,
o Numerical Constant
o Character Constant
Numerical Constant
It is divided into two types,
1. Integer Constant
2. Real Constant
Integer Constant
• Integer constants are the numeric constants formed with the sequence of digits without
any fractional part or exponential part.
• There are three types of integer constants in C language: decimal constant (base 10),
octal constant (base 8) and hexadecimal constant (base 16).
• Decimal Digits: 0 1 2 3 4 5 6 7 8 9
• Octal Digits: 0 1 2 3 4 5 6 7
• Hexadecimal Digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
Example
• Decimal Constants: 0, ‐9, 22, etc.
• Octal Constants: 021, 077, 033, etc.
• Hexadecimal Constants: 0x7f, 0x2a, 0x521, etc.
Floating Point Constant
• Floating point constants are the numeric constant that has either fractional part or
exponent part.

Example
‐2.0
0.0000234
‐0.22E‐5
Character Constant
• Character constants are the constant which use single quotation around characters.
1. Single Character Constant
• It contains a single character enclosed within a pair of single inverted commas both
pointing to the left.
• Eg: ‘s’, ‘M’, ‘3’, etc.
2. String Constant
• A string constant is a sequence of characters enclosed in double quotes, the
characters may be letters, numbers, special characters and blank spaces, etc.
• Eg: “Hello”, ”23”, “a”, etc.
Rules for Defining Constants
• It must have at least one digit.
• It can be either positive or negative.
• No commas or blank spaces are allowed.
• Decimal points are not allowed in integer constants, but allowed in real constants.
Different Data types in C
Explain the various data types available in C with example. (Or) Discuss the basic data
types in C. (May/June 2016)
Data types
• Data types are the keywords, which are used for assigning a type to a variable.
• Allows the programmers to select the appropriate data type as per the need of the
application.
• Data types are used to specify the types of data that are going to process within the
program.
• C supports different types of data types. They are,

1. Primary Data Type


2. User Defined Data Type
3. Derived Data Type
4. Empty Data Type
Primary Data Type
The primary data types are divided into the following,
1. Integer Data Type
• Integer data type allows a variable to store numeric values.
• The keyword is used to define integer data type is “int”.
• The storage size of integer data type is 2 or 4 or 8 byte.
• Eg., int a;
Signed Integer Unsigned Integer
 It occupies 2 bytes in memory.  It also occupies 2 bytes in
 It ranges from -32768 to 32767. memory.
 Control string used is %d or %L.  It ranges from 0 to 65535.
 Eg: int a=2;  Control string used is %u.
long int b=2;  Eg: unsigned long b;
unsigned short int c;

2. Character Data Type


• Character data type allows a variable to store only one character.
• Storage size of character data type is 1 byte. We can store only one character using
character data type.
• The keyword is used to define character data type is “char”.
• Eg: char a;
Signed Char Unsigned Char
 It occupies 1 byte in  It occupies 1 byte in memory.
memory.  It ranges from 0 to 255.
 It ranges from -128 to 127.  Control String used is %c.
 Control String used is %c.
3. Floating Point Data Type
Floating point data type consists of 2 types. They are,
 Float
 double
float
• Float data type allows a variable to store decimal values.
• Storage size of float data type is 4 byte.
• These are numbers which contain fractional parts, both positive and negative.
• The keyword used to define float data type is, float.
• It ranges from (3.42-38) to (3.42+38).
• Control String used is %f.
• Eg: float a;
double
• Double data type is also same as float data type which allows up-to 10 digits after
decimal.
• The keyword used to define double variables is double.
• The range for double data type is from 1E–37 to 1E+37.
• It also occupies 2 bytes in memory.
• Eg: double a;
User Defined Data Type
• The keyword used to define user defined data type is “typedef”.
• It allows users to define the identifier which would represent an existing data type.
• The main advantage is it increases the program’s readability.
Derived Data Type
• Derived data types are created by using predefined data types (int, char, float,
double) only.
• Array, pointer, structure and union are called as derived data types in C language.
Empty Data Type
• Void is an empty data type that has no value.
• This can be used in functions and pointers.
Example Program
#include<stdio.h>
main() {
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */
printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}

Output
value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06
Variable
• Variables are memory location in computer's memory to store data.
• To indicate the memory location, each variable should be given a unique name called
identifier.
• A variable is an identifier that is used to represent some specified type of information
within a designated portion of the program.
Rules for naming the variables
• Variable name can be composed of letters (both uppercase and lowercase letters),
digits and underscore '_' only.
• The first letter of a variable should be either a letter or an underscore.
• No commas or blank spaces are allowed within a variable name.
• There is no rule for the length of length of a variable. However, the first 31 characters
of a variable are discriminated by the compiler.
Variable Declaration
• Declaration of variable can be done in the declaration part of the program.
• The variables must be declared before they are used in the program.
Syntax
Data_type variable name;
Example
int a; char m;
float s;
Initializing Variables
• Value can be initialized in the valuable name using an assignment operator = .
Syntax
Data_type variable name = value; (or) variable name=value;
Example
Eg: int x=2; x=2;
Scope of the Variable
• Scope of the variable implies the availability of variables within the program.
• Variables have 2 types of scope.
o Local variables
o Global variables
Local Variables
• Local variables are defined inside a main function block (Or) inside a compound
statement of a function subprogram are called local variables.
Example
function() {
int i, j;
}
Global / External Variables
• The variables that are declared before the function main() are called the global /
external variables.
Eg:
int a, b; // here a,ball is a global variables.
main() {
……
function()
}
function() {
…….}

Enumerated constants

 Enumerated data types are a special form of integers, with the following constraints:
o Only certain pre-determined values are allowed.
o Each valid value is assigned a name, which is then normally used instead of
integer values when working with this data type.
 Enumerated types, variables, and typedefs, operate similarly to structs:

enum suits { CLUBS, HEARTS, SPADES, DIAMONDS, NOTRUMP } trump;


enum suits ew_bid, ns_bid;

typedef enum Direction{ NORTH, SOUTH, EAST, WEST } Direction;


Direction nextMove = NORTH;

 Values may be assigned to specific enum value names.


o Any names without assigned values will get one higher than the previous
entry.
o If the first name does not have an assigned value, it gets the value of zero.
o It is even legal to assign the same value to more than one name.
o Example:
o enum Errors{ NONE=0, // Redundant. The first one would be zero anyway
 MINOR1=100, MINOR2, MINOR3, // 100, 101, and 102
MAJOR1=1000, MAJOR2, DIVIDE_BY_ZERO=1000 }; // 1000, 1001, and
1000 again.

 Because enumerated data types are integers, they can be used anywhere integers are
allowed. One of the best places in in switch statements:

switch( nextMove ) {

case NORTH:
y++;
break;

// etc.
 The compiler will allow the use of ordinary integers with enumerated variables, e.g.
trump = 2; , but it is bad practice.

Keywords
• Keywords are the reserved words used by the compiler that have standard and fixed
(or) predefined meaning in ‘C’ Language.
• Those words cannot be changed by the user and they are the basic building blocks for
program statements.
• There are 32 keywords in C language. Some of the keywords are,

Keywords in C Language
auto double int struct do
break else Long switch default
case enum register typedef const
char extern return union if
continue for Signed, void goto
unsigned
float static sizeof short while
• All the keywords must be written in lower case.

Operators and Expression

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
 arithmetic operators( *, %, /, +, -)
 relational operators(==, !=, >, <, >=, <=)
 logical operators(&&, || and !).

Example of precedence
(1 > 2 + 3 && 4)
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

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)

The table below shows all the operators in C with precedence and associativity.
Operator Meaning of operator Associativity
() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection

! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment Right to left
-- Decrement
& Dereference
* Operator(Address)
sizeof Pointer reference
(type) Returns the size of an
object
Type cast(conversion)

* Multiply
/ Divide Left to right
% Remainder

+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)

<< Left shift


Left to right
>> Right shift

< Less than


<= Less than or equal
Left to right
> Greater than
>= Greater than or equal

== Equal to
Left to right
!= Not equal to

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left

Simple assignment
=
Assign product
*=
Assign quotient
/=
Assign remainder
%= Right to left
Assign sum
-=
Assign difference
&=
Assign bitwise AND
^=
Assign bitwise XOR
|=
Assign bitwise OR
<<= Assign left shift
>>= Assign right shift

, Separator of expressions Left to right

Operators in C Language
What are the various operators available in C? Discuss each one of them with suitable
illustrations. (Nov/Dec 2014) (Or) Explain the different types of operators available in C.
(April/May 2015) (Nov/Dec 2015) (May/June 2016) (Or) Explain various operators in C
language in detail. (April / May 2017)
Operators
• An operator is a symbol that specifies an operation to be performed on the operands.
Operand
• It is a data item on which operators perform operation.
• Eg: a+b
Here, a, bOperands + Operator
Various Types of Operator
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators
• C allows basic arithmetic operations like addition, subtraction, multiplication and
division.
• Arithmetic Operators are,
o + , - , * , / , %.
Arithmetic operators are classified as
• Unary Arithmetic: It requires only one operand.
o Eg: +x, -y
• Binary Arithmetic: It requires two operands.
o Eg: a+b, a%b, etc.
• Integer Arithmetic: It requires both operands are integer values for arithmetic
operation.
o Eg: a+b a=5, b=2
o a+b = 5+2=7
• Floating Point Arithmetic: It requires both operands are float type for arithmetic
operation.
o Eg: a+b, a=6.5 b=3.5
o a+b, 6.5+3.5 = 10
Sample Program 1:
#include<stdio.h> // Header File
#include<conio.h>
int a=5, b=10; //Global Declaration
void main( ) /* main is the starting of every c program */
{
int c; //Local Declaration
clrscr( );
printf(“ \n The sum of the two values:”);
c = a+b;
printf(“%d”,c);
getch( );
}
Output: The sum of the two values: 15

Sample Program 2:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=10, b=4, c;
float d=3, e;
clrscr( );
c = a/b;
printf(" \n Value of a/b is:%d",c);
e = a/d;
printf("\n Value of a/d is:%f",e);
getch( );
}
Output
Value of a/b is: 2
Value of a/d is: 3.333333
Relational Operator
• Relational operators are used to compare two or more operands. Operands may be
variables, constants or expression.
• If the relation is true, it returns value 1 and if the relation is false, it returns value 0.
o Relational operators are, <, >, <=, >=, ==, !=
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“\n Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“\n The Result is”);
printf(“%d”, a<b);
printf(“%d”, a>b);
printf(“%d”, a<=b);
printf(“%d”, a>=b);
printf(“%d”, a==b);
printf(“%d”, a!=b);
getch();
}
Output
Enter the Values of a and b: 4 2
The Result is
0
1
0
1
0
1
Logical Operators
• Logical operators are used to combine the results of two or more conditions.
Operator Meaning Example
If c=5 and d=2 then,((c==5) &&
&& Logical AND
(d>5)) Returns false.
|| Logical OR If c=5 and d=2
Then, ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.
Logical AND – This operator is used where a set of statements are to be executed, if two or
more expressions are true.
Logical OR – This is used, if either of them is true from two or more condition, then set of
statements are executed.
Logical NOT – This operator reverses the value of the expression it operates on.

Sample Program
#include<stdio.h>
#include<conio.h>
void main()
{
int c1.c2,c3;
clrscr();
printf(“Enter the values c1, c2, c3:”);
scanf(“%d%d%d”, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(“c1 is less than c2 and c3”);
if(!(c1<c2))
printf(“\n c1 is greater than c2”);
if((c1<c2)||((c1<c3))
printf(“c1 is less than c2 or c3 both”);
getch();
}
Output
Enter the values c1, c2, c3: 9 6 3
C1 is greater than c2
Assignment Operator
• Assignment operators are used to assign a value or an expression or a value of a
variable to another variable.
• Syntax: variable=expression (or) value ;
• Example : x=10; x=a+b; x=y;
• Two types of assignment operator are,
o Compound Assignment
o Nested Assignment (or) Multiple Assignment

Compound Assignment
• Assign a value to a variable in order to assign a new value to a variable after
performing a specified operation.
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

Multiple Assignments
• It is used to assign a single value or an expression to multiple variables.
• Syntax: var1=var2=…………..varn=single variable or expression;
Sample Program
#include<stdio.h>
#include<conio.h>
int b=10;
void main( ) {
int a=3, b=5;
clrscr( );
a+=b; // a= a+b
printf(" \n The sum of the two values:%d",a);
getch( );
}
Output:
The sum of the two values: 8
Increment and Decrement Operators
• These are the increment (++) and decrement (--) operators. Both of these are unary
operators.
• The ++ adds 1 to the operand and – subtracts 1 from the operand.
o ++x - Pre Increment (First increment and then return the value)
o --x - Pre Decrement (First decrement and then return the value)
o x++ - Post Increment (First return the value and then increment)
o x-- - Post Decrement (First return the value and then decrement)

Example
Let a=5 and b=10
a++; //a becomes 6
a‐‐; //a becomes 5
++a; //a becomes 6
‐‐a; //a becomes 5
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5;
clrscr();
printf(“Post Increment Value a++=%d\n”,a++);
printf(“Pre Increment Value ++a=%d\n”,++a);
printf(“Pre Decrement Value -- a=%d\n”,--a);
printf(“Post Decrement Value a--=%d\n”,a--);
getch();
}
Output:
Post Increment Value a++=5
Pre Increment Value ++a=7
Pre Decrement Value --a=6
Post Decrement Value a--=6
Conditional Operator (Or) Ternary Operator
• Conditional operator itself checks the condition and executes the statement depending
on the condition.
• Syntax: condition?exp1:exp2
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a=5, b=2, big;
clrscr();
big=(a>b)?a:b;
printf(“Largest number is %d”,big);
getch();
} Output: Largest number is 5
Bitwise Operators
• It is used to manipulate the data at bit level. It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
Operations of above operators are,
a b a|b a&b a^b ~a
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0

Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a, b, c;
clrscr();
a=12;
b=25;
c=a&b;
printf(“Bitwise AND=%d”,c);
c=a/b;
printf(“Bitwise OR=%d”,c);
c=a^b;
printf(“Bitwise XOR=%d”,c);
c=~a;
printf(“One’s Complement=%d”,c);
getch();
}
Output:
Bitwise AND=8
Bitwise OR=29
Bitwise XOR=21
One’s Complement= 220
Special Operators
It consists of the following,
Operators Meaning
, Comma Operator
sizeof() Size of Operator
& and * Address Operator / Indirection Operator
. and  Member Selection Operator
Comma Operator
• It is used to separate the statement elements such as variables, constants or expression,
etc.
sizeof() Operator
• It is a unary operator which is used in finding the size of data type, constant, arrays,
structure etc.

Address Operator / Indirection Operator


• Address Operator (&) - This symbol is used to specify the address of the variable.
• Indirection Operator (*) - It is used to specify the value of the variable.

Member Selection Operator


• These symbols are used to access the elements from a structure.
Sample Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
printf(" \n Size of Int is:%d",sizeof(c));
getch( );
}
Output
Size of Int is: 2
Expressions
• An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language.
• Syntax: variable=expression;
• Eg: y=(a/b)+c; z=(a*b)-d;
Type Conversion
• It is a process of converting the type of an expression from one type to another type.
• Eg: x = (int)10.45
Example Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
c=(int)10.45;
printf("\n Output is:%d",c);
getch( );}
Output Output is: 10

Managing Input / Output Functions in C


Explain briefly about formatted and unformatted input/output functions in C. (Or)
Describe the various input and output statements in C with suitable examples. (May/June
2016) (Or) Explain various input and output functions of C language in detail. (April /
May 2017)
• In C Language two types of Input/output statements are available and all input and
output operations are carried out through function calls.
o Unformatted Input / Output Statements
o Formatted Input / Output Statements
Unformatted Input / Output Statements
• These statements are used to input/output a single/group of characters from/to the
input/output devices.
Unformatted Input Statements
getchar() function
• A single character can be given to the computer using ”C” input library function
getchar().
• It reads a single character from a standard input device.
• Syntax: char variable=getchar();
getc() function
• It is used to accept a single character from the standard input to character variable.
• Syntax: character variable=getc();
gets() function
• It is used to read the string from the standard input device.
• Syntax: gets(char type of array variable);

Unformatted Output Statements


putchar() function
• It is used to display one character at a time on the standard output device.
• Syntax: putchar(character variable);
putc() function
• It is used to display a single character in a character variable to standard output device.
• Syntax: putc(character variable);
puts() function
• It is used to display / write the string to the standard output device.
• Syntax: puts(char type of array variable);
Formatted Input / Output Statements
• These statements are used read the data from the keyboard and write the data to the
monitor.
Formatted Input Statements
• Reads the formatted data from the keyboard.
scanf() function
• It is used to read information from the standard input device.
• scanf() function starts with a string argument and may contain additional arguments.
• scanf() requires conversion symbol(control string) to identify the data to be read
during execution of the program.

• Syntax: scanf(“control string”,&var1,&var2…..&varn);
• Eg: scanf(“%d %f %c”,&a,&b,&c);
Rules for writing scanf() function
• The control string must begin with (%) sign and must be within quotations.
• If there is a number of input data items, items must be repeated by commas and must
begin with (&) sign except for string input.
• The control string and the variables going to input should match with each other.
Formatted Output Statements
• Writes the formatted data to the monitor.
printf() function
• printf() is formatted output function.
• It is used to print the result message on the output screen.
• It prints all types of data values.
• It must have termination with semicolon.

Syntax:
printf(“control string”,var1,var2,……var n);
Rules for writing printf() function
• Place appropriate headings in the output.
• The Variable must be separated by comma and need not be begin with &sign.
• The control string and variables must match in their order.
• The control string must be in quotation.
• The printf statement is terminated by semicolon (;).
Example Program 1
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char a[10];
puts(“Enter a String:”);
gets(a);
puts(“Answer=”);
puts(a);
getch();
}
Output
Enter a String: MECH
Answer = MECH
Example Program 2
#include<stdio.h>
#include<conio.h>
void main() {
clrscr();
char a;
printf(“Enter a Character:”);
a = getchar();
printf(“Answer=”);
putchar(c);
getch();
}
Output
Enter a Character: B Answer = B

Assignment Statements
Simple Assignments
 The C-based languages use == as the equality relational operator to avoid confusion
with their assignment operator.
 The operator symbol for assignment:
1. = FORTRAN, BASI C, PL/I, C, C++, Java
2. := ALGOL, Pascal, Ada
If
Conditional Targets
(flag)
Example:
Count1 =0;
flag ? count 1 : count2 = 0;
⇔ Else

Count2=0;

Compound Assignment Operators

 A compound assignment operator is a shorthand method of specifying a commonly


needed form of assignment.
 The form of assignment that can be abbreviated with this technique has the destination
var also appearing as the first operand in the expression on the right side, as in
a=a + b

 The syntax of assignment operators that is the catenation of the desired binary
operator to
the = operator.
sum += value; ⇔ sum = sum + value;

Unary Assignment Operators

 C-based languages include two special unary operators that are actually abbreviated
assignments.
 They combine increment and decrement operations with assignments.
 The operators ++ and -- can be used either in expression or to form stand- alone
single-operator assignment statements. They can appear as prefix operators:

sum = ++ count; ⇔count = count + 1; sum = count;

 If the same operator is used as a postfix operator:

sum = count ++; ⇔sum = count; count = count + 1;

Assignment as an Expression

 This design treats the assignment operator much like any other binary operator,
except that it has the side effect of changing its left operand.
Ex:
while ((ch = getchar())!=EOF)
{...} // why ( ) around assignment?

 The assignment statement must be parenthesized because the precedence of the


assignment operator is lower than that of the relational operators.
ƒ
Disadvantage:
 Another kind of expression side effect which leads to expressions that is difficult to
read and understand.
For example
a = b + (c = d / b++) – 1
Denotes the instructions
Assign b to temp
Assign b + 1 to b
Assign d / temp to c
Assign b + c to temp
Assign temp – 1 to a
 There is a loss of error detection in the C design of the assignment operation
that frequently leads to program errors.

if (x = y) ...
instead of
if (x == y) ..

Decision Making
Control Statements
• All the instructions are executed sequentially by default, when no repetition of some
calculations is necessary.
• In some situation we may have to change the execution order of statements based on
some condition or to repeat set of statements until certain conditions are met.
• In such situation conditional or control structure statements are used.
• C language provides four general categories of control structures.
a) Sequential Structure
• In which instructions are executed in sequence.
Eg:
i=i+1;
j=j+1;
b) Selection Structure
• Sequence of the instructions is determined by using the result of the condition.
• If the result is true, then the statement i=i+1 will be executed otherwise it executes
j=j+1.

Eg:
if(x>y)
i=i+1;
else
j=j+1;
c) Iteration Structure
• In which statements are repeatedly executed. These form program loops.
Eg:
for(i=1;i<=5;i++)
{
i=i+1; }
d) Encapsulation Structure
• In which the other compound structure are included.
• It includes an if statement in a for loop or a for loop in an if statement.

Decision Making (Or) Conditional Statements


Explain the various decision making statements with example in detail. (Or) Explain
in detail about various decision making structures available in C with illustrative
examples.(Nov/Dec 2015)
 Conditions are placed in the program using decision making statements.
 Decision making statements check the condition and then executes its sub blocks.
 ‘C’ language provides the following conditional statements or selection structures
(decision making).
o if statement
o if…else statement
o nested if…else statement
o if…else ladder
The if statement
 The if statement is a decision making statement.
 It is used to control the flow of execution by executing statements and also test
logically whether the condition is true (or) false.
Syntax
if (condition is true)
{
statement 1;
statement 2;
}

Example
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
clrscr( );
printf("\n Enter the Number:");
scanf("%d",&a);
if(a>10)
{
printf("\n a is greater than 10");
}
getch( ); }
Output:
Enter the Number: 12
a is greater than 10
The if…else statement
• It is basically two way decision making statement used to control the flow of execution
and to carry out the logical test.
• It has two blocks if &else. if block is executed when the condition is true, else block
is executed when the condition is false.
Syntax
if(condition)
{
true statements;
}
else
{
false statements;
}
Example
#include<stdio.h>
#include<conio.h>
void main( ) {
int a;
clrscr( );
printf("\n Enter the Number:");
scanf("%d",&a);
if(a>10) {
printf("\n a is greater than 10");
}
else {
printf("\n a is less than 10");
}
getch( );
}
Output:
Enter the number: 2
A is less than 10

nested if…else statement


• Writing an entire if…else statement in another if…else statement is called nesting,
and the statement is called nested
if…else.
Syntax
if(condition 1) {
if(condition 2) {
true statement 2;
}
else {
false statement 2;
}}
else {
false statement 1;
}
The if…else Ladder
• Number of logical conditions is checked for executing various statements.
• If three are more than three alternatives and indentation is not consistent, it may be
different for you to determine the logical structure of the if statement.
Syntax
if(condition 1) {
statement 1;
}
else if(condition 2) {
statement 2;
}
else if(condition 3) {
statement 3;
}
else {
default statements;
}

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3;
float avg;
printf("\n Enter the Marks:");
scanf("%d%d%d",&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
printf("\n The average is:%f",avg);
printf("\n The Grade is:");
if(avg>=60) {
printf("First class");
}
else if(avg>=50) {
printf("Second class");
}
else if(avg>=35) {
printf("Thrid class");
}
else
{
printf("Fail");
}
getch();
}
Output:
Enter the Marks: 65
75
70
The average is: 70.000000
The Grade is: First class

Switch or Branching Statements


Write about the need and types of branching statements in C language and discuss with
examples. (Dec/Jan 2014)
The switch statement
• The switch statement is used to execute a particular group of statements from several
available groups of statements.
• It is a multi-way decision statement, it tests the value of given variable or expression
against a list of case values and when a match is found, a block of statements
associated with that case is executed.
• Switch statement required only one argument of any data type which is checked with
number of case options.
• If the value matches with case constant, that particular case statement is executed if
not default is executed.
• Every case statements terminate with break statement is used to exit from the current
case structure.
Syntax
switch(expression)
{
case constant 1 :
block 1;
break;
case constant 2 :
block 2;
break;
……………………
default :
default block;
break;
}
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int a, b, c, option;
printf(“\n 1.Addition”);
printf(“\n 2.subtraction”);

printf(“\n 3.multiplication”);
printf(“\n 4.Division”);
printf(“\n 5.Exit”);
printf(“\n Enter Two Numbers:”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter Your Option:”)
scanf(“%d”, &option);
switch(option) {
case 1:
c=a+b;
printf(“\n Addition=%d” ,c);
break;
case 2:
c=a-b;
printf(“\n subtraction=%d”,c);
break;
case 3:
c=a*b;
printf(“\n multiplication=%d”,c);
break;
case 4:
c=a/b;
printf(“\n division=%d”,c);
break;
case 5:
exit(0);
break;
default:
printf(“Invalid Choice”);
}
getch();
}

Output
Enter Two Numbers: 2 4
Enter Your Option: 1
6
The break statement
• It is used to terminate the loop.
• When a break statement is used inside any C loop, then the loop is terminated.
Syntax: break;

The continue statement


• When a continue statement is encountered inside any C loop, the control is
automatically transferred to the beginning of the loop.
Syntax
continue;

The goto statement


• It is used to transfer the control unconditionally from one place to another place in the
program.
• When a goto statement is encountered inside a loop, the control is transferred to the
beginning.
• It requires a label to identify the place to move the execution.
• A label is a valid variable name and must be ended with colon (:).
Syntax
goto label;
………….
………….
label:
(Or)
label:
………..
goto label;

Difference between Break and Continue statement


Break Continue
Break statement takes the control to the Continue statement takes the control to the
outside of the loop. beginning of the loop.
This can be used only in looping
It is also used in switch statement. statements.
Always associated with if condition in
loops. This is also associated with if condition.

Branching and Looping


Various Looping Concepts
Write about the need and types of looping statements in C language and discuss with
examples. (Dec/Jan 2014) (Or) Explain in detail about various looping structures
available in C with illustrative programs. (Nov/Dec 2014) (Or) Describe the various
looping statements used in C with suitable examples. (April/May 2015)
• The loop is defined as the block of statements which are repeatedly executed for
certain number of times.
• The loop in a program consists of two parts,
o Body of the loop
o Control Statement – Used to test the condition
• They are three types of loop control statements
o while loop
o do-while loop
o for loop
The while Loop
• The while loop is an entry controlled loop or top tested loop statement, means the
condition is evaluated first if it is true, and then the body of the loop is executed.
• It is a repetitive control structure, used to execute the statements within the body until
the condition becomes false.
Syntax
while(condition) {
……………..
body of the loop;
……………..
}
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int x=0;
while(x<10)
{
printf(“%d\n”,x);
x++;
}
getch(); }
Output
0 6
1 7
2 8
3 9
4
5

The do…while Loop


• The do…while loop is an exit controlled loop or bottom tested loop statement, means
the condition is evaluated last if it is true, and then the body of the loop is executed.
• Loop will be executed at least once even though the condition is false.
• It is also a repetitive control structure, used to execute the statements within the body
until the condition becomes false.
Syntax
do
{
…………..
body of the loop;
…………..
}while(condition);

Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int x=0;
do {
printf(“%d\n”,x);
x++;
}while(x<4);
getch();
}
Output
0
1
2
3

The for Loop


• The for loop is another repetitive control structure, and is used to execute set of
instructions repeatedly until the condition becomes false.
• for loop has 3 parts,
o Initialize Counter – used to initialize counter variable.
o Test Condition – used to test the condition
o Increment / Decrement Counter – used to increment / decrement the counter
variable
Syntax
for(initialize counter;test condition;increment / decrement counter)
{
……………
body of the loop;
……………..
}
Example Program
#include<stdio.h>
#include<conio.h>
void main() {
int x;
for(x=0;x<10,x++)
{
printf(“%d\n”,x);
}
getch();
}
Output
0 7
1 8
2 9
3
4
5
6

Difference between while and do….while loop


Differentiate entry and exit checked conditional constructs with an example.

while do….while
 It is an entry controlled loop or top  It is an exit controlled loop or bottom
tested loop. tested loop.
 First the condition is tested, if it is  It executes the body once, after it
true then the block is executed until checks the condition, if it is true the
the condition becomes false. body is executed until the condition
becomes false.
 Loop will not be executed if the  Loop will be executed at least once
condition is false. even though the condition is false.

Preprocessor Directives
Discuss about the preprocessor directives in C. (Or) Write short notes on #include,
#endif statement. (Nov/Dec 2014) (Or) Write short notes on #include, #ifndef, #endif
statements. (Nov/Dec 2015) (Or) Describe about the preprocessors with suitable
example. (May/June 2016)
• Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
• Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
Rules for Defining Preprocessor
• Every preprocessor must start with # symbol.
• The preprocessor is always placed before main() function.
• The preprocessor cannot have termination with semicolon.
• There is no assignment operator in #define statement.
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
 Below is the list of preprocessor directives that C language offers.
o File Inclusion
o Macro Substitution
o Conditional Inclusion
1. File Inclusion
• This is used to include an external file, which contains functions or some other macro
definitions to our source program.
Syntax
#include”Filename” and #include<Filename>
• Where Filename is the name of the file that can be included in our source program.
• When ‘filename’ is quoted, it searches for that file in current directory and then in
standard directories.
• When ‘filename’ is included in the angle brackets (< >), the included file is searched
only in the standard directory.
Example
#include<stdio.h>
#include”loop.c”
Where “stdio.h” is the file that contains standard I/O function in ‘C’ standard directory
and “loop.c” is the program written by the user.
Example Program
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\n Enter the Numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
Output:
Enter the Numbers:
7
4
The Value is 11

2. Macro Substitutions
• This is used to define symbolic constants in the source program. The identifier or
string or integer defined is replaced by macro substitution.
• ie., It is used to define and use integer, string, or identifier in the source program.
• There are three types of macros.

o Simple Macros
o Augmented Macros
o Nested Macros
(i). Simple Macros
• It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”
Example Program
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\n The Value CITY is %s",CITY);
getch();
}
Output:
The Value is 6.280000
The Value CITY is Chennai
(ii). Augmented Macros
• It is used to define more complex forms in the source program.
Syntax
#define identifier (v1,v2,….) string/integer
Eg:
#define cube(n) (n*n*n)

Example Program
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("\n The Value of 3 cube is %d",cube(3));
getch();
}
Output:
The Value of 3 cube is 27
(iii). Nested Macro
• Here one macro is used by another macro.

Eg:
#define a 3
#define sq a*a
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("\n The Value is %d",sq);
getch();
}
Output:
The Value is 9
3. Conditional Inclusion
• These are used to control the preprocessor with conditional statements.
• The preprocessor directives are,
o #if, #elif (else if) – It allows only constant expression. #elif establishes an if-
else-if chain for multiple compilation options.

o #define – Used to define symbolic constant.


o #ifdef – It is used to check the identifier was defined as a macro name.
o #ifndef - It is used to check the identifier was not defined as a macro name.
o #else – It allows only constant expression. If the result of the expression is
TRUE, then block of statement between #if and #endif is followed. If the result
of the expression is FALSE, then block of statement between #if and #endif is
skipped.
o #undef – Used to undefine a macro.
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\n The value C is %d",c);
getch();
}
Output: The value C is 8

Compilation process
Compilation and Linking Program Process
• Compilation refers to the process of converting a program from the source code into
machine code.
• The stages of developing your C program are as follows.
Creating the Program
• Create the program in any C editor (Turbo C).
• Save the program (File  Save) or Press F2 button. Use the extension .c for saving
the file.
• Eg: sample.c

Compiling the Program


• Compile the program by clicking on the Compile Menu  Compile or press Alt+F9
button.
Running the Program (Executing)
• Run the program by clicking on the Run Menu  Run or press Ctrl+F9 button.
Compilation Process
• Compiling a C program is a multi-stage process which involves four stages. They are,
o Preprocessing (Preprocessor)
o Compiling (Compiler)
o Assembling (Assembler)
o Linking (Linker)

Preprocessor
• The Preprocessor accepts source code as input and is responsible for removing
comments and interpreting special preprocessor directives denoted by #.
• Preprocessor directives are special instructions to the preprocessor that tells how to
prepare the program for compilation.
• Eg: #include<stdio.h>, #include<math.h>, etc.

Compiler
• It converts the programs written in high level language to machine language.
• i.e. it translates the source code to assembly code.
Assembler
• It converts the programs written in Assembly language to machine language.
• The assembler creates an object code.
Linker
• If a source file references library functions or functions defined in other source files
the link editor (Linker) combines these functions (with main()) to create an executable
file.
• Linking refers to the creation of a single executable file from multiple object files.
Example programs:

Example 1
#include<stdio.h>
#define NUM 10
void main()
{
#if((NUM%2)==0)
printf("\n Number is Even");
#endif
}
Output
Number is Even
Example 2
#include<stdio.h>
#define NUM 11
void main()
{
#if((NUM%2)==0)
printf("\n Number is Even");
#else
printf("\n Number is Odd");
#endif
}
Output
Number is Odd
Example 3
Step 1: program.c (Program written by Programmer)
#include<stdio.h>
#define LESSTHAN <
int main()
{
int a = 30;
if(a LESSTHAN 40)
printf("a is Smaller");
return(0);
}
Step 2: Program is processed by Pre-processor
int main()
{
int a = 30;
if(a < 40)
printf("a is Smaller");
return(0);
}
Step 3: Program is processed by Compiler
a is Smaller
Example 4 (#undef)
#include<stdio.h>
#define TEMP 10
#ifdef TEMP
#undef TEMP
#define TEMP 75
#else
#define TEMP 100
#endif
int main()
{
printf("%d",TEMP);
return 0;
}
Output :
75
Example 5 (#ifndef)
#include<stdio.h>
#define MAX 90
void main()
{
#ifndef MAX
#define MIN 90
#else
#define MIN 100
#endif
printf("MIN Number: %d",MIN);
}Output :MIN Number: 100
C Programming Examples
1. Write a C program to find the roots of a quadratic equation. (May/June 2014)
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main ( ) {
int a,b,c,d,r1,r2;
clrscr( );
printf(" \nEnter the value of a:");
scanf("%d",&a);
printf(" \nEnter the value of b:");
scanf("%d",&b);
printf(" \nEnter the value of c:");
scanf("%d",&c);
d=b*b-4*a*c;
if(d>=0) {
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
printf(" \nThe roots are %d,%d",r1,r2);
}
else {
printf(" \nThe roots are imaginary");
}
getch( );
}
Output:
Enter the value of a: 4
Enter the value of b: 5
Enter the value of c: 6
The roots are imaginary.
2. Write a C program for Fibonacci series. (Or) Write a C program to print the
Fibonacci series of a given number. (Dec/Jan 2014)
#include<stdio.h>
#include<conio.h>
void main() {
int f=0,f1=-1,f2=1,n,i;
printf("\n Enter the Number:");
scanf("%d",&n);
while(f<n) {
f=f1+f2;
f1=f2;
f2=f;
printf("\t%d",f);
}
getch();
}
Output:
Enter the Number: 5
0 1 1 2 3 5
3. Write a C program to find the factorial of a given number.
#include<stdio.h>
int main() {
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial: \n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
Output:
Enter a number to calculate its factorial: 6
Factorial of 6 = 720
4. Write a C program to swap two numbers using temporary (third) variable.
#include<stdio.h>
#include<conio.h>
void main() {
int x, y, temp;
clrscr();
printf("Enter the value of x and y:\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
getch();
}
Output:

5. Write a C program to swap two numbers without using third variable.


#include<stdio.h>
#include<conio.h>
void main( ) {
int a, b;
clrscr( );
printf("\n Enter the value of a:");
scanf("%d",&a);
printf("\n Enter the value of b:");
scanf("%d",&b);
a=a+b;
b=a-b;
a=a-b;
printf(“\n After Swapping”);
printf("\n The value of a is:%d",a);
printf("\n The value of b is:%d",b);
getch( );
}
Output:
Enter the value of a: 5
Enter the value of b: 6
After Swapping
The value of a is: 6
The value of b is: 5
6. Write a C program to find the number is odd or even.
#include<stdio.h>
#include<conio.h>
void main() {
int n;
clrscr();
printf("Enter an Integer:\n");
scanf("%d", &n);
if (n%2 == 0)
printf("It is an Even Number:\n");
else
printf("It is an Odd Number.\n");
getch();
}
Output:
Enter n Integer: 3
It is an Odd Number.
7. Write a C program to check whether a given number is prime or not. (May/June
2014)
#include<stdio.h>
main() {
int n, i, c = 0;
printf("Enter any Number:");
scanf("%d", &n);
for(i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}}
if(c == 2) {
printf("%d is a Prime number:");
}
else {
printf("%d is not a Prime number:");
}
return 0;
}
Output:
Enter any Number: 7
7 is a Prime Number.
8. Write a C program to check the given number is palindrome or not.
#include<stdio.h>
int main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or not:\n");
scanf("%d",&n);
temp = n;
while(temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if( n == reverse )
printf("%d is a palindrome number.\n", n);
else
printf("%d is not a palindrome number.\n", n);
return 0;
}
Output:

9. Write a C program to reverse a number.


#include<stdio.h>
#include<conio.h>
void main() {
int n,r=0,sum=0;
printf("\n Enter the No:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
printf("Reverse of the number is:%d",sum);
getch();
}
Output:
Enter the No: 567
Reverse of the number is: 765
10. Write a C program to find the sum of digits of an integer. (May/June 2014)
#include<stdio.h>
#include<conio.h>
void main() {
int n,r=0,sum=0;
printf("\n Enter the No:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("Sum of the digits is:%d",sum);
}
Output:
Enter the No: 156
Sum of the digits is: 12
11. Write a C program to find the given number is armstrong or not.
#include<stdio.h>
#include<conio.h>
void main() {
int r=0,sum=0,n,a;
printf("\n Enter the Number:");
scanf("%d",&n);
a=n;
while(n>0) {
r=n%10;
sum=sum+r*r*r;
n=n/10;
}
if(a==sum) {
printf("\n It is an Armstrong Number.");
}
else {
printf("\n It is not an Armstrong Number.");
}
getch();
}
Output:
Enter the Number: 153
It is an Armstrong Number.
12. Write a C to perform arithmetic operations.
#include<stdio.h>
#include<conio.h>
void main() {
int first, second, add, subtract, multiply;
float divide;
clrscr();
printf("Enter two integers\n");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting
printf("Sum = %d\n",add);
printf("Difference = %d\n",subtract);
printf("Multiplication = %d\n",multiply);
printf("Division = %.2f\n",divide);
getch();
}
Output:

13. Write a C Program to perform arithmetic operation using switch case.


#include<stdio.h>
#include<conio.h>
void main() {
int a,b,c,n;
clrscr();
printf("\nEnter the value of a & b:");
scanf("%d%d",&a,&b);
printf("\nMENU");
printf("\n1.ADD\n2.SUB\n3.MULTIPLY\n0.EXIT");
printf("\nEnter the choice:");
scanf("%d",&n);
switch(n) {
case 1:
c=a+b;
printf("\nThe result of Addition is:%d",c);
break;
case 2:
c=a-b;
printf("\nThe result of Subtraction is:%d",c);
break;
case 3:
c=a*b;
printf("\nThe result of Multiplication is:%d",c);
break;
case 0:
exit(0);
break; }
getch(); }
Output:
Enter the value of a & b: 5 6
MENU
1.ADD
2.SUB
3.MULTIPLY
0.EXIT
Enter the choice: 1
The result of Addition is: 11
Unit – I : C Programming Basics

1.Define programming paradigms.

 Programming paradigms are a way to classify programming languages based on


their features.

2.What is a over view of flow diagarm in programming paradigms?

3.List out types of programming paradigms.


 Imperative paradigm
 Functional paradigm
 Logic paradigm
 Object-oriented paradigm
4.Define Imperative paradigm.
 The 'first do this, next do that' is a short phrase which really in a nutshell describes
the spirit of the imperative paradigm.
Digital hardware technology and the ideas of Von Neumann
 Language representatives(Fortran, Algol, Pascal, Basic, C).

5.Define Functional paradigm.

 Functional programming is in many respects a simpler and more clean


programming paradigm than the imperative one.
Used to Mathematics and the theory of functions.
6.Define logic paradigm.

 The logical paradigm seems less natural in the more general areas of
computation.
 Automatic proofs within artificial intelligence.
7. Define Object-oriented paradigm.
 An object-oriented program is constructed with the outset in concepts.
 The theory of concepts, and models of human interaction with real world
phenomena
8. Write down the steps involved to solve a problem. (Or) What are the main steps
of problem solving? (April / May 2017)
• Define the problem.
• Analyze the problem and formulate a method to solve it (see also “validation”).
• Describe the solution in the form of an algorithm.
• Draw a flowchart for the algorithm.
• Write the computer program.
• Compile and run the program (debugging).
• Test the program (debugging) (see also “verification”).
• Interpretation of results.
9. What is Hardware?
• It is a collection of several physical components of the computer system.
• Some of these components are,
o CPU
o Peripherals
10. Define Software.
• Computer Software is a set of instructions or programs that tells a computer how
to do a job.
• It is classified into two types. They are,
• Application Software
o It is a set of programs that are used to perform specific task.
o Eg. Banking Software, etc.
• System Software
o It is a collection of programs designed to operate, control and extend
processing capabilities of computer and which makes the operation of a
computer system more efficient.
o Eg. MS-DOS, MS Windows, UNIX.

11. Differentiate between hardware and software.


Software Hardware
It is collection program to bring the It is the physical components of the
computer hardware system into operation. computer system.
It consists of numbers, alphabets, It consists of electronic components like
alphanumeric symbols, keywords, etc. ICs, diodes, resistors, etc.
It is designed and developed by high level It can understand only low level language
languages. or machine language.
It is represented in any high level It works only on binary number such as
languages such as BASIC, COBOL, C, 0’s & 1’s.
C++, etc.

12. What is Programming Language?


• It is a language designed to describe a set of consecutive action to be executed by
a computer.
• It is an artificial language used to instruct computers to perform a particular task.
13. Why programming languages are needed?
• The purpose of using computers is to solve problems, which are difficult to solve
manually.
• Programming languages are developed with the primary objectives of facilitating
large number of people to use computer without knowing the internal structure of
the computer.
14. Define Compilation process. (Or) What is Compilation Process?(Nov/Dec 2015)
• Compilation refers to the process of converting a program from the textual source
code into machine code.
• C program building process involves four stages to get executable (.exe). They are,
o Preprocessing
o Compiling
o Assembling
o Linking
o
15. What do you meant by linking?
• Linking refers to the creation of a single executable file from multiple object files.
• In this step, it is common that the linker will complain about undefined functions.
• During compilation, if the compiler could not find the definition for a particular
function, it would just assume that the function was defined in another file.
16. Differentiate between Compiler and Interpreter.
Complier Interpreter
Compiler Takes Entire program as Interpreter Takes Single instruction as
input input.
Intermediate Object Code is Generated No Intermediate Object Code is
Generated
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
It takes large amount of time to analyze It takes less amount of time to analyze
the source code the source code.
Overall execution time is comparatively Overall execution time is slower.
faster.
Eg: C, C++ Eg: BASIC, Python, Ruby

17. Difference between machine language and assembly language.


Machine Language Assembly Language
It is machine independent language. It is machine dependent language.
It uses binary numbers (0 & 1) for It uses mnemonic codes for
programming. programming.
It is not portable and debugging process It is portable and the debugging process
is easy. is also not very easy.

18. Mention the features and applications of C.


• C is a general purpose, structured programming language.
• C is a powerful, efficient, compact & flexible.
• C is highly portable.
• C is robust language.
• C is middle level language. It supports low level & high level language.
• C programs are fast and efficient.
• C language allows dynamic memory allocation.

19. Write the structure of C program.


20. How will you execute a C program?
• Execution is the process of running the program, to execute a C program; we need
to follow the steps given below.
o Creating the Program.
o Compiling the Program.
o Linking the program with system library.
o Executing the Program.
21. What is an Error?
• It is defined as the mistakes done during running and testing the program with
sample data.
• The two types of errors are,
o Syntax Error – Errors made in syntax.
o Logical Error – Errors made in the conditional and control statements.
22. Define character set in C.
• Character set are the set of alphabets, letters and some special characters that are
valid in C language.
• It is used to represent information.
• The two types of character sets are,
• Source Character Set
• Execution Character Set
23. What is source character set?
• It is used to construct the statements in the source program.
• Source character set is classified into,
o Alphabets - A to Z and a to z
o Digits - 0 to 9
o Special Characters - +, -, ?, /, (, ), *, &, ^, $, #, @, !, <, >, :, ;, ’, ”, _, =
o White Spaces - Blank Space, Horizontal Tabs, Vertical Tab, New Line, Form
Feed.
24. What is execution character set?
• It is used at the time of execution.
• Execution character set is also called as non-graphic character (or) Escape
sequence.
• Escape sequence are invisible and cannot be printed (or) displayed on the output
screen.
• Escape sequence are always represented by a back slash (\) followed by a character.
Escape
Character Result
Sequence
Bell (Alert) \a Beep Sound
Back Space \b Moves Previous Position
Horizontal Tab \t Moves next horizontal tab
Vertical Tab \v Moves next vertical tab
Newline (line \n Moves next line
feed)
Form feed \f Moves initial position next
page
Carriage return \r Moves beginning of the next
line
Question mark \? Present Question mark
Backslash \\ \\ Present Back slash mark
NULL \0 NULL

25. What is C Token?


• Token is defined as the collection of entities such as identifiers, keywords,
constants, strings, operators and special symbols.
• A token is source-program text that the compiler does not break down into
component elements.
26. Define Identifier. (Or) What is Identifier?
• Identifier is a combination of alphanumeric characters.
• An identifier is used for any variable, function, data definition, etc.
• Eg., STDNAME, _SUB, TOT_MARKS – Valid Identifiers
• Eg., Return, STD NAME - Invalid Identifiers
27. Write down the rules for naming an identifier.
 It consists of letters (uppercase & lowercase), digits and underscore ( _ ) only.
• The first letter of an identifier should be either a letter or an underscore.
• No space and special symbols are allowed between the identifier.
• The identifier cannot be a keyword.
28. Define Keyword in C. (Or) what are Keywords?
• Keywords are the reserved words used by the compiler that have standard and fixed
(or) predefined meaning in ‘C’ Language.
• Those words cannot be changed by the user and they are the basic building blocks
for program statements.
• There are 32 keywords in C language. Some of the keywords are,
Keywords in C Language
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
• All the keywords must be written in lower case.
29. What are Constants? (Or) What are the different types of constants
available in C? (April / May 2017)
• Constants are the entity whose values can't be changed during the execution of a
program.
• Eg: x=3, Here 3 is a constant.
• Constants are classified into two types. They are,
o Numerical Constant
o Character Constant
30. What is data type in C?
• Data types are the keywords, which are used for assigning a type to a variable.
• Allows the programmers to select the appropriate data type as per the need of the
application.
• Data types are used to specify the types of data that are going to process within the
program.

31. What are the different data types available in C? (Or) List different data types
available in C. (May/June 2014)
C supports 4 different types of data type. They are,
1. Primary Data Type
2. User Defined Data Type
3. Derived Data Type
4. Empty Data Type
32. What is Integer Data Type?
• Integer data type allows a variable to store numeric values.
• The keyword is used to define integer data type is “int”.
• The storage size of int data type is 2 or 4 or 8 byte.
• Eg., int a;
33. What is Floating Point Data Type?
Floating point data type consists of 2 types. They are,
 float
 double

float
• Float data type allows a variable to store decimal values.
• Storage size of float data type is 4 byte.
• These are numbers which contain fractional parts, both positive and negative.
• The keyword used to define float data type is, float.
• Eg: float a;
double
• Double data type is also same as float data type which allows up-to 10 digits after
decimal.
• The keyword used to define double variables is double.
• The range for double data type is from 1E–37 to 1E+37.
• Eg: double a;
34. What is Character Data Type?
• Character data type allows a variable to store only one character.
• Storage size of character data type is 1 byte. We can store only one character
using character data type.
• The keyword is used to define character data type is “char”.
• Eg: char a;

35. What is a Variable? (Or) What is a Variable? Illustrate with an example.


(Nov/Dec 2014) (Or) What are Variables? Give Examples. (May/June 2016)
• Variables are memory location in computer's memory to store data.
• To indicate the memory location, each variable should be given a unique name
called identifier.
• A variable is an identifier that is used to represent some specified type of
information within a designated portion of the program.
Syntax: Data_type variable name;
Example: int a; char m; float s;
36. Write down the rules for naming a variable.
• Variable name can be composed of letters (both uppercase and lowercase letters),
digits and underscore '_' only.
• The first letter of a variable should be either a letter or an underscore.
• No commas or blank spaces are allowed within a variable name.
• There is no rule for the length of length of a variable. However, the first 31
characters of a variable are discriminated by the compiler.
37. What is meant by scope of variables?
• Scope of the variable implies the availability of variables within the program.
• Variables have 2 types of scope.
o Local variables & Global variables
38. What is Local Variable?
• Local variables are defined inside a main function block (or) inside a compound
statement of a function subprogram are called local variables.
Example
function() {
int i, j;
}
39. What is Global Variable?
• The variables that are declared before the function main() are called the global /
external variables.
Eg:
int a, b; // here a,ball is a global variables.
main() {
……
function()
}
function() {…….}
40. What is an Operator and Operand?
Operators
• An operator is a symbol that specifies an operation to be performed on the
operands.
Operand
• It is a data item on which operators perform operation.
• Eg: a+b
Here, a, bOperands + Operator
41. What are the various operators available in C? (Or) What are various types of
C operators? (Jan 2014)
The various types of operators in C are,
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
42. What is Ternary Operator? (Or) What is Conditional Operator? (Or) Give an
example for ternary operator. (Nov/Dec 2014)
• Conditional operator itself checks the condition and executes the statement
depending on the condition.
• Syntax: condition?exp1:exp2
• Example: big=(a>b)?a:b;
43. What are increment and decrement operator?
• These are the increment (++) and decrement (--) operators. Both of these are unary
operators.
• The ++ adds 1 to the operand and – subtracts 1 from the operand.
o ++x Pre Increment (First increment and then return the value)
o --x Pre Decrement (First decrement and then return the value)
o x++ Post Increment (First return the value and then increment)
o x-- Post Decrement (First return the value and then decrement)

44. What are the logical operators available in C?


• Logical operators are used to combine the results of two or more conditions.
Operator Meaning Example
If c=5 and d=2 then,((c==5) &&
&& Logical AND (d>5))
Returns false.
If c=5 and d=2
|| Logical OR Then, ((c==5) || (d>5)) returns
true.
! Logical NOT If c=5 then !(c==5) returns false.
45. What are the Bitwise operators available in C?
• It is used to manipulate the data at bit level. It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
46. What is Assignment Operator?
• Assignment operators are used to assign a value or an expression or a value of a
variable to another variable.
• Syntax: variable=expression (or) value ;
• Example : x=10; x=a+b; x=y;
• Two types of assignment operator are,
o Compound Assignment
o Nested Assignment (or) Multiple Assignment
47. What is Dereferencing Operator?
• Dereferencing operation is performed to access or manipulate data contained in
memory location pointed to by a pointer.
• Any operation performed on the de-referenced pointer directly affects the value
of variable it points to.
48. What is Indirection Operator?
• Asterisk (*) is the indirection operator used along with pointer variable while
dereferencing the pointer variable.
• It is used to specify the value of the variable.
• It is also called as value at operator.

49. What is an Expression?


• An expression represents data item such as variables, constants and are
interconnected with operators as per the syntax of the language.
• Syntax: variable=expression;
• Eg: y=(a/b)+c; z=(a*b)-d;
50. What is Type Conversion? (Or) Define Implicit Type Conversion.
(May/June 2016)
• It is a process of converting the type of an expression from one type to another
type.
• Eg: x = (int)10.45

51. What are Input / Output Statements?


• In C Language two types of Input/output statements are available and all input and
output operations are carried out through function calls.
o Unformatted Input / Output Statements
o Formatted Input / Output Statements
52. Write a for loop statement to print number from 10 to 1. (Jan 2014)
#include<stdio.h>
#include<conio.h>
void main() {
int i;
clrscr();
for(i=10; i>=1; i--) {
printf(“number is %d”, i);
}
getch();
}
53. Write a code segment using while statement to print number from 10 to 1.
#include<stdio.h>
#include<conio.h>
void main() {
int x=10;
while(x<=1)
{
printf(“%d\n”,x);
x--;
}
getch();
}

54. What is the difference between ‘=’ and ‘==’ operator?


• = is an assignment operator. Used to assign values to the variables.
• == is a relational operator. Used to find the relation between the value and variable.
Example
• i=5 is an infinite loop because it is a non zero value.
• i==5 is true only when i=5.
55. What is the difference between if and while statement?
56. What is a Modulo Operator? (Or) Discuss the working of modulo operator.
(Nov/Dec 2015)
• ‘%’ is modulo operator. It gives the remainder of an integer division.
Example: a=17, b=6. Then c=%b gives 5.
57. How many bytes are occupied by int, char, float, long int and double?
• int - 2 Bytes
• char - 1 Byte
• float - 4 Bytes
• long int - 4 Bytes
• double - 8 Bytes
58. What is the difference between ++a and a++?
++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)
Example:
a=5;
x=a++; /* assign x=5*/
y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7*/
59. Define delimiters in ‘C’.
• A delimiter is a unique character or series of characters that indicates the beginning or
end of a specific statement, string or function body set.
• Delimiters are used in programming languages to specify code set characters or data
strings, which serve as data and code boundaries and facilitate the interpretation of
code.

60. Give the syntax for the ‘for’ loop statement.


for (Initialize Counter; Test Condition; Increment / Decrement Counter)
{
Statements;
}
66. What is the use of sizeof( ) operator?
• The sizeof( ) operator gives the bytes occupied by a variable.
• Number of bytes occupied varies from variable to variable depending upon its data
types.
Example:
int x, y;
printf(“%d”,sizeof(x));
Output:
2
67. Differentiate between while and do while statement. (Jan 2013)
while do….while
 It is an entry controlled loop or top  It is an exit controlled loop or bottom
tested loop. tested loop.
 First the condition is tested, if it is true  It executes the body once, after it checks
then the block is executed until the the condition, if it is true the body is
condition becomes false. executed until the condition becomes
false.
 Loop will not be executed if the  Loop will be executed at least once even
condition is false. though the condition is false.

68. Differentiate between break and continue statement.

Break Continue
Break statement takes the control to the Continue statement takes the control to the
outside of the loop. beginning of the loop.
This can be used only in looping
It is also used in switch statement. statements.
Always associated with if condition in
loops. This is also associated with if condition.

59. What is switch statement?


• The switch statement is used to execute a particular group of statements from several
available groups of statements.
• It is a multi-way decision statement, it tests the value of given variable or expression
against a list of case values and when a match is found and a block of statements
associated with that case is executed.
• Switch statement required only one argument of any data type which is checked with
number of case options.
• If the value matches with case constant, that particular case statement is executed if
not default is executed.
• Every case statements terminate with break statement is used to exit from the current
case structure.
60. What is goto statement?
• It is used to transfer the control unconditionally from one place to another place in the
program.
• When a goto statement is encountered inside a loop, the control is transferred to the
beginning.
• It requires a label to identify the place to move the execution.
• A label is a valid variable name and must be ended with colon (:).
61. What is break statement?
• It is used to terminate the loop.
• When a break statement is used inside any C loop, then the loop is terminated.
Syntax: break;
62. What is main( ) function in ’C’ program.
o Every C program must have main ( ) function.
o All functions in C has to end with ‘( )’ parenthesis.
o It is a starting point of all ‘C’ programs.
o The program execution starts from the opening brace ‘{‘and ends with closing brace

‘}’, within which executable part of the program exists.

63.What is Preprocessor Directive? (Or) What is the use of preprocessor directives?


(May/June 2014) (Or) Define Pre-processor directives in C. (April / May 201
• Before a C program is compiled in a compiler, source code is processed by a program
called preprocessor. This process is called preprocessing.
• Commands used in preprocessor are called preprocessor directives and they begin
with “#” symbol.
64. What are the rules for defining preprocessor directive?
• Every preprocessor must start with # symbol.
• The preprocessor is always placed before main() function.
• The preprocessor cannot have termination with semicolon.
• There is no assignment operator in #define statement.
65. What are different types of preprocessor directives in C? (Or) Write any two
preprocessor directive in C. (Dec/Jan 2014)
 The different types of preprocessor directives in C language are,
o File Inclusion
o Macro Substitution
o Conditional Inclusion

You might also like