Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

C Progm 1 and 2 Module Notes

The document outlines problem-solving techniques using C programming, covering algorithms, flowcharts, and pseudocode for various problems. It emphasizes the importance of precise problem identification, algorithm development, and implementation in programming. Additionally, it introduces the C programming language, its structure, data types, and operators, highlighting its applications in various fields.

Uploaded by

Shaheena Begum
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C Progm 1 and 2 Module Notes

The document outlines problem-solving techniques using C programming, covering algorithms, flowcharts, and pseudocode for various problems. It emphasizes the importance of precise problem identification, algorithm development, and implementation in programming. Additionally, it introduces the C programming language, its structure, data types, and operators, highlighting its applications in various fields.

Uploaded by

Shaheena Begum
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

BCA103

PROBLEM-SOLVING USING C PROGRAMMING


Course Code: BCA103

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

10. Count no. of odd, even and zeros in list of integers.


Step 1: Start
Step 2: [ Take Input ] Read: Number
Step 3: Check: If Number%2 == 0 Then
Print : N is an Even Number.
Else
Print : N is an Odd Number.
Step 4: Exit
Or

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.

Flowcharts: Symbols used in flow charts. Flowcharts for simple


problems mentioned in algorithms. Pseudocode.
Flowchart A flow chart is a step by step diagrammatic representation of the logic paths to
solve a given problem. Or A flowchart is visual or graphical representation of an algorithm.
The flowcharts are pictorial representation of the methods to be used to solve a given
problem and help a great deal to analyze the problem and plan its solution in a systematic and
orderly manner. A flowchart when translated in to a proper computer language, results in a
complete program.
Advantages of Flowcharts
1. The flowchart shows the logic of a problem displayed in pictorial fashion which felicitates
easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a compact means
of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts. These parts can
be connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at a later time.

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.

4. Draw a flowchart to find the factorial of given positive integer N

10
BCA103

5. Develop a flowchart to illustrate how to make a Land phone telephone call

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

Short Answer Type Questions - 2 Marks


1. Define Algorithm
2. What is Flowchart

11
BCA103

3. What is Pseudo code?


4. What are the symbols of Flowchart
5. Write an Algorithm for perimeter of Triangle
6. What are the basic steps involved In problem solving
Long Answer Type Questions - 6 Marks
1. Differentiate between Algorithm and Flowchart.
2. Write an algorithm to find greatest of given three numbers.
3. Write an algorithm to check whether given integer value is PRIME or
NOT.
4. Draw the flowchart to find roots of Quadratic equation ax2+ bx + c = 0
Note : Practice more related Algorithms and Flowcharts.
----------------------------------------------------------------------------------------------------------

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.

Introduction to C: Overview of C Program:


‘C’ is high level language and is the upgraded version of another language
(Basic Combined Program Language). C language was designed at Bell
laboratories in the early 1970’s by Dennis Ritchie. C being popular in the modern
computer world can be used in Mathematical Scientific, Engineering and
Commercial applications

12
BCA103

The most popular Operating system UNIX is written in C language. This


language also has the features of low level languages and hence called as “System
Programming Language”

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.

Importance of C programming language


C programming language offers several advantages over other programming languages,
including:

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

to its popularity as a programming language are listed below.


• C is a high-level programming language, which enables the programmer to concentrate
on the problem at hand and not worry about the machine code on which the program
would be run.
• Small size C has only 32 keywords. This makes it relatively easy to learn as compared
to other languages.
• C makes extensive use of function calls.
• C is well suited for structured programming. In this programming approach, C enables
users to think of a problem in terms of functions/modules where the collection of all the
modules makes up a complete program. This feature facilitates ease in program
debugging, testing, and maintenance.
• Unlike PASCAL it supports loose typing (as a character can be treated as an integer
and vice versa).
• Structured language as the code can be organized as a collection of one or more
functions

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

language it is not an ideal option.


• C is widely used to implement end-user applications.

Structure of a ‘C’ Program


The Complete structure of C program is
The basic components of a C program are:
• main()
• pair of braces { }
• declarations and statements
• user defined functions
Pre-processor Statements: These statements begin with # symbol. They
are called pre-processor directives. These statements direct the C pre-processor
to include header files and also symbolic constants in to C program. Some of
the pre-processor statements are
#include<stdio.h>: for the standard input/output functions
#include<test.h>: for file inclusion of header file Test.
#define NULL 0: for defining symbolic constant NULL = 0 etc.
Global Declarations: Variables or functions whose existence is known in
the main() function and other user defined functions are called global variables
(or functions) and their declarations is called global declaration. This declaration
should be made before main().

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.

Declarations: It is part of C program where all the variables, arrays,


functions etc., used in the C program are declared and may be initialized with
their basic data types.

Statements: These are instructions to the specific operations. They may

15
BCA103

be input-output statements, arithmetic statements, control statements and other


statements. They are also including comments.

User-defined functions: These are subprograms. Generally, a subprogram


is a function, and they contain a set of statements to perform a specific task.
These are written by the user; hence the name is user-defined functions. They
may be written before or after the main() function.

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

C is a compiled language. So once a C program is written, you must run it through a C


compiler that can create an executable file to be run by the computer. While the C program is
human-readable, the executable file, on the other hand, is a machine-readable file available in
an executable form.
The mechanical part of running a C program begins with one or more program source
files, and ends with an executable file, which can be run on a computer. The programming
process starts with creating a source file that consists of the statements of the program written
in C language. This source file usually contains ASCII characters and can be produced with a
text editor, such as Windows notepad, or in an Integrated Design Environment. The source
file is then processed by a special program called a compiler.

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.

Classification and Types of Tokens in C


Here are the categories in which we can divide the token in C language:

 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

case else int

char extern long

continue float register

default for return

short sezeof static

struct switch typedef

union unsigned void

while const entry

violate enum noalias

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].

Rules for naming a variable:-


 It can be of letters, digits and underscore( _ )
 First letter should be a letter or an underscore, but it should not be a
digit.
 Reserve words cannot be used as variable names.

17
BCA103

Example: basic, root, rate, roll-no etc are valid names.

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

Data Types in ‘C’

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.

Defining symbolic Constants:

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:

Using #define Directive:The #define directive is a preprocessor directive used to define


symbolic constants.

It has the following syntax:


#define constant_name value
Example:
#define PI 3.14159 #define MAX_SIZE 100
When the preprocessor encounters PI or MAX_SIZE in the code, it replaces them with their
respective values (3.14159 and 100) before the compilation process. This substitution is
performed throughout the entire code wherever the symbolic constants are used.

Operators and Expression:

An Operator is a symbol that operates on a certain data type. The data


items that operators act upon are called operands. Some operators require
two operands, some operators act upon only one operand. In C, operators can
be classified into various categories based on their utility and action.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operator
4. Assignment Operator
1. Arithmetic Operators
5. Increment & Decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Comma Operator
21
BCA103

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

(X < 10) ———————— 1 ( if value of x is less than 10)


0 Other wise
(a + b) = = ( c + d ) 1 (if sum of a and b is equal to sum of c, d)
0 Other wise

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

Logical And (&&): A compound Expression is true when two expression


when two expressions are true. The && is used in the following manner.
Exp1 && Exp2.
The result of a logical AND operation will be true only if both operands are
true.
The results of logical operators are:
Exp1 Op. Exp2 Result
True && True True

True && False False


False && False False
False && True False
Example: a = 5; b = 10; c = 15;
Exp1 Exp2 Result
1. ( a< b ) && ( b < c ) => True
2. ( a> b ) && ( b < c ) => False
3. ( a< b ) && ( b > c ) => False
4. ( a> b ) && ( b > c ) => False
Logical OR: A compound expression is false when all expression are
false otherwise the compound expression is true. The operator “||” is used as It
evaluates to true if either exp-1 or exp-2 is true. The truth table of “OR” is Exp1
|| Exp2
Exp1 Operator Exp2 Result:
True || True True
True || False True
False || True True
False || False False
Example: a = 5; b = 10; c = 15;
Exp1 Exp2 Result
1. ( a< b ) || ( b < c ) => True
2. ( a> b ) || ( b < c ) => True

23
BCA103

3. ( a< b ) || ( b > c ) => True


4. ( a> b ) || ( b > c ) => False
Logical NOT: The NOT ( ! ) operator takes single expression and
evaluates to true(1) if the expression is false (0) or it evaluates to false (0) if
expression is true (1). The general form of the expression.
! ( Relational Expression )
The truth table of NOT :
Operator. Exp1 Result
! True False
! False True
Example: a = 5; b = 10; c = 15
1. !( a< b ) False
2. !( a> b ) True
4. Assignment Operator
An assignment operator is used to assign a value to a variable. The most
commonly used assignment operator is =. The general format for assignment
operator is :
<Identifer> = < expression >
Where identifier represent a variable and expression represents a constant,
a variable or a Complex expression.
If the two operands in an assignment expression are of different data types,
then the value of the expression on the right will automatically be converted to
the type of the identifier on the left.
Example: Suppose that I is an Integer type Variable then
1. I = 3.3 3 ( Value of I )
2. I = 3.9 3 ( Value of I )
3. I = 5.74 5 ( Value of I )

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

7. Bit wise Operator


A bitwise operator operates on each bit of data. These bitwiseoperator
can be divided into three categories.
i. The logical bitwise operators.
ii. The shift operators
iii. The one’s complement operator.

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

After right shift by 2 places is a>>2


0000 0000 0000 0011 c=13>>2
c= 13/4=3
iii) Bit wise complement: The complement op.~ switches all the bits in a
binary pattern, that is all the 0’s becomes 1’s and all the 1’s becomes 0’s.
variable value Binary patter
x 23 0001 0111
~x 132 1110 1000
8. Comma Operator
A set of expressions separated by using commas is a valid construction in c
language.
Example :int i, j;
i= ( j = 3, j + 2 ) ;
The first expression is j = 3 and second is j + 2. These expressions are
evaluated from left to right. From the above example I = 5.
Size of operator: The operator size operator gives the size of the data
type or variable in terms of bytes occupied in the memory. This operator allows
a determination of the no of bytes allocated to various Data items
Example :int i; float x; double d; char c; OUTPUT
Printf (“integer : %d\n”, sizeof(i)); Integer : 2
Printf (“float : %d\n”, sizeof(i)); Float : 4
Printf (“double : %d\n”, sizeof(i)); double : 8
Printf (“char : %d\n”,sizeof(i)); character : 1

Expressions An expression can be defined as collection of data object and operators


that can be evaluated to lead a single new data object. A data object is a constant,
Uni variable or another data object.
Example : a + b
x + y + 6.0
3.14 * r * r
( a + b ) * ( a – b)
The above expressions are called as arithmetic expressions because
the data objects (constants and variables) are connected using arithmetic
operators.
Evaluation Procedure: The evaluation of arithmetic expressions is as per
the hierarchy rules governed by the C compiler. The precedence or hierarchy
rules for arithmetic expressions are
1. The expression is scanned from left to right.
2.While scanning the expression, the evaluation preference for the operators
are
*, /, % - evaluated first
+, - - evaluated next

27
BCA103

3. To overcome the above precedence rules, user has to make use of


parenthesis. If parenthesis is used, the expression/ expressions with in parenthesis
are evaluated first as per the above hierarchy

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.

For eg – 2 + 3 * 4 – 1 == 2+ (3 * 4) – 1 = 16 => This happens because precedence of


multiplication operator is higher than the other two.

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.

Here is the precedence and associativity in C table,

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

 The Comma Operator


 Type cast Operator
 Reference operator or Address Operater ("&")
 Dereference operator ("*") or Pointer Operater
 Double Pointer operator ("**")
 sizeof operator

29
BCA103

The Comma Operator

 The Comma operator can be used to link the related expressions together.

Example For Comma Operator

Comma Operator In for Loops


for(i=0,j=1;i>10:i++,j++)

Comma Operator In while Loops

While(c<10,c--)

Type cast Operator

Syntax:

( type )

Explanation

 converts a to the specified type.

 Note that the use of a parenthesized type in a method declaration or definition is not

an example of the use of the type cast operator.

Example For Type Cast Operator

float s= 12.5; int a;


a = (int) s;
now a value is 12.

Reference operator or Address Operater ("&")

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.

This is called "referencing" operater.

30
BCA103

Syntax

data_type x;
data_type *pt;
pt = &x

Built in mathematical functions:


In C language, Mathematical functions are predefined functions which accept values and
return the result. To use mathematical functions, we have to include math.h header file in our
program.

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.

Syntax of ceil() function


double ceil(double num);
A ceil() function takes input in double data type and return the result in double data
type. You can also pass a float data type number to the ceil() function but the number will
implicitly convert into double data type as shown in the example below.
fmod() Function
The fmod() function returns the remainder of the division of two double data type numbers.
Syntax of fmod() function
double fmod(double x, double y);
A fmod() function takes two input in double data type and return the result in double
data type. You can also pass float data type numbers to the fmod() function but the numbers
will implicitly convert into double data type as shown in the example below.

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

In mathematics the power is written as xy.


A pow() function takes two input (first as base value and second as power value) in
double data type and return the result in double data type. You can also pass an integer or
float data type numbers to the pow() function but the numbers will implicitly convert into
double data type as shown in the example below.

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

17. What is Preprocessor statement in C.


18. What are different types of errors occurred during the execution of C
program.
19. What is Variable and Constant in C? What are types of Constants in
C.
20. What are basic data types in C.
21. What is String Constant

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

You might also like