Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 1 PPA

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

BCA-102 : Programming Principle & Algorithm (PPA)

Unit – I and II
History, Structures of ‘C’ Programming, Function as building blocks. Character set, C Tokens, Keywords,
Identifiers, Variables, Types of operators, Precedence and Associativity, Expression, Statement and types of
statements. Constant, Data Types, Comments.Introduction to Programming Concepts: Software, Classification of
Software, Modular Programming, Structured Programming, Algorithms and Flowcharts with examples. Overview of C
Language: History of C, Character set, C tokens, Identifiers, Keywords, Data types, Variables, Constants, Symbolic
Constants , Operators in C, Hierarchy of Operators, Expressions, Type Conversions and Library Functions.
Console based I/O and related built in I/O function.

Software :
Software is defined as a collection of programs, documentation and operating procedures. ∙ The
Institute of Electrical and Electronic Engineers (IEEE) defines software as a ‘collection of computer
programs, procedures, rules and associated documentation and data.’

Software Characteristics
 Functionality: Refers to the degree of performance of the software against its intended purpose.
 Reliability: Refers to the ability of the software to provide desired functionality under the given
conditions.
 Usability: Refers to the extent to which the software can be used with ease.
 Efficiency: Refers to the ability of the software to use system resources in the most effective and
efficient manner.
 Maintainability: Refers to the ease with which the modifications can be made in a software system
to extend its functionality, improve its performance, or correct errors.
 Portability: Refers to the ease with which software developers can transfer software from one
platform to another, without (or with minimum) changes.
 Robustness refers to the degree to which the software can keep on functioning in spite of being
provided with invalid data
 Integrity refers to the degree to which unauthorized access to the software or data can be
prevented.
Classification of Software :
 System software: This class of software manages and controls the internal operations of a
computer system. For example, an operating system, Compiler, Assembler, Interpreter is a system
software
 Real-time software: This class of software observes, analyzes, and controls real world events as
they occur. An example of real-time software is the software used for weather forecasting that
collects and processes parameters like temperature and humidity from the external environment
to forecast the weather.
 Business software: This class of software is widely used in areas where management and control of
financial activities is of utmost importance. For example, Tally, Excel, Power BI is a business
software
 Engineering and scientific software: This class of software has emerged as a powerful tool in the
research and development of next generation technology. Example : Applications such as the study
of celestial bodies, under-surface activities, and programming of an orbital path for space shuttles
are heavily dependent on engineering and scientific software. MATLAB, AUTOCAD, ORCAD etc

 Artificial intelligence (AI) software: This class of software is used where the problem-solving
technique is non-algorithmic in nature Ex : pattern recognition, and game-playing techniques

 Web-based software: This class of software acts as an interface between the user and the Internet.
The software incorporates executable instructions written in special scripting languages such as CGI
or ASP, HTML, XML etc.
Modular programming :
 Modular programming also called as stepwise refinement or top-down design is a programming
approach that breaks down program functions into modules.
 Modular programming is a solution to the problem of very large programs that are difficult to debug
and maintain. Libraries of components built from separately compiled modules can be combined
into a whole by using a programming tool called linker.

Advantages Of Modular Programming


 Faster development.
 Several programmers can work on individual programs at the same time.
 Easy debugging and maintenance.
 Easy to understand as each module works independently to another
module.
 Less code has to be written.
 The scoping of variables can easily be controlled.
 Modules can be re-used, eliminating the need to retype the code many
times.
Structured programming :
 Structured programming is a programming paradigm aimed at improving the clarity, quality, and
development time of a computer program by making extensive use of the structured control flow
constructs of selection (if/then/else) and repetition (while and for), block structures, and subroutines.

 Advantages of structured programming are:


 It encourages top-down implementation, which improves both readability and
maintainability of code.
 It promotes code reuse, since even internal modules can be extracted and made
independent, residents in libraries,...
 It's widely agreed that development time and code quality are improved through structured
programming.
Algorithm:
 The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means a
procedure or a technique
 An algorithm is a sequence of steps to solve a particular problem
 Algorithm is an ordered set of unambiguous steps that produces a result and terminates in a
finite time
 Software Engineer commonly uses an algorithm for planning and solving the problems.

Characteristics :
 Input: An algorithm may or may not require input
 Output: Each algorithm is expected to produce at least one result
 Definiteness: Each instruction must be clear and unambiguous.
 Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after
finite number of steps

Advantages of algorithm
 It is a step-wise representation of a solution to a given problem, which makes it easy to understand.
o An algorithm uses a definite procedure.
 It is not dependent on any programming language, so it is easy to understand for anyone even
without programming knowledge.
 Every step in an algorithm has its own logical sequence so it is easy to debug.
HOW TO WRITE ALGORITHMS
 Step 1 : Define your algorithms input
 Step 2 : Define the variables
 Step 3 : Outline the algorithm's operations
 Step 4 : Output the results of your algorithm's operations

Example : Write an Algorithm to find Area & Perimeter of Triangle


S= (A + B + C)/ 2.0
AREA = SQRT(S x (S-A) x (S-B) x(S-C))
PERIMETER = A+B+C

Step 1 : Start
Step 2 : Input A,B,C
Step 3: Calculate S = (A+B+C)/2.0
Step 4 : Calculate Area = SQRT(S x (S-A) x (S-B) x(S-C))
Step 5 : Calculate Perimeter = A+B+C
Step 6 : Output Area, Perimeter
Step 7: Stop
Flowchart :
Flowchart is diagrammatic /Graphical representation of sequence of steps to solve a problem o
Flowchart is often considered as a blueprint of a design used for solving a specific problem. o The
first design of flowchart goes back to 1945 which was designed by John Von Neumann. o Unlike an
algorithm, Flowchart uses different symbols to design a solution to a problem. It is another commonly
used programming tool
Advantages of flowchart:
 Flowchart is an excellent way of communicating the logic of a program.
 Easy and efficient to analyze problem using flowchart.
 During program development cycle, the flowchart plays the role of a blueprint, which makes
program development process easier.
 The flowchart makes program or system maintenance easier.
 It is easy to convert the flowchart into any programming language code.
History of C :
 C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
 It was developed to overcome the problems of previous languages such as B, BCPL, etc. o Initially,
C language was developed to be used in UNIX operating system. It inherits many features of
previous languages such as B and BCPL.
 The programming languages that were developed before C language.

Features of C language :

C is the widely used language. It provides many features

 Simple
 Machine Independent or Portable  Fast Speed
 Mid-level Mid level programming language  Pointers
 Structured programming language  Recursion
 Rich Library  Extensible
 Memory Management
o Simple : C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
o Machine Independent or Portable : Unlike assembly language, c programs can be executed on
different machines with some machine specific changes. Therefore, C is a machine
independent language.
o Mid-level programming language :Although, C is intended to do low-level programming. It is
used to develop system applications such as kernel, driver, etc. It also supports the features of
a high level language. That is why it is known as mid-level language.
o Structured programming language : C is a structured programming language in the sense that
we can break the program into parts using functions. So, it is easy to understand and modify.
Functions also provide code reusability.
o Rich Library : C provides a lot of inbuilt functions that make the development fast.
o Memory Management : It supports the feature of dynamic memory allocation. In C language,
we can free the allocated memory at any time by calling the free() function.
o Fast Speed : The compilation and execution time of C language is fast since there are lesser
inbuilt functions and hence the lesser overhead.
o Pointers : C provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array, etc.
o Recursion : In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
o Extensible : C language is extensible because it can easily adopt new features.
Character set :
 The C character set consists of upper and lowercase alphabets, digits, special characters and white
spaces.
 C language supports a total of 256 characters.
 C language supports a total of 256 characters.

C tokens:
 Every smallest individual unit of a c program is called token.
 Every instruction in a c program is a collection of tokens.
 Tokens are used to construct c programs and they are said to the basic building blocks of a c program.
In a c program tokens may contain the following...
 Keywords
 Identifiers
 Operators
 Special Symbols
 Constants
 Strings
 Data values
Keywords :
 Keywords are also known as reserved words in C programming language.
 There are 32 keywords. All the 32 keywords have pre-defined meaning which is already known to the
compiler.

Properties of Keywords

1. All the keywords in C programming language are defined as lowercase letters so they must be used only in
lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays, pointers, etc...
4. Every keyword in C programming language represents something or specifies some kind of action to be
performed by the compiler.

The following table specifies all the 32 keywords with their meaning...
Identifiers:
 An identifier is a collection of characters which acts as the name of variable, function, array, pointer,
structure, etc...
 In other words, an identifier can be defined as the user-defined name to identify an entity uniquely in
the c programming language
Rules for Creating Identifiers
1. An identifier can contain letters (UPPERCASE and lowercase), numerics & underscore symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an underscore.
3. We should not use any special symbols in between the identifier even whitespace. However, the only
underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first 31 characters only.
6. An identifier must be unique in its scope.

Example of valid identifiers : total, sum, average, _m _, sum_1, etc.


Example of invalid identifiers :
1. 2sum  invalid because (starts with a numerical digit)
2. int  invalid because (reserved word)
3. char  invalid because (reserved word)
4. m+n  invalid because (special character, i.e., '+')

Data types :
 Data types in the c programming language are used to specify what kind of value can be stored in a
variable.
 In the c programming language, data types are classified as follows...
 Primary data types (Basic data types OR Predefined data types)
 Derived data types (Secondary data types OR User-defined data types)
 Enumeration data types
 Void data type
Primary data types
The primary data types in the C programming language are the basic data types. All the primary data types are
already defined in the system. Primary data types are also called as Built-In data types. The following are the primary
data types in c programming language...

1. Integer data type


2. Floating Point data type
3. Double data type
4. Character data type

Integer Data type


 The integer data type is a set of whole numbers.
 "int" to represent integer data type in c
 The integer data type is used with different type modifiers like short, long, signed and unsigned
Floating Point data types
 Floating-point data types are a set of numbers with the decimal value
 The floating-point data type has two variants...
 float
 double
 The float value contains 6 decimal places whereas double value contains 15 or 19 decimal places.

Character data type


 The character data type is a set of characters enclosed in single quotations.
void data type
 The void data type means nothing or no value.
 Generally, the void is used to specify a function which does not return any value.
 We also use the void data type to specify empty parameters of a function.
Enumerated data type
 An enumerated data type is a user-defined data type that consists of integer constants and each integer
constant is given a name.
 The keyword "enum" is used to define the enumerated data type.
Derived data types
 Derived data types are user-defined data types.
 The derived data types are also called as user-defined data types or secondary data types.
 In the c programming language, the derived data types are created using the following concepts...
 Arrays
 Structures
 Unions
 Enumeration
Variables :
 Variables in a c programming language are the named memory locations where the user can store
different values of the same datatype during the program execution.
 Every variable in c programming language must be declared in the declaration section before it is used.
 Every variable must have a datatype that determines the range and type of values be stored
The following are the rules to specify a variable name...
1. Variable name should not start with a digit.
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters of the variable
name.
Declaration of Variable :
datatype variableName;
Example : int regno;
char name[20];
float salary;

Constants :
 A constant is a named memory location which holds only one value throughout the program
execution.
 In a c programming language, constants can be created using two concepts...
 Using the 'const' keyword
 Using '#define' pre-processor

 Different types of constants are

 Integer constants
 An integer constant can be a
decimal integer or octal integer
or hexadecimal integer.
Floating Point constants

 A floating-point constant must contain both integer and decimal parts.


 Some times it may also contain the exponent part.
 When a floating-point constant is represented in exponent form, the value must be suffixed with 'e' or 'E'.
Example : The floating-point value 3.14 is represented as 3E-14 in exponent form.

Character Constants

 A character constant is a symbol enclosed in single quotation. A character constant has a maximum length of
one character.
Example : ‘A’ , ‘2’, ‘+’, ‘c’, ‘*’
In the C programming language, there are some predefined character constants called escape sequences. Every
escape sequence has its own special functionality and every escape sequence is prefixed with '\' symbol. These
escape sequences are used in output function called 'printf()'.

String Constants

 A string constant is a collection of characters, digits, special symbols and escape sequences that are enclosed
in double quotations.
Example : “ SIMSBCA”

Symbolic Constants
 A symbolic constant can be defined as a constant that is represented by a name (symbol) in a program.
 Whenever the constant’s value is needed in the program, the name of the constant is used in the same
way as the name of a variable is used to access its value.

There are two methods in C for defining a symbolic constant:

 Using the 'const' keyword

const datatype constantName = value ;


Example : const int x = 10 ;
 Using '#define' pre-processor

#define CONSTANTNAME value


Example : # define PI 3.142
Example :
/* A program to compute the area and circumference of a circle */
#include <stdio.h>
#define PI 3.142;

int main()
{
float area, circumference, radius;

printf("Enter the radius of the circle:");


scanf("%f", &radius);

area = PI * radius * radius;


circumference = 2 * PI * radius;

printf("\n The area = %f circumference = %f", area, circumference);


return 0;
}

Operators in C :
 An operator is a symbol used to perform arithmetic and logical operations in a program.
 C programming language supports a rich set of operators that are classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Arithmetic Operators (+, -, *, /, %)


Relational Operators (<, >, <=, >=, ==, !=)

Logical Operators (&&, ||, !)

Increment & Decrement Operators (++ & --)


Assignment Operators (=, +=, -=, *=, /=, %=)

Bitwise Operators (&, |, ^, ~, >>, <<)


 The bitwise operators are used to perform bit-level operations in the c programming language.
Program to illustrate Bit wise operator
#include <stdio.h>

main() {

unsigned int a = 60; /* 60 = 0011 1100 */


unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c );

c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );

c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - Value of c is %d\n", c );
}
Tracing :

2|60
2 |30 - 0
2 | 15- 0
2 |7  1
2 |3  1
2 |1  1

A= 60 : 0011 1100 A= 60 : 0011 1100


B= 13 : 0000 1101 B= 13 : 0000 1101
A&B 0 0 0 0 1 1 0 0 A|B 0 0 1 1 1 1 0 1

A= 60 : 0011 1100
B= 13 : 0000 1101
A^B 0 0 1 1 0 0 0 1

~A (60+1) 11000011

A<<2 1 1 0 0 0 0 1 1  1111 0000

A>>2 1 1 0 0 0 0 1 1  0000 1111


Conditional Operator (?:)

 The conditional operator is also called a ternary operator because it requires three operands.
 In this operator, first we verify a condition, then we perform one operation out of the two operations
based on the condition result.
 If the condition is TRUE the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example : (a>b)?a:b;

Program to display largest of three numbers using conditional operators :

#include <stdio.h>
int main()
{
int a,b,c,c,big1,big2,largest;
printf("\n Enter a ,b,c,d");
scanf("%d %d %d %d",&a,&b,&c,&d);
big1 = ( a > b) ? a : b;
big2 = (c > d) ? c : d;
largest = (big1 > big2) ? big1 : big2;
printf("\n largest = %d",largest);
return 0;
}
Special Operators (sizeof, pointer, comma, dot, etc.)
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.

sizeof(variableName);
Example : sizeof(A); ⇒ the result is 2 if A is an integer
Pointer operator (*)
This operator is used to define pointer variables in c programming language.
Comma operator (,)
This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.
Dot operator (.)
This operator is used to access members of structure or union.

C Operator Precedence and Associativity :


 Operator precedence is used to determine the order of operators evaluated in an
expression. In c programming language every operator has precedence (priority).
 Operator associativity is used to determine the order of operators with equal precedence
evaluated in an expression.
 In the c programming language, when an expression contains multiple operators with equal
precedence, we use associativity to determine the order of evaluation of those operators.
C Expression Evaluation : An expression is evaluated based on the precedence and associativity of the operators in
that expression.

Type Conversions :
 Converting one datatype into another is known as type casting or, type-conversion.
 For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'.
You can convert the values from one type to another explicitly using the cast operator as follows
(type_name) expression
 Two types of Conversion :
o Implicit Conversion
o Explicit conversion
Implicit conversion : If conversion is done automatically by the compiler itself, then such conversion is called implicit
type conversion
Example :
int a = 10; - 2 bytes
float b = 3.142;  4 bytes
int c;  2 bytes
float d;  4 bytes

d=a; = d = 10.0 -- Implicit conversion -> promotion


c=b;  c= 3  implicit conversion ->demotion

lower type converted to higher type  is called promotion


higher type truncated and converted into lower type  is called demotion
Explicit conversion : Forcing data type to convert from one type to another is called Explicit
conversion.
Example : float a;
int b = (int)a + 1; (a is forced to convert from floating point to integer)

Library Functions
o The C Standard Library is a set of C built-in functions, constants and header files
like <stdio.h>, <stdlib.h>, <math.h>, etc. This library will work as a reference
manual for C programmers.

“math.h” header file supports all the mathematical related functions in C language.
Formatted and Unformatted Input/Output functions in C with Examples
Formatted I/O Functions
Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user.
These types of I/O functions can help to display the output to the user in different formats using the format
specifiers. These I/O supports all data types like int, float, char, and many more.
Why they are called formatted I/O?
These functions are called formatted I/O functions because we can use format specifiers in these functions an d
hence, we can format these functions according to our needs.

List of some format specifiers-

S NO. Format Specifier Type Description

1 %d int/signed int used for I/O signed integer value

2 %c char Used for I/O character value

3 %f float Used for I/O decimal floating-point value

4 %s string Used for I/O string/group of characters

5 %ld long int Used for I/O long signed integer value

6 %u unsigned int Used for I/O unsigned integer value

7 %i unsigned int used for the I/O integer value

8 %lf double Used for I/O fractional or floating data

9 %n prints prints nothing

The following formatted I/O functions will be discussed in this section-


1. printf()
2. scanf()
3. sprintf()
4. sscanf()

printf():
printf() function is used in a C program to display any value like float, integer, character, string, etc on the console
screen. It is a pre-defined function that is already declared in the stdio.h(header file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
scanf():
scanf() function is used in the C program for reading or taking any value from the keyboard by the user, these
values can be of any data type like integer, float, character, string, and many more. This function is declared in
stdio.h(header file), that’s why it is also a pre-defined function. In scanf() function we use &(address-of operator)
which is used to store the variable value on the memory location of that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);

sprintf():
sprintf stands for “string print”. This function is similar to printf() function but this function prints the string into a
character array instead of printing it on the console screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);

sscanf():
sscanf stands for “string scanf”. This function is similar to scanf() function but this function reads data from the
string or character array instead of the console screen.
Syntax:
sscanf(array_name, “format specifier”, &variable_name);

Unformatted Input/Output functions


Unformatted I/O functions are used only for character data type or character array/string and cannot be used for any
other datatype. These functions are used to read single input from the user at the console and it allows to display
the value at the console.
Why they are called unformatted I/O?
These functions are called unformatted I/O functions because we cannot use format specifiers in these functions
and hence, cannot format these functions according to our needs.
The following unformatted I/O functions will be discussed in this section-
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()

getch():
getch() function reads a single character from the keyboard by the user but doesn’t display that character on the
console screen and immediately returned without pressing enter key. This function is declared in conio.h(header
file). getch() is also used for hold the screen.
Syntax:
getch();
or
variable-name = getch();

getche():
getche() function reads a single character from the keyboard by the user and displays it on the console screen and
immediately returns without pressing the enter key. This function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
getchar():
The getchar() function is used to read only a first single character from the keyboard whether multiple characters is
typed by the user and this function reads one character at one time until and unless the enter key is pressed. This
function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();

putchar():
The putchar() function is used to display a single character at a time by passing that character directly to it or by
passing a variable that has already stored a character. This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);

gets():
gets() function reads a group of characters or strings from the keyboard by the user and these characters get stored
in a character array. This function allows us to write space-separated texts or strings. This function is declared in
stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type variable of any length
gets(str);

puts():
In C programming puts() function is used to display a group of characters or strings which is already stored in a
character array. This function is declared in stdio.h(header file).
Syntax:
puts(identifier_name );

Formatted I/O vs Unformatted I/O


S
Formatted I/O functions Unformatted I/O functions
No.

These functions allow us to take input or display These functions do not allow to take input or
1
output in the user’s desired format. display output in user desired format.

2 These functions support format specifiers. These functions do not support format specifiers.

3 These are used for storing data more user friendly These functions are not more user-friendly.

Here, we can use only character and string data


4 Here, we can use all data types.
types.

printf(), scanf, sprintf() and sscanf() are examples of getch(), getche(), gets() and puts(), are some
5
these functions. examples of these functions.

You might also like