Basics of Computer Languages Explained
Basics of Computer Languages Explained
COMPUTER ENGGINEERING
DEPARTMENT COMPUTER
PROGRAMMING
3310701
BASICS OF COMPUTER LANGUAGE
Q1: What is a computer language? Briefly describe the major type of the computer
languages?
Ans: Computer Language
The computer works by executing instructions. Each instruction directs one operation of the
computer system. Several instructions are written to perform one task. This set of instructions given to
the computer to perform a task is called the computer program.
The computer instructions are written in a specific manner and according to a set of rules. These
languages are divided into two main categories. These are given below.
1. Low Level Languages
2. High Level Languages
High-Level Languages
The programming languages that are close to human language are called high-level languages. The
instructions in these languages are more like human languages.
BASIC, FORTRAN, COBOLM, PASCAL, C, etc. are examples of high level languages. Unlike low
level languages, these languages are easier to learn. These languages are used for writing application
programs. For example, a high level language may be used for writing a program for maintaining the budget
of a company.
Source Code
A computer program written in a high level language is called the source code. It is also called the
source program. Since the computer works only with the binary code, the programs written in high level
languages cannot run directly on the computer. They must be converted into the binary code for execution
by the computer.
Object Code
A computer program written in the machine language is called the object code. It is also called the
object program. Since machine language is the native language of the computer, a program written in
machine language runs directly on the computer.
Q3: What are the language processors? Briefly describe their various types?
Language Processors
The computer works only with the binary code. Therefore, the programs written in high level
languages must be converted into the machine language (binary code) for execution by the computer.
Special programs are used to convert a source code into the object code. These programs are called
language processors.
Every high level programming language has its own language processor. The language processors
are divided into two categories. These are given below
1. Compilers
2. Interpreters
Compiler
The language processor that translates programs written in a high level language into the machine
language as a whole is called the compiler. The compiler translates the source program into the machine
code or object code. It saves the compiled program into another file called the object file. The computer
directly executes the object file. The program is compiled only once and can be executed a number of times
directly on the computer.
If there is any error in the source program, the compiler specifies the error at the time of compilation.
All errors must be removed before the compiler can successfully compile the source program.
Interpreter
The language processor that executes a source program by translating and executing one instruction
at a time is called interpreter. If there is any error in the instruction it indicates the error and program
execution stops.
The interpreter translates the program instructions one by one and executes them immediately. It
does not create an object program. Thus the interpreter translates the source program each time the program
is executed. This method of translating and executing a program is slow and time consuming. A BASIC
language processor is an example of Interpreter.
Machine Independent
A program written in a high level language can be used on any computer system for which the
compiler of the language is available.
Shorter Programs
The High level language programs are shorter than the programs written in machine languages. A
single instruction written in a high level language translates into several machine language instructions.
Easier to Understand
The program instructions in high level language are similar to the plain English statement. This
makes the program easy to understand. Anyone who is familiar with the computer language can easily
understand the logic of the program written in a high level language.
1. Input R
2. Compute A = 3.14 * R *R
3. Print A
4. STOP
Explanation: Here Input R (Step-1) represents that a value of R(radius) is to taken from user. The last step
is STOP which indicates end of algorithm.
1. Input n1, n2
2. if n1 < n2, goto 5
3. Print n2
4. goto 6
5. Print n1
6. STOP
Que. What is a flowchart ? Give the symbols used in flowchart with their use. Or
Draw basic flowchart symbols. [02]
Ans. A flowchart is a pictorial representation of algorithm. As it represents solution in form of picture.
It is more easier to understand and develop. A main advantage of flowchart is visibility of paths (or flows)
within solution. Each path (or logical sequence) is clearly visible as arrows are used to represent flow.
Before developing flowcharts for example problems, different flowchart symbols must be known. As
shown below…..
Arrow
Input / Output
Process / Computation
Decision Making
Subroutine
Page Break
Continue
Start
StatrStart
Start
Input R
A=∏ R2
Print A
STOP
Start
Input N1, N2
Yes No
N1 < N2 ?
Print N1 Print N2
Stop
Standard Defination : “ An algorithm is a procedure or formula for solving a problem, based on conductiong a
sequence of specified actions. A computer program can be viewed as an elaborate algorithm”.
Advantages of Algorithms:
Disdvantages of Algorithms:
Characteristics of Algorithms:
Uniqueness – results of each step are uniquely definedand only depend on the input and the result of the
precedingsteps.
Finiteness – the algorithm stops after a finite number ofinstructions are executed.
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Step 1: Start
Step 4: If a > b
If a > c
Else
Else
If b > c
Else
Step 5: Stop
Step 1: Start
D ← b2-4ac
Step 4: If D ≥ 0
r1 ← (-b+√D)/2a
r2 ← (-b-√D)/2a
Else
rp ← -b/2a
ip ← √(-D)/2a
Step 5: Stop
Step 1: Start
factorial ← 1
i←1
5.2: i ← i+1
Step 7: Stop
Step 1: Start
flag ← 1
i←2
flag ← 0
Go to step 6
5.2 i ← i+1
Step 6: If flag = 0
Display n is prime
Step 7: Stop
Step 1: Start
Step 6: Stop
Ans. Every C program is a group of building blocks that are called functions. A function is subroutine
that may include one or more statements designed to perform a specific task. C Program is divided in
following sections….
Documentation Section
Link Section
Definition Section
Global Declaration Section
Main() Function Section
{
Declaration Part
Executable Part
Function 1
Function 2 User - defined
: Functions
Function n
Documentation Section: It consists of a set of comment lines giving the name of the program, the
author and other details , which the programmer would like to use later.
For Example: // this is the prog. To find area of a circle.
Link Section: The link section provides instructions to the compiler to link functions from the
system library.
For Example: #include<stdio.h>
#include<conio.h>
Global Declaration Section: There are some variables that are used in more than
one function. These variables are called global
variables and are declared in the global declaration section
that is outside of all the functions. It means, if a variable is used in
more than one function than it is possible to declare it as global
variable. Generally it is declared above the Main()
function.
Main() Function Section: Every C program must have one main() section. This section contain two
parts, declaration part and executable part. The declaration part declares all the variables , which
are to be used in the executable part. There is at least one statement in executable part. These two parts
must be in between opening and closing braces. The program execution begins at the opening brace and
ends at the closing brace. The closing brace of the main function is the logical end of the program.
Note: (1) Remember that you should always declare all the types of variables before any
executable statement.
2) All statements in the declaration and executable parts end with a semicolon.
Subprogram Section: The subprogram section contains all the user defined functions that are called
in the main function. User defined functions are generally placed immediately after the end of main
function.
Note: All the sections, except main function may be absent when they are not required. Main
is the unique section of the program i.e more than one main() is illegal.
1. Creating a program
2. Compiling a program
3. Linking the program with functions that are needed from the C
library
4. Executing a program
b. As against this in bottom-up design programming begins with the smallest of logics and
from this the next bigger logic is built and so on further up till the entire problem is
programmed.
c. Modular programming is a term used to describe dividing a program into areas of code or
modules that perform specific tasks. The programmer designs the program in levels, where
a level consists of one or more modules.
Brief History of C:
C is a general purpose programming language. It was developed at AT & T Bell Laboratories in
1972. it was designed and written by Dennis Ritche. It was written as a part of the UNIX operating system.
The UNIX system and its tools were written in C. As the UNIX system spread, the C language also became
popular. Because of its capabilities as a medium level language, C language was used to develop system
software. It was also widely used to write software to control industrial processes.
ANSI-C Standard:
The standard for a language specifies the form of the program written in that language. It also
specifies how programs are to be interpreted. The purpose of a standard is to specify the syntax of the
language and make it portable across various computer systems
The standard for C language was first proposed by the American National Standards Institute
(ANSI) in late 1980s. In 1990, the International Standards Organization als9o adopted the ANSI standard
for C language. This is known as ANSI/ISO C standard. This standard is now an internationally recognized
standard and almost all C compilers now follow the ANSI C standard.
Advantages of C language
Following are the advantages of C language:
Portable Language
The C –programs written on one type of computer system can be easily used on another computer
system.
Efficient Language
Since C can directly access the hardware of the computer system and uses fewer commands, the
compiled C programs run more efficiently on the computer than that of other languages.
Structure of C programs
The format according to which a program is written is called the structure of the program. The
structure of a C program consists of three main parts. These are given below:
Preprocessor Directives
The main() function
C Statements
A program example is given below. The first statement of the program is a preprocessor directive. This
preprocessor directive has been written to include the stdio.h header file. The second statement indicated
the main function. The C statements are written in the main function within curly braces.
#include <stdio.h>
main ()
{
printf ("This is my first Program");
}
Preprocessor Directives
The Instruction that are given to the compiler before the beginning of the actual program are
called preprocessor directives. These are also known as compiler directives. These are written at the
beginning of the source code.
These preprocessor directives start with a number sign (#) and the keyword "include" or "define".
They are the instructions or directives that tell the compiler to take action(s) before compiling the source
code. The program that handles the preprocessor directives is called the preprocessor because it does some
processing before the compilation process starts.
For example, preprocessor directives are used to include header files in the program. The
preprocessor includes the specified header file into the source code before compiling.
Q10: what are Header files and what are they used for?
Header Files
Header files are part of the C compiler and contain definitions of standard library functions. There
are several header files. Each header file contains definitions of one type of functions only. For example,
the math.h header file contains definitions of mathematical functions available in C language.
Each header file has an extension .h. The preprocessor directive "include" is used to add a header
file into the program. The name of the file is written in angle brackets (<>) after "#include" directive. The
syntax to include a header file is:
Giving the name of the header file in angle brackets specifies that the header file is located in the
include directory of the compiler program.
The name of the header file can also be written in double quotes. When the name of the file is
written in double quotes. It specifies that the file is to be loaded from the current directory. The syntax to
include a header file is:
A header file is added if the functions defined in it are to be used in the program. For example, the
header file stdio.h had definitions of various built-in input and output functions. This file is included in a
program if any of its functions is used in the program.
main()
{
program statements…
}
C Statements
The statements of the program are written under the main() function between curly braces
{}. These statements are the body of the program. Each statement in C ends with a semicolon(;).
C is a case sensitive language. The C statements are normally written in lowercase letters
but, in some cases, these can also be written in uppercase.
Keywords:
The words that are used by the language for special purposes are called keywords. These are also
called reserved words. These have predefined uses and cannot be used for any other purpose in a C program.
These are always written in lower case
For example, in a C program, the keyword main is used to indicate the starting of the program,
include is used to add header files, int is used to declare an integer type variable. All these words are
keywords of C.
There are 32 words defined as keywords in C. Following is the completer list of C keywords:
C Keywords:
Tokens
A program statement consist of variable names, keywords, constants, punctuation marks, operators,
etc. In C, these elements of a statement are called tokens. In the following program segment:
main()
{
int a, b;
}
main, {, }, int, a, b and punctuation marks (,) and (;) are tokens of the program.
Q15: What are Comments and what are they used for?
In C, a slash asterisk (/*) combination is used to specify the beginning and asterisk slash (*/) is used
to mark the end of the comment statement. For example
In the above example, two lines indicate the comment statements. The comments can be given at any place
in the source program. For example, the comments can also be given after a C statement as shown below:
Creating C program:
There are four fundamental stages or steps in creating a C program. These steps are Editing,
Compiling, Linking and Executing a program. A brief description of these steps is given below:
Editing
Writing, Changing and revising the source code is called editing. In this step the source code of the
program is written and edited. The source code is written in any text editor. It is saved on the disk in an
ASCII text file.
Most C compilers come with an editor for writing the source code. This editor is specially designed
for writing the source code of C programs. It provides features that make the writing of the C source code
Compiling
The converting of the source code into the machine code is called compiling. The program that is
used to convert the source code into the machine code is called the compiler.
The compiler takes the source code file of the C program stored on the disk. It converts it into the
machine code or the object code. Object code is the intermediate form of the program. In the first step, the
compiler creates object code and saves it in a new file on the disk. The file has an extension obj.
Before creating the object code, the compiler scans the source code for errors. If there are errors in
the source code, it does not compile the source code and indicates the errors. All errors must be removed
from the source code before creating the object code of the program.
Linking
In this step the necessary libraries are linked to the object code. After linking the libraries, the
executable file of the program is created.
A C program may contain predefined routines and functions. These functions are contained in
separate files. These files are part of the C compiler and are called library files or runtime libraries.
The linker can also detect errors. For example, if the source code uses a library function that does
not exist, the linker generates an error. Of there are errors, the linker does not create the executable file.
These are removed in the source code and a new object file is created. The new object file is then linked to
the libraries to create executable file. The executable file is created with the .exe extension. This file is
directly run on the computer system.
Executing
In this step, the program is actually run on the computer system. The executable file is run by giving
it to the system loader. For example, In Windows Operating System, when the name of an executable file
is double clicked, the system loader loads the file into the computer memory and executes it.
The executable file of the program may also contain certain errors. These errors can produce wrong
output or they may halt the system. These errors are located and removed in the source code and the source
code is again compiled to create a new executable file.
Preprocessor
Every C source code contains certain preprocessor directives at the beginning of the code. These
directives are instructions for the C preprocessor.
Preprocessor is the part of the C compiler. Before translating the program into the object code, the
preprocessor carries out the preprocessor directives. These directives start with the number sign (#). The
most commonly used preprocessor directives are #include and #define.
Usually preprocessor directives a meant to include a header file into the source code. Before
compiling the program, preprocessor includes the required header file into the source code. The new source
code is called the expanded source code. The compiler then translates the expanded source code into the
object code.
Debugging
Errors in a program are called "bugs" and tracking and removing these errors is called debugging.
There can be two main types of errors in a program. There are given below.
Syntax Errors
The rules for writing statements of a computer programming language are called syntax of the
language. The program statements are written strictly according to these rules. A single mistake in these
rules causes an error. This error is called syntax error. The compiler detects these errors. It does not compile
a program that contains syntax errors. These errors are easy to locate and remove.
Logical Errors
The errors in the logic of a program are called logical errors. The compile cannot detect these errors.
A program with logical errors runs correctly but it gives wrong result.
The logical errors may occur due to the following reasons.
The input data may be incorrect because the out put of the program depends upon
the input data
The sequence of instructions used in a program may be correct
A mathematical formula used in program instructions may be incorrect. For example
using a division operator (/) in a formula when the multiplication operator (*) should
have been used causes wrong output.
These errors are most difficult to locate and remove. To track logical errors, all units of the program are
examined one by one.
Constants:
The quantity whose value cannot change during the execution of the program is called constant. It
may be a numeric or a non numeric quantity.
Variables
A quantity whose value may change during execution of the program is called variable. It may be
a numeric or a non-numeric quantity. It is represented by a symbol called variable name. The variable name
consists of alphabets and digits.
A variable represents a storage or memory location in the computer memory. Data is stored into the
memory location. The name of the memory location, i.e. the variable name, remains fixed during execution
of the program but the data stored in that location may change from time to time.
Data Types in C:
The actual values used in a program are called data. There are four basic types of data in C. these are:
int Integer
float Real Values
double Large real values
char Characters
Data Types
Type Size in Bytes Data storage Range
int 16 bits (2 bytes) -32768 to 32767
short int 16 bits (2 bytes) -32768 to 32767
long int 32 bits (4 bytes) -2147483648 to
2147483647
unsigned int 16 bits (2 bytes) 0 to 65635
1. int
2. short int
3. long int
4. unsigned int
The int:
The range of values of int data type depends upon the computer system being used and it takes two
to four bytes. In MS DOS, an integer type variable takes two bytes in the memory and the range of values
stored is from -32768 to 32767.
The maximum and minimum values for integer data types are specified in integer.h header file. The
minimum integer value is defined by INT_MIN and maximum integer value is defined by INT_MAX.
1. float
2. double
Q6: Explain how real numbers are expressed in scientific or exponential notation?
A real type data can also be represented in exponential form. In this form, a real number is divided into
two parts i.e. a mantissa and an exponent. The general form of a real number in exponential form is:
±mE ±n or ±me ±n
where
m represent the mantissa. It has an absolute value greater than or equal to 1.0 and less than
10.0
n represents the value of exponent. It is a real number.
Integer Constants
A numerical value without a decimal is called integer constant. The minus (-) sign is used to indicate
a negative integer constant. The use of (+) sign with a positive integer constant is optional.
Integer constants are used in expressions for calculations. The Integer constants are written without
".", "e", or "f". For example:
1000 -87
The long integer constants are written with L appended. For example:
8000000L -86316L
Character Constants
A single character enclosed in single quotation marks is called character constant. For example 'a',
'/', and '+' represent character constants.
String Constants
A sequence of characters consisting of alphabets, digits and/or special characters enclosed in double
quotation marks is called string constants. For example, "Pakistan" and "Lahore" are examples of string
constants.
The long integer type variables are declared using the long int keyword. For example, to declare a variable
"length" of long integer type, the statement is written as:
long int length;
The float type variables are declared using the float keyword. For example, to declare a variable "length"
of float type, the statement is written as:
float height;
The double type variables are declared using the double keyword. For example, to declare a variable
"distance" of double type, the statement is written as:
double distance;
The long double type variables are declared using the long double keyword. For example, to declare a
variable "huge" of long double type, the statement is written as:
long double huge;
The character type variables are declared using the char keyword. For example, to declare a variable "nm"
of char type, the statement is written as:
Char nm;
More than one variable of the same data type can also be declared in one statement. In this case, the names
of the variables are written after the keyword separated by commas. For example, to declare three variables
"xyz", "d" and "s" of integer type, the statement is written as:
Int xyz, d, s;
To declare different types of variables, different statements are used. For example, to declare variables a
and xy as int types, b as float type, nm as character type and sum as double type, the statement are written
as:
int a, xy;
float b;
char nm;
double sum;
Que. Define an operator. List all the operators and explain any two of them.
Ans. An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. They are used in programs to manipulate data and variables. They are used
generally a part of the mathematical or logical expression.
There are following categories of operators.
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:The operators +,-,* and / all work the same way as they are used in other languages.
These can operate on any built in data type allowed in “C”. The unary minus operator multiplies its single
operand by –1, a number preceded by a munus sign changes its sign. As the arithmetic operators perform
mathematical functions the meaning is also same in language “C”. + means Addition, - means Subtraction,
* means Multiply, / means Division and % means Modulo division. It is subdivided into three categories
as follows.
Integer Arithmatic: When both the operands are integers the expression is called Integer
Arithmetic. Integer Arithmetic always have integer [Link] largest integer value depends on the
machine. For example a=14, b=3…
a+b=17 a-b=11 a*b=42 a/b=4(decimal part truncated)
a%b=2(remainder of division)
During the integer division, if both the operands are of the same sign, the result is truncated towards
zero. If one of them is negative, the direction of truncation is implementation dependent. i.e 6/7=0 and –
6/-7=0 but –6/7 may be zero or –1.
Similarly during modular division, the sign of the result is always the sign of the first
operand(the dividend). i.e –14%3= -2 -14 % -3 = -2 14 % -3 = 2 and also remember that
%(modulo operator) can not be used with real(floating) values.
Real Arithmetic: An arithmetic operation involving only real operands is called “real arithmatic”.
A real operand may assume values either in decimal or exponential notation. If x,y,z are floats, then,….
x= 6.0 / 7.0 = 0.857143
y= 1.0 / 3.0 = 0.333333
z= -2.0 / 3.0= -0.666667
Mixed Mode Arithmetic: When one of the operand is real and other is integer, the expression is
called mixed mode arithmetic expression. If either operand is of real(float) type, then only the real operation
is performed and the result is always a real number. i.e 15 / 10.0 = 1.5 where as 15 / 10 = 1
Relational Operators: The relational operators are generally used to compare two values, which is
necessary to take certain decisions. An expression such as A > B or 1 < 20 containing relational operators
is known as relational expression. The value of relational expression is either one or zero. The value is
Opeator Meaning
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal to
== Is equal to
!= Not equal to
Relational expressions are used in decision making statements such as if and while to decide something.
Each relational operator needs two operands for comparison of their values. Hence, these operators are
binary operators. Following examples shows the expressions involving relational operators.
1. a<b
2. a==b+3
3. d>=5.66
4. alphabet !=’t’
5. (p+q)<=(t+r-5)
The expression a<b means “is a less than b?” The result of comparing a with b may be either ‘true’ or
‘false’. If it is false, the value of the expression is treated as 0, and if true as 1.
Example:
Program Output
main() 0
{ 1
int a=10,b=20,c=30,d,e;
d=a>b;
e=b<=c;
printf(“%d \n %d”, d,e);
}
Logical Operators: The logical operators are used when we want to test more than one condition and
make decisions. “C” has following three logical operators.
|| meaning logical OR
(expression1) || (expression2)
Operands Results
Exp1 Exp2 Exp1 && Exp2 Exp1 || Exp2
An example is :
a>b && a>c
An expression of this kind which combines two or more relational expressions is termed as a logical
expression or compound logical expression. It works similarly as an electronic gate works. For above
example, if a>b and a>c when both the conditions are true (1) then only the expression value is true
(1). If one of the conditions is false (0) then the whole expression value is false (0).
Similarly for a>b || a>c if only one of the conditions is true (1) then the whole expression value is true
(1) and if both the conditions are false (0) only then the whole expression value is false (0).
The third logical operator is the not operator, written as !. This operator reverses the value of the expression
it operates on; it makes true expression false and a false expression true.
y=9
!(y<10)
Will give false as result because we negate the condition with not operator.
Assignment Operator: Assignment operators are used to assign the result of an expression to a variable.
The assignment operator is ‘= ‘also used a ‘shorthand’ assignment operators.
Increment and Decrement Operators: These are unary operator since they operate only on one operand.
The operand has to be a variable and not a constant. Thus, the expression a++ is valid whereas 6++ is
invalid. The increment (++) and decrement (--) are very useful operators in “C”. The operator ++ adds 1 to
the operand while – subtracts 1 from the operand. They may have following forms…
These operators can be used either before or after their operand (i.e. in either ‘prefix’ or ‘postfix’ position),
so we can have a++ (postfix) as well as ++a (prefix), and a-- as well as --a. Prefix and postfix operators
have same effect if they are used in a different statements.
For example, the effect of the following two statements would be same.
a++
++a
However, prefix and postfix operators have different effects when used in association with some other
operators in C statements. For example;
a=5
a=a+1
b=a
a=a-1;
b=a;
b=a;
a=a-1;
Example program:
Program Output
main() 10
{ 11
int a=10,b=10;
printf(“%d”, a++);
printf(“%d”, ++b);
}
A=10; if(A>B)
B=20; X=A;
X=(A>B)?A:B; else
X=B;
For the above example the value of X=20.
Example program:
Program Output
Bitwise Operators:
Normally the higher level languages don’t support the bit-wise operators as they denotes the lower level
operations which are common in assembly / machines languages. But “C” language is exception. It supports
the bit-wise operators. Two operands are compared on a bit-by-bit basis. Hence both the operands must be
of the same type( either char or int)
Throughout the discussion of bitwise operators we are going to use a function called showbits(). The task
of showbits() is to display the binary representation of any integer or character value. For example;
Assume n=4
Then the output of showbits(n)=0100
Following operators are used as bit-wise operator with their meaning….
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Left Shift
>> Right Shift
~ 1’s complement
Special Operators: C supports some special operators such as Comma operator and sizeof operator.
Comma Operator: The comma operator can be used to link the related expressions together. A
comma linked-list of expressions are evaluated left to right and the value of right-most expression is the
value of the combined expression. for example the statement value=(x=10,y=5,x+y); first assigns the
value 10 to x, then assigns 5 to y and finally assigns 15 (i.e. 10+5) to value. Since comma operator has the
lowest precedence of all operators the parentheses are necessary. We can also use it in for loop as follows:
for(n=1, m=10; n<=m; n++,m++)
Sizeof Operator: The sizeof is a compile time operator and, when used with an operand, it returns
the number of bytes the operand occupies. The operand may be a variable, a constant or a data-type
qualifier.
For Example: m = sizeof(sum); k = sizeof(235L);
n = sizeof(long int);
the sizeof operator normally used to determine the lengths of arrays and structutes when their sizes
are know to the programmer.
Operators Associativity
( ) , [ ], -> Left to right
! ~ ++ -- +(unary plus) – (unary minus) * &(Address) sizeof Right to left
* / % Left to right
+ - Left to right
<< >> (bitwise operators) Left to right
< <= > >= (relational operators) Left to right
== != Left to right
& (bitwise AND) Left to right
^ (bitwise EX-OR) Left to right
| (bitwise OR) Left to right
&& (Logical AND) Left to right
| | (logical OR) Left to right
? : (conditional operator) Right to left
= *= /= %= += - = &= ^= |= <<= >>= (assignment) Right to left
, (comma operator) Left to right
int a,e;
float b,d;
double c;
e = a * b + c / d
(float) (double)
(float) (double)
(int) (double)
Type Casting: Some times user needs explicit type conversion. For example, int/int is always int, but if
we need the answer in float then explicit type casting is useful. Consider the following statements.
float average;
int sum= 25;
int n = 10;
average = (float)sum / n;
where sum/n results into 2.5 rather than 2 because the division is performed after converting the sum into
float and the result of float/int is always float. The conversion does not change the value. It only changes
the fype for evaluation process only.
(type_name)expression;
where, type_name is type to which the expression value is casted. It can be any valid data type of “C”.
Extra Questions:
1. Explain the following operators. May-05[04]
1. ?.
2. Size of.
3. ++ and -- . [09]
4. Conditional (?:)
5. Bit wise
6. Cast
Here, the condition is represented by relational or logical expression. If condition is true then
statement 1 is executed and if condition is false, then statement 2 is executed. The statement 1 and/or
statement 2 can be either single statement or compound statement i.e group of statements. A compound
statement must be enclosed in pair of braces { }. Enclosing a single statement in braces { } is not
compulsory. Note that this conditional statement doesn’t require a semicolon.
The else part in if-else is optional. The if statement without else looks like:
if(condition)
statement;
For example
main()
{
int num;
printf(“Enter a number greater than 5”);
scanf(“%d”,&num);
if(num>5)
printf(“What an obedient servant you are!”);
}
In this case, if condition is true, then statement is executes, otherwise control transferred to the
statement that follows the if structure. The fig. shows the above explanation…
Nested if-else: Generally the nested if else is used in multiple condition checking. Here any one condition
is taken as main condition. The format is given below:
Here if the condition1 is true only then control is transferred to the condition2 and if it is true then only
statement1 is executed. If condition1 is true and condition2 is false then statement2 is executed. If
condition1 is false then statement3 is executed after that the control will be transferred to the next statement
after the if-else structure.
For example:
main()
{
int i;
printf(“Enter either 1 or 2”);
scanf(“%d”,&i);
if(i==1)
printf(“You would go to heaven!);
else
{
if(i==2)
printf(“Hell was created with you in mind”);
else
printf(“how about mother earth”);
}
}
Ladder if-else: The ladder if-else is very useful to allow multiple choice. It means to select one alternative
from many. The format is given below:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.
.
.
else if(conditionN)
statementN;
else
default_statement;
In above multiple if-else, compound statement must be enclosed in pair of braces { }. The last else is
optional. Here the condition1 is evaluated first and if it is true then statement1 is executed otherwise
condition2 is evaluated and if it is true then statement2 will be executed and so on. If all the conditions
become false then default_statement is executed.
AVPTI COMPUTER ENGINEERING DEPARTMENT 40
For example:
Que: The marks obtained by a student in 5 different subjects are input through the keyboard. The student
gets a division as per the following rules:
% >= 60 :First division
% >50 but %<60 :Second division
% >40 but <50 :Third division
% < 40 :Fail
Program:
main()
{
int m1,m2,m3,m4,m5;
float per;
printf(“Enter the marks in 5 subjects”);
scanf(“%d %d %d %d %d “, &m1, &m2, &m3, &m4, &m5,);
per=(m1+ m2+ m3+ m4+ m5)/5;
if(per >=60)
printf(“First Division”);
else
{
if(per >=50 && per <60)
printf(“Second Division”);
else
{
if(per >=50 && per <60);
printf(“Second Division”);
else
{
if(per >=40 && per <50);
printf(“Third Division”);
else
printf(“Fail”);
}
}
}
}
Ultimately collectively the various form of if constructs can be organized as:
Sr Form of if Example
no
1. If(expression) If(i==1)
Statement1; Printf(“%d”,i);
2. If(expression) If(marks>40)
{ {
statement 1; Printf(“You have passed”);
statement 2; Printf(“You can get prize”);
……….. }
statement n;
6. If(expression) If(per>=60)
{ Printf(“First Division”);
Statement 1; Else
Statement 2; {
………….; if(per>=50)
statement n; Printf(“Second Division”);
} Else
else {
{ if(per>=40)
if(expression) Printf(“Third Division”);
{ Else
Statement 1; Printf(“Fail”);
Statement 2; }
………….; }
statement n;
}
else
{
if(expression)
{
Statement 1;
Statement 2;
………….;
statement n;
}
else
{
Statement 1;
Statement 2;
………….;
statement n;
}
}
}
switch(c)
{
AVPTI COMPUTER ENGINEERING DEPARTMENT 44
case ‘v’ :
printf(“I am in case v\n”);
break;
case ‘3:
printf(“I am in case 3n”);
break;
case ‘12’ :
printf(“I am in case 12\n”);
break;
}
}
4. Sometimes there may not be any statement in some of the cases in switch.
main()
{
char ch;
printf(“Enter any of the alphabet a or b”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘A’:
printf(“a as in ashar”);
break;
case ‘b’:
case ‘B’:
printf(“b as in brain”);
break;
case ‘c’:
case ‘C’:
printf(“c as in cookie”);
break;
default:
printf(“ Wish you knew what are alphabets”);
}
}
5. Even if there are multiple statements to be executed in each case there is no need to enclose
these within a pair of braces.
6. Switch offers a better way to writing as compared to if.
7. A switch can occur within another.
The disadvantage of switch statement is that we must have character or integer constant after case.
Que: What is the importance of looping ? explain entry controlled loop(any one) and exit controlled
loop.
Ans: If you want to execute some specific part of program (body of loop) repeatedly then looping is very
useful. It generally checks the condition, and executes the specific part (body of loop) if the condition is
true. This process is repeated until the condition becomes false. So, it works like a counter.
Entry controlled loops: In entry controlled loop, the condition is checked first and then body of
loop is executed. It means, first it checks the condition and if it is true then the body of loop will be executed.
After that it again checks the condition, and if it is true then body of loop will be executed again. This will
be repeated until the condition become false. If the condition is false very first time, then control is
transferred to the next statement outside of the loop.
while and for are examples of entry controlled loops.
while loop:
The structure of while loop is as given below.
while (test condition)
{
Body ;
}
statementX;
Here, condition is evaluated first and if it is true, then the statements in the body of the loop are
executed. After executing body, the condition is evaluated again and if it is true body is executed again.
This process is repeated again as long as the condition is true. The control moves out, once the condition
is false. It is not necessary to enclose body of loop in pair of braces { } if body contains only one statement.
The flow chart is given as below.
For example, the while loop can be written as follows to print 1 to 10.
…
…
i=1;
while (i <= 10)
{
printf(“%d\n”,i);
i++;
}
…
…
for(x=0;x<=9;x++)
{
printf(“%d”,x);
}
printf(“\n”);
In above example the for loop is executed 10 times and prints the digits 0 to 9 in one column.
for(x=9;x>=9;x--)
{
printf(“%d”,x);
}
printf(“\n”);
In above example the for loop is executed 10 times and prints the digits 9 to 0 in one column.
Exit controlled loop: On some occasions it might be necessary to execute the body of the loop
before the test is performed. Such situations can be handled with the help of the do statement. The syntax
is as follows.
do
{
body of the loop;
}
while(test-condition);
AVPTI COMPUTER ENGINEERING DEPARTMENT 47
On reaching the do statement, the program proceed to evaluate the body of the loop first. At the end
of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop will be terminated and the control goes to the statement
that appears immediately after the while statement. Since the test-condition is evaluated at the bottom of
the loop, the do…while construct provides an exit-controlled loop and therefore the body of the loop is
always executed at least once. For example,
…
…
i=1;
sum=0;
do
{
sum= sum + i;
i=i+2;
}
while(sum<40 || i<10);
printf(“%d %d\n”, i, sum);
….
The loop will be executed as long as one of the two relations is true.
The flow chart of exit controlled loop is as given below.
Extra Questions:
Que: Define array. Explain the declaration and initialization of 1-D array.
Ans: An array is a group of related data items that share a common name. For example if we define an
array name price to represent a set of prices of a group of items. A particular value is indicated by writing
a number called index number or subscript in brackets after the array name. For example, price[10]
represents the price of 10th item. While the complete set of values is referred to as an array, the individual
values are called elements. Array can be of any variable type.
A list of items can be given one variable name using only one subscript and such a variable is called
a single-subscripted variable or a one-dimensional array.
For ex., int num[5]; and the computer reserves five storage locations as below:
num[0] 10
num[1] 20
num[2] 30
num[3] 40
num[4] 15
These elements may be used in programs just like any other C variable.
For ex, a=num[0]+100;
num[2]=num[3] + num[4]; etc.
We also can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The general form of initialization of arrays is:
static data_type variable-name[size] = { list of values };
The values in the list are separated by commas. For example,
static int number[3]= { 5,5,5};
will declare the variable number as an array of size-3 and will assign 5 to each element. If the number of
values in the list is less than the number of elements, then only that many elements will be initialized.
The remaining elements will be set to zero automatically.
The size may be omitted. In such case the compiler allocates enough space for all initialized elements. For
ex. static int counter[] = {1,1,1,1};
Will declare the counter array to contain four elements with initial values 1.
As an ordinary variable we can use the elements of two dimensional arrays for arithmetic operations.
Like the one dimensional arrays , two dimensional arrays may be initialized by following their declaration
with a list of initial values enclosed in braces, for example: