C Progm 1 and 2 Module Notes
C Progm 1 and 2 Module Notes
MODULE-1
Problem Solving techniques: Introduction, Problem solving procedure, Algorithm: Steps
involved in algorithm development. Algorithms for simple problems: To find largest of
three
numbers, factorial of number, check for prime number, check for palindrome, Count no. of
odd,
even and zeros in list of integers.
Flowcharts: Definition, advantages, Symbols used in flow charts. Flowcharts for simple
problems mentioned in algorithms. Pseudocode.
------------------------------------------------------------------------------------------------
Problem Solving techniques: “Computer Science is a science of abstraction -creating the
right model for a problem and devising the appropriate mechanizable techniques to solve it.”
the term computerisation to indicate the use of computer to develop software in order to
automate any routine human task efficiently. Computers are used for solving various day-to-
day problems and thus problem solving is an essential skill that a computer science student
should know
The computers themselves cannot solve a problem. Precise step-by-step instructions should
be given by us to solve the problem. the success of a computer in solving a problem depends
on how correctly and precisely we define the problem, design a solution (algorithm) and
implement the solution (program) using a programming language. Thus, problem solving is
the process of identifying a problem, developing an algorithm for the identified problem and
finally implementing the algorithm to develop a computer program.
To apply problem solving techniques. Problem solving begins with the precise identification
of the problem and ends with a complete working solution in terms of a program or software.
1
BCA103
Procedure (Steps Involved in Problem Solving) A computer cannot solve a problem on its
own. One has to provide step by step solutions of the problem to the computer. In fact, the
task of problem solving is not that of the computer. It is the programmer who has to write
down the solution to the problem in terms of simple operations which the computer can
understand and execute. In order to solve a problem by the computer, one has to pass though
certain stages or steps. They are
Understanding the problem
Analysing the problem
Developing the solution
Coding and implementation
Algorithm
A set of sequential steps usually written in Ordinary Language to solve a given problem is
called Algorithm.
It may be possible to solve to problem in more than one ways, resulting in more than one
algorithm. The choice of various algorithms depends on the factors like reliability, accuracy
and easy to modify. The most important factor in the choice of algorithm is the time
requirement to execute it, after writing code in High-level language with the help of a
computer. The algorithm which will need the least time when executed is considered the best.
Steps involved in algorithm development
An algorithm can be defined as “a complete, unambiguous, finite number of logical steps
for solving a specific problem “
Step1. Identification of input: For an algorithm, there are quantities to be supplied called
input and these are fed externally. The input is to be indentified first for any specified
problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
for any specified problem.
Step3 : Identification the processing operations : All the calculations to be performed in
order to lead to output from the input are to be identified in an orderly manner.
Step4 : Processing Definiteness : The instructions composing the algorithm must be clear
and there should not be any ambiguity in them.
Step5 : Processing Finiteness : If we go through the algorithm, then for all cases, the
algorithm should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently
basic and in practice they can be carries out easily
An algorithm must possess the following properties
1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated
2
BCA103
3. Effectiveness: Each step must be effective, in the sense that it should be primitive easily
convert able into program statement) can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to solve
problems of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities as input data produce
one or more output values. An algorithm can be written in English like sentences or in any
standard representation sometimes, algorithm written in English like languages are called
Pseudo Code
Example 1. Suppose we want to find the average of three numbers, the algorithm is as
follows
Step 1 :Read the numbers a, b, c
Step 2: Compute the sum of a, b and c
Step 3 :Divide the sum by 3
Step 4 :Store the result in variable d
Step 5 :Print the value of d
Step 6: End of the program
1. Write an algorithm to calculate the simple interest using the formula. Simple interest
= P*N* R/100.
Where P is principle Amount, N is the number of years and R is the rate of interest.
Step 1: Read the three input quantities’ P, N and R.
Step 2 : Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.
2. Area of Triangle:
Write an algorithm to find the area of the triangle. Let b, c be the sides of the triangle ABC
and A the included angle between the given sides.
Step 1: Input the given elements of the triangle namely sides b, c and angle between the sides
A. Step 2: Area = (1/2) *b*C* sin A
Step 3: Output the Area
Step 4: Stop.
3. Write an algorithm to find the largest of three numbers X, Y,Z.
Step 1: Read the numbers X,Y,Z.
Step 2: if (X > Y)
Big = X
3
BCA103
else BIG = Y
Step 3 : if (BIG < Z)
Step 4: Big = Z
Step 5: Print the largest number i.e. Big
Step 6: Stop.
4. Write down an algorithm to find the largest data value of a set of given data values
Algorithm largest of all data values:
Step 1: LARGE 0
Step 2: read NUM
Step 3: While NUM > = 0 do 3.1 if NUM > LARGE 3.1.1 then 3.1.1.1 LARGE NUM 3.2.
read NUM Step 4: Write “largest data value is”, LARGE
Step 5: end.
5. Write an algorithm which will test whether a given integer value is prime or not.
Algorithm prime testing:
Step 1: M 2
Step 2: read N
Step 3: MAX SQRT (N)
Step 4: While M < = MAX do 4.1 if (M* (N/M) = N 4.1.1 then 4.1.1.1 go to step 7 4.2. M
M + 1 Step 5: Write “number is prime”
Step 6: go to step 8
Step 7: Write “number is not a prime”
Step 8: end.
6. Write algorithm to find the factorial of a given number N
Step 1: PROD 1
Step 2: I 0
Step 3: read N
Step 4: While I < N do 4.1 I I + 1 4.2. PROD PROD* I
Step 5: Write “Factorial of”, N, “is”, PROD
Step 6: end.
7. Write an algorithm to find sum of given data values until negative value is entered.
Algorithm Find – Sum
Step 1: SUM 0
4
BCA103
Step 2: I 0
Step 3: read NEW VALUE
Step 4: While NEW VALUE < = 0 do 4.1 SUM SUM + NEW VALUE 4.2 1 I + 1 4.3
read NEW VALUE
Step 5: Write “Sum of”, I, “data value is, “SUM
Step 6: END
8.Write an algorithm to calculate the perimeter and area of rectangle. Given its length
and width. Step 1: Read length of the rectangle.
Step 2: Read width of the rectangle.
Step 3: Calculate perimeter of the rectangle using the formula perimeter = 2* (length +
width)
Step 4: Calculate area of the rectangle using the formula area = length *width.
Step 5: Print perimeter.
Step 6: Print area.
Step 7: Stop
9. Algorithm to check if a given number is Palindrome or not
Step 1: Start
Step 2: Read the input number from the user
Step 3: Declare and initialize the variable reverse and assign input to a temp variable
tempNum=num
Step 4: Start the while loop until num !=0 becomes false
rem = num % 10
reverse*= 10 + rem
num = num / 10
Step 5 : Check if reverse == tempNum
Step 6: If it’s true then the number is a palindrome
Step 7: If not, the number is NOT a palindrome
Step 8: Stop
5
BCA103
1. Initialize Counters: Create two counters, one for odd numbers and one for even
numbers. Set both counters to zero.
2. Loop Through Numbers: Iterate through each number from 1 to 100.
3. Check Each Number:
- If the number is divisible by 2 (i.e., number % 2 == 0), it is even. Increment the
even counter.
- Otherwise, it is odd. Increment the odd counter.
4. Output the Results: After the loop, print or return the counts of odd and even
numbers.
6
BCA103
Symbols used in Flow-Charts The symbols that we make use while drawing flowcharts as
given below are as per conventions followed by International Standard Organization (ISO).
a. Oval: Rectangle with rounded sides is used to indicate either START/ STOP of the
program.
b. Input and output indicators: Parallelograms are used to represent input and output
operations. Statements like INPUT, READ and PRINT are represented in these
Parallelograms.
c. Process Indicators: - Rectangle is used to indicate any set of processing operation such as
for storing arithmetic operations.
d. Decision Makers: The diamond is used for indicating the step of decision making and
therefore known as decision box. Decision boxes are used to test the conditions or ask
questions and depending upon the answers, the appropriate actions are taken by the computer.
The decision box symbol is
e. Flow Lines: Flow lines indicate the direction being followed in the flowchart. In a
Flowchart, every line must have an arrow on it to indicate the direction. The arrows may be
in any direction
7
BCA103
f. On- Page connectors: Circles are used to join the different parts of a flowchart and these
circles are called on-page connectors. The uses of these connectors give a neat shape to the
flowcharts. Ina complicated problems, a flowchart may run in to several pages. The parts of
the flowchart on different pages are to be joined with each other. The parts to be joined are
indicated by the circle.
g. Off-page connectors: This connector represents a break in the path of flowchart which is
too large to fit on a single page. It is similar to on-page connector. The connector symbol
marks where the algorithm ends on the first page and where it continues on the second.
1 Simple Problems using Flow Chart Draw the Flowchart for the following 1. Draw the
Flowchart to find Roots of Quadratic equation ax2+ bx + c = 0. The coefficients a, b, c are
the input data
8
BCA103
2. Draw a flowchart to find out the biggest of the three unequal positive numbers.
9
BCA103
3. Draw a flowchart for adding the integers from 1 to 100 and to print the sum.
10
BCA103
Pseudocode:
The Pseudo code is neither an algorithm nor a program. It is an abstract form of a program. It
consists of English like statements which perform the specific operations. It is defined for an
algorithm. It does not use any graphical representation. In pseudo code, the program is
represented in terms of words and phrases, but the syntax of program is not strictly followed.
Advantages: * Easy to read, * Easy to understand, * Easy to modify.
Example: Write a pseudo code to perform the basic arithmetic operations.
Read n1, n2
Sum = n1 + n2
Diff = n1 – n2
Mult = n1 * n2
Quot = n1/n2
Print sum, diff, mult, quot
End
11
BCA103
MODULE-2
Introduction to C: Overview of C Program, Importance of C Program, Basic structure of a
C
program, Execution of C Program.
Constants, Variables & Data types: Character set, C token, Keywords & identifiers,
Constants,
Variables, datatypes, Declaration of variables, assigning values to variables, defining
symbolic
constants.
Operators and Expression: Arithmetic, Relational, logical, assignment, increment &
decrement, conditional, bit wise & special operators, evaluation of expressions, Precedence
of
arithmetic operators, type conversions in expressions, operator precedence & Associativity,
built in mathematical functions.
12
BCA103
Features of C language
• Simple, versatile, general purpose language
• It has rich set of Operators
• Program execution are fast and efficient
• Can easily manipulates with bits, bytes and addresses
• Varieties of data types are available
• Separate compilation of functions is possible and such functions can be
called by any C program
• Block- structured language
• Can be applied in System programming areas like operating systems,
compilers & Interpreters, Assembles, Text Editors, Print Spoolers, Network
Drivers, Modern Programs, Data Bases, Language Interpreters, Utilities etc.
Efficiency: C allows for direct memory manipulation and low-level access to system
resources. This results in highly efficient code execution.
Portability: C code can be easily ported to different platforms without major modifications,
thanks to its wide availability of compilers and libraries.
Speed: C is known for its fast execution speed, making it suitable for developing
performance-critical applications.
Control: C gives programmers fine-grained control over memory management and system
resources.
Compatibility: C code can be easily integrated with code written in other languages like
C++, Java, and Python.
Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used
to write complex programs. The C compiler combines the features of assembly languages and
high-level languages, which makes it best suited for writing system software as well as
business
packages. Some basic characteristics of C language that define the language andhave led
13
BCA103
Uses of C
C is a very simple language that is widely used by software professionals around the
globe. The uses of C language can be summarized as follows:
• C language is primarily used for system programming The portability, efficiency, the
ability to access specific hardware addresses, and low runtime demand on system
resources make it a good choice for implementing operating systems and embedded
system applications
• C has been so widely accepted by professionals that compilers, libraries, and
interpreters of other programming languages are often written in C.
• For portability and convenience reasons, C is sometimes used as an intermediate
language for implementation of other languages. Examples of compilers which use C
this way are BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and Vala.
• Basically, C was designed as a programming language and was not meant to be used as
a compiler target language. Therefore, although C can be used as an intermediate
14
BCA103
main(): As the name itself indicates it is the main function of every C program.
Execution of C program starts from main (). No C program is executed without
main() function. It should be written in lowercase letters and should not be
terminated by a semicolon. It calls other Library functions user defined functions.
There must be one and only one main() function in every C program.
Braces: Every C program uses a pair of curly braces ({,}0. The left
brace indicates beginning of main() function. On the other hand, the right brace
indicates end of the main() function. The braces can also be used to indicate the
beginning and end of user-defined functions and compound statements.
15
BCA103
Execution of C Program :
C program basically goes under 6 phases for execution:
1) edit 2) preprocess 3) compile 4) link 5) load 6) execute
Character Set
The character set is the fundamental raw-material for any language. Like
natural languages, computer languages will also have well defined character-set,
which is useful to build the programs.
The C language consists of two character sets namely – source character
set execution character set. Source character set is useful to construct the
statements in the source program. Execution character set is employed at the
time of execution of h program.
1. Source character set : This type of character set includes three types
of characters namely alphabets, Decimals and special symbols.
i. Alphabets : A to Z, a to z and Underscore( _ )
ii. Decimal digits : 0 to 9
iii. Special symbols: + - * / ^ % = & ! ( ) { } [ ] “ etc
2. Execution character set : This set of characters are also called as
non-graphic characters because these are invisible and cannot be printed or
displayed directly.
These characters will have effect only when the program being executed.
These characters are represented by a back slash (\) followed by a character.
C token: Tokens are some of the most important elements used in the C language for
creating a program. One can define tokens in C as the smallest individual elements in a
program that is meaningful to the functioning of a compiler.
16
BCA103
A token is the smallest unit used in a C program. Each and every punctuation and word that
you come across in a C program is token. A compiler breaks a C program into tokens and
then proceeds ahead to the next stages used in the compilation process.
Identifiers in C
Keywords in C
Operators in C
Strings in C
Special Characters in C
Constant in C
Reserve Words/Keywords
In C language , some words are reserved to do specific tasks intended for
them and are called Keywords or Reserve words. The list reserve words are
auto do goto
break double if
Identifiers
These are the names of the objects, whose values can be changed during
the program execution. Variables are named with description that transmits the
value it holds.
[A quantity of an item, which can be change its value during the execution
of program is called variable. It is also known as Identifier].
17
BCA103
Declaration of variables:
Syntax type Variable list
int i, j i, j are declared as integers
float salary salary is declared ad floating point variable
Char sex sex is declared as character variable
VARIABLES
A variable is defined as a meaningful name given to a data storage location incomputer
memory. When using a variable, we actually refer to address of the memory where the data is
stored. C language supports two basic kinds of variables numeric and character.
Declaring variables
Each variable to be used in the program must be declared. To declare a variable, specify
the data type of the variable followed by its name. The data type indicates the kind of values
that the variable will store.
Variable names should always be meaningful and must reflect the purpose of their
usage in the program. The memory location of the variable is of importance to the compiler
only and not to the programmer. Programmers must only be concerned with accessing data
through their symbolic names. In C, variable declaration always ends with a semicolon, for
example:
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
CONSTANTS
Constants are identifiers whose values do not change. While values of variables can be
changed at any time, values of constants can never be changed. Constants are used to define
fixed values like mathematical constant pie or the charge on an electron so that their value
does
not get changed in the program even by mistake.
A constant is an explicit data value specified by the programmer. The value of the
constant is known to the compiler at the compile time. C allows the programmer to specify
constants of integer type, floating point type, character type, and string type
18
BCA103
Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and
assign it a value. For example,
const float pi = 3.14;
The const keyword specifies that the value of pi cannot change. However, another way
to designate a constant is to use the pre-processor command define. Like other pre- processor
commands, define is preceded with a # symbol. Although #define statements canbe placed
anywhere in a C program, it is always recommended that these statements be placed at the
beginning of the program to make them easy to find and modify at a later stage. Look at the
example given below which defines the value of pi using define.
#define pi 3.14159
#define service_tax 0.12
19
BCA103
The built-in data types and their extensions is the subject of this chapter.
Derived data types such as arrays, structures, union and pointers and user defined
data types such as typedef and enum.
Basic Data Types
There are four basic data types in C language. They are Integer data,
character data, floating point data and double data types.
a. Character data: Any character of the ASCII character set can be
considered as a character data types and its maximum size can be 1 byte or 8
byte long. ‘Char’ is the keyword used to represent character data type in C.
Char - a single byte size, capable of holding one character.
b. Integer data: The keyword ‘int’ stands for the integer data type in C
and its size is either 16 or 32 bits. The integer data type can again be classified
as
1. Long int - long integer with more digits
2. Short int - short integer with fewer digits.
3. Unsigned int - Unsigned integer
4. Unsigned short int – Unsigned short integer
5. Unsigned long int – Unsigned long integer
As above, the qualifiers like short, long, signed or unsigned can be applied
to basic data types to derive new data types.
int - an Integer with the natural size of the host machine.
c. Floating point data: - The numbers which are stored in floating point
representation with mantissa and exponent are called floating point (real) numbers.
These numbers can be declared as ‘float’ in C.
float – Single – precision floating point number value.
d. Double data: - Double is a keyword in C to represent double precision
floating point numbers.
double - Double – precision floating point number value.
Assigning a value to a variable : means writing a value to the variable. This process
involves four entities:
20
BCA103
1. A data type
2. A variable
3. The simple assignment operator (=)
4. The value that will be copied to the variable
A typical example of assigning a value to a variable is the statement “int a = 4.” Here:
“int” is the data type
“a” is the variable
"=" is the operator
“4” is the value
Assigning a value is a process that defines the value of a variable or a constant.
A constant is a data item whose value remains constant throughout the execution of the
program.
Symbolic constants in C are identifiers that represent fixed values in a program. Unlike
variables, whose values can change during execution, symbolic constants have values that
remain constant throughout the program. They provide a way to give meaningful names to
fixed values, improving code readability and maintainability. Symbolic constants are defined
using the #define preprocessor directive or the const keyword. Let’s delve into each method
and explore symbolic constants in detail:
1. Arithmetic Operators
5. Increment & Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Comma Operator
1. The Arithmetic operators performs arithmetic operations. The Arithmetic
operators can operate on any built in data type. A list of arithmetic operators are
Operator Meaning
+
*
/
%
Addition
Subtraction
Multiplication
Division
Modulo division
2. Relational Operators
Relational Operators are used to compare arithmetic, logical and character
expressions. The Relational Operators compare their left hand side expression
with their right hand side expression. Then evaluates to an integer. If the Expression
is false it evaluate to “zero”(0) if the expression is true it evaluate to “one”
Operator Meaning
<
>
<=
>=
==
Less than
Greater than
Less than or Equal to
Greater than or Equal to
Equal to
!=
Not Equal to
The Relational Operators are represented in the following manner:
Expression-1
Relational Operator
Expression-2
The Expression-1 will be compared with Expression -2 and depending on
the relation the result will be either “TRUE” OR “FALSE”.
Examples :
Expression Evaluate to
(5 <= 10) ———————— 1
(-35 > 10) ———————— 0
22
BCA103
3. Logical Operators
A logical operator is used to evaluate logical and relational expressions.
The logical operators act upon operands that are themselves logical expressions.
There are three logical operators.
Operators Expression
&& Logical AND
|| Logical OR
! Logical NOT
23
BCA103
Multiple assignment
< identifier-1 > = < identifier-2 > = - - - = < identifier-n > = <exp>;
Example: a,b,c are integers; j is float variable
1. a = b = c = 3;
2. a = j = 5.6; then a = 5 and j value will be 5.6
C contains the following five additional assignment operators
1. += 2.-= 3. += 4. *= 5. /=
The assignment expression is: - Exp1 < Operator> Exp-2
Ex: I = 10 (assume that)
Expression Equivalent to Final Value of ‘I’
1. I + = 5 I = I + 5 15
2. I - = 5 I = I - 5 10
3. I * = 5 I = I * 5 50
4. I / = 5 I = I / 5 10
5. Increment & Decrement Operator
The increment/decrement operator act upon a Single operand and produce
a new value is also called as “unary operator”. The increment operator ++
adds 1 to the operand and the Decrement operator – subtracts 1 from the
24
BCA103
operand.
Syntax: < operator >< variable name >;
The ++ or – operator can be used in the two ways.
Example : ++ a; Pre-increment (or) a++ Post increment —a; Pre
Decrement (or) a— Post decrement
1. ++ a Immediately increments the value of a by 1.
2. a ++ The value of the a will be increment by 1 after it is utilized.
Example 1: Suppose a = 5 ;
Statements Output
printf ( “a value is %d”, a ); a value is 5
printf ( “a value is %d”, ++ a ); a value is 6
printf ( “a value is %d “, a) ; a value is 6
Example 2: Suppose : a = 5 ;
Statements Output
printf (“a value is %d “, a); a value is 5
printf (“a value is %d “, a++); a value is 5
printf (“a value is %d “,a); a value is 6
a and a- will be act on operand by decrement value like increment operator.
6. Conditional operator (or) Ternary operator (? :)
It is called ternary because it uses three expression. The ternary operator
acts like If- Else construction.
Syn :( <Exp –1 > ? <Exp-2> : <Exp-3> );
Expression-1 is evaluated first. If Exp-1 is true then Exp-2 is evaluated
other wise it evaluate Exp-3 will be evaluated.
Flow Chart :
Exp-1
Exp-2 Exp-3
Exit
Example:
1. a = 5 ; b = 3;
( a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is :a is larger
2. a = 3; b = 3;
(a> b ? printf (“a is larger”) : printf (“b is larger”));
Output is :b is larger
i) The logical Bitwise Operator :There are three logical bitwise operators.
Meaning Operator:
a) Bitwise AND &
25
BCA103
b) Bitwise OR |
c) Bitwise exclusive XOR ^
Suppose b1 and b2 represent the corresponding bits with in the first and
second operands, respectively.
B1 B2 B1 & B2 B1 | B2 B1 ^ B2
11110
10011
01011
00000
The operations are carried out independently on each pair of corresponding
bits within the operand thus the least significant bits (ie the right most bits) within
the two operands. Will be compared until all the bits have been compared. The
results of these comparisons are
A Bitwise AND expression will return a 1 if both bits have a value of 1.
Other wise, it will return a value of 0.
A Bitwise OR expression will return a 1 if one or more of the bits have a
value of 1. Otherwise, it will return a value of 0.
A Bitwise EXCLUSIVE OR expression will return a 1 if one of the bits
has a value of 1 and the other has a value of 0. Otherwise, if will return a value
of 0.
Example::Variable Value Binary Pattern
X 5 0101
Y 2 0010
X & Y 0 0000
X | Y 7 0111
X ^ Y 7 0111
ii) The Bitwise shift Operations: The two bitwise shift operators are
Shift left (<<) and Shift right (>>). Each operator requires two operands.
The first operand that represents the bit pattern to be shifted. The second is an
unsigned integer that indicates the number of displacements.
Example: c = a << 3;
The value in the integer a is shifted to the left by three bit position. The
result is assigned to the c.
A = 13; c= A<<3;
Left shit << c= 13 * 2 3 = 104;
Binary no 0000 0000 0000 1101
After left bit shift by 3 places ie,. a<<3
0000 0000 0110 1000
The right –bit – shift operator ( >> ) is also a binary operator.
Example: c = a >> 2 ;
The value of a is shifted to the right by 2 position
insert 0’s Right – shift >> drop off 0’s
0000 0000 0000 1101
26
BCA103
27
BCA103
The precedence and Associativity: the Precedence and Associativity of the operators
smartly is one of the important part of C programming.
Precedence talks about the priority among the different operators, which to consider
first. Like arithmetic operators have higher priority than assignment operators and so on.
When we have more than one operator in a single statement then this precedence
comes into the picture as the result may vary greatly.
Associativity comes into the picture when we have operators of the same precedence.
It doesn’t talk about which to pick first rather says the order of evaluation.
28
BCA103
Down the rows in the table shows the priorities decreasing.Under each row, all the operators
have the same priority, there comes associativity.It can be clearly seen, Unary, Ternary, and
Assignment Operators are evaluated right to left.
“x == 5 && x == 10 || x != 0 “
In the above statement relational operator(== and !=) is executed first then, logical
AND (&&), and at last logical (OR).
Special Operators
29
BCA103
The Comma operator can be used to link the related expressions together.
While(c<10,c--)
Syntax:
( type )
Explanation
Note that the use of a parenthesized type in a method declaration or definition is not
The reference operator noted by ampersand ("&"), is also a unary operator in c languages
that uses for assign address of the variables. It returns the pointer address of the variable.
30
BCA103
Syntax
data_type x;
data_type *pt;
pt = &x
With the help of mathematical functions we can easily solve a complex equation in our
program, for example, if we want to find the square root of a number, then we can use sqrt()
mathematical function to find the square root of a given number.
abs() Function
The abs() function returns the absolute value of an integer number. Here Absolute value
means number without negative sign. The absolute value of a number is always positive.
Syntax of abs() function
int abs(int num);
An abs() function takes input in integer data type and return the result in integer data type.
Program:
C program to input an integer and print its absolute value.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int n,x;
printf("Enter an integer number ");
scanf("%d",&n);
x=abs(n);
printf("Absolute value of %d is %d",n,x);
return 0;
}
Output
Enter an integer number -18
Absolute value of -18 is 18
sqrt() Function
The sqrt() function returns the square root of a positive number. Remember that square root
of a negative can not be calculated.
Syntax of sqrt() function
double sqrt(double num);
31
BCA103
A sqrt() function takes input in double data type and return the result in double data type.
You can also pass an integer data type number to the sqrt() function but the number will
implicitly convert into double data type as shown in the example below.
Example
C program to input an integer and print its square root.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int n;
double x;
printf("Enter an integer number ");
scanf("%d",&n);
x=sqrt(n);
printf("Square root of %d is %lf",n,x);
return 0;
}
Output
Enter an integer number 25
Square root of 25 is 5.000000
------------------------------------------------
ceil() Function
The ceil() function returns the nearest integer number greater than the number passed
as argument.
pow() Function
The pow() function is used to computes the power of a number.
Syntax of pow() function
double pow(double x, double y);
32
BCA103
Example
C program to input two integer numbers and print the power.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int a,b;
double c;
printf("Enter two integer numbers\n");
scanf("%d%d",&a,&b);
c=pow(a,b);
printf("Power = %lf",c);
return 0;
}
Output
Enter two integer numbers
5
2
Power = 25.000000
--------------------------------------------------------------
Questions:
1. Write the structure of C program
2. Define a variable and a constant in C.
3. What is an expression in C.
4. What are the operators used in C.
5. Mention the significance of main( ) function.
6. What are formatted and Unformatted Input-output statements.
7. Write the syntax of scanf() and printf() statements.
8. Write the syntax do loop control structure.
9. Write short notes on go to statement?
10. Mention difference between While loop and do…While loop.
11.What is Nested Loop?
12. Write the syntax of While statement.
13. Write the syntax of for… loop statement.
14. Write about ‘Switch” Statement.
15. Write the syntax of Simple if statement.
16. Write the syntax of if … else statement.
33
BCA103
Long answers:
Long Answer Type Questions - 6 Marks
01. Explain the basic structure of C program.
02. Write about data types used in C.
03. What is Constant? Explain various types of constants in C. (or)
04. Explain various types of Operators in C.
05. Explain formatted and un-formatted input and output statements in C
06. Explain various conditional control structures in C.
07. Explain various conditional looping statements in C.
08. Write the differences between Break and Continue
Note: Practice some more programs related using above statements
------------------------------*******---------------------------
34