Unit 1 Notes
Unit 1 Notes
Unit 1 Notes
Functional 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:
Functional paradigm.
Characteristics:
Logic paradigm.
Characteristics:
Object-oriented paradigm.
Characteristics:
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.
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.
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,
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:
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.
Precedence of operators
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
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)
== Equal to
Left to right
!= Not equal to
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
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, bOperands + 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.
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;
The syntax of assignment operators that is the catenation of the desired binary
operator to
the = operator.
sum += value; ⇔ sum = sum + value;
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:
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?
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.
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
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
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;
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
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.
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
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:
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.
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;
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.