Академический Документы
Профессиональный Документы
Культура Документы
Algorithm
A step by step procedure for solving a particular problem is an Algorithm. To be an algorithm, a
set of rules must be unambiguous and have a clear stopping point. Algorithms can be expressed
in any language, from natural languages like English or French to programming languages like
FORTRAN, C.
Properties of algorithm
Donald Ervin Knuth has given a list of five properties for a,algorithm, these properties are:
1) Finiteness: An algorithm must always terminate after a finite number of steps. It means after
every step one reach closer to solution of the problem and after a finite number of steps
algorithm reaches to an end point.
2) Definiteness: Each step of an algorithm must be precisely defined. It is done by well thought
actions to be performed at each step of the algorithm. Also the actions are defined
unambiguously for each activity in the algorithm.
3) Input: Any operation you perform need some beginning value/quantities associated with
different activities in the operation. So the value/quantities are given to the algorithm before it
begins.
4) Output: One always expects output/result (expected value/quantities) in terms of output from
an algorithm. The result may be obtained at different stages of the algorithm. If some result is
from the intermediate stage of the operation then it is known as intermediate result and result
obtained at the end of algorithm is known as end result. The output is expected value/quantities
always have a specified relation to the inputs
5) Effectiveness: Algorithms to be developed/written using basic operations. Actually operations
should be basic, so that even they can in principle be done exactly and in a finite amount of time
by a person, by using paper and pencil only.
Example
Write an algorithm to read two numbers and find their sum.
Inputs to the algorithm:
First num1.
Second num2.
Expected output:
Sum of the two numbers.
Algorithm:
Problem Solving & Computer Programming TEAM MCA 2016
Step1: Start
Step2: Read\input the first num1.
Step3: Read\input the second num2.
Step4: Sum num1+num2 // calculation of sum
Step5: Print Sum
Step6: End
Flow Chart
A graphical representation of the sequence of operations in an information system or program is
called .Information system flowcharts show how data flows from source documents through the
computer to final distribution to users. Program flowcharts show the sequence of instructions in a
single program or subroutine. Different symbols are used to draw each type of flowchart.
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their interconnections
e.g. control flow from one action to the next
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown
as long as it does not exceed 3 symbols.
From the bottom of the page to the top of the same page.
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
Pseudocode
Pseudocode (rarely known as Program Design Language) is an informal high-level description of
the operating principle of a computer program or other algorithm.
It uses the structural conventions of a normal programming language, but is intended for human
reading rather than machine reading.
Pseudocode typically omits details that are essential for machine understanding of the algorithm,
such as variable declarations, system-specific code and some subroutines.
The purpose of using pseudocode is that it is easier for people to understand than conventional
programming language code, and that it is an efficient and environment-independent description
of the key principles of an algorithm.
Consists of natural language-like statements that precisely describe the steps of an algorithm or
program
Written at a level so that the desired programming code can be generated almost automatically
from each statement
Steps are numbered. Subordinate numbers and/or indentation are used for dependent statements
in selection and repetition structures
Pseudocode Advantages
Can be done easily on a word processor
Easily modified
Implements structured concepts well
Pseudocode Disadvantages
Its not visual
There is no accepted standard, so it varies widely from company to company
Compile After checking for syntactical correctness, converts the programming language source
files into machine readable instructions, where C variables are associated with memory
addresses, and C statements are turned into a series of machine language instructions. The
compiler can produces various forms of output, depending on the compiler options selected.
Linkage Editor Links compiler output with external modules requested by the compiled
program. C programs can use routines from C libraries or any object or archive file from the
IBM XL family of languages. C programs can also use modules produced by the current or
previous compilations. As well as linking the external modules, the linkage editor resolves
addresses within the object module.
Run and Test This stage can be both the final step in program development, or it can be an
intermediate point in the program design and implementation process. A program's design
commonly is further refined as a result of information gathered during testing
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 subroutines, block
structures, for and while loopsin contrast to using simple tests and jumps such as the goto
statement which could lead to "spaghetti code" which is difficult both to follow and to maintain.
Structured programming frequently employs a top-down design model, in which developers map
out the overall program structure into separate subsections. A defined function or set of similar
functions is coded in a separate module or submodule, which means that code can be loaded into
memory more efficiently and that modules can be reused in other programs. After a module has
been tested individually, it is then integrated with other modules into the overall program
structure.
Control structures
Problem Solving & Computer Programming TEAM MCA 2016
Following the structured program theorem, all programs are seen as composed of control
structures:
Selection : one or a number of statements is executed depending on the state of the program.
This is usually expressed with keywords such as if..then..else..endif.
Iteration : a statement or block is executed until the program reaches a certain state, or
operations have been applied to every element of a collection. This is usually expressed with
keywords such as while, repeat, for or do..until. Often it is recommended that each loop should
only have one entry point (and in the original structural programming, also only one exit point,
and a few languages enforce this).
Recursion : a statement is executed by repeatedly calling itself until termination conditions are
met. While similar in practice to iterative loops, recursive loops may be more computationally
efficient, and are implemented differently as a cascading stack.
Subroutines
Subroutines; callable units such as procedures, functions, methods, or subprograms are used to
allow a sequence to be referred to by a single statement.
Blocks
Blocks are used to enable groups of statements to be treated as if they were one statement.
Block-structured languages have a syntax for enclosing structures in some formal way, such as
an if-statement bracketed by if..fi as in ALGOL 68, or a code section bracketed by
BEGIN..END, as in PL/I, whitespace indentation as in Python - or the curly braces {...} of C and
many later languages.
Program design
A program design is a process to conceptualize the program requirements into program
implementation or execution. Program design takes the user requirements as challenges and tries
to find optimum solution. While the program is being conceptualized, a plan is chalked out to
find the best possible design for implementing the intended solution.
Program design The activity of progressing from a specification of some required program to a
description of the program itself. Most phase models of the software life cycle recognize
program design as one of the phases. The input to this phase is a specification of what the
program is required to do. During the phase the design decisions are made as to how the program
Problem Solving & Computer Programming TEAM MCA 2016
will meet these requirements, and the output of the phase is a description of the program in some
form that provides a suitable basis for subsequent implementation.
Frequently the design phase is divided into two subphases, one of coarse architectural design and
one of detailed design. The architectural design produces a description of the program at a gross
level; it is normally given in terms of the major components of the program and their
interrelationships, the main algorithms that these components employ, and the major data
structures. The detailed design then refines the architectural design to the stage where actual
implementation can begin.
Program design language (PDL) A language, used for expressing program designs, that is similar
to a conventional high-level programming language but emphasizes structure and intention rather
than the ability to execute programs expressed in the language. PDLs are often employed in
conjunction with structured programming. When not executable they are termed
pseudolanguages.
Typically the formal syntax of a PDL would cover data definition and overall program structure.
Facilities in the latter area would include the basic control-flow constructs sequential,
conditional, and iterative plus those for the definition and invocation of subroutines. These
facilities would be used to define the overall framework of the program, but individual actions
within the framework would be expressed using pseudolanguage natural English mixed with a
more formal semantically rich language. Correspondingly, the PDL facilities for data definition
may be expected to be richer than those of a typical programming language, encompassing a
broader range of basic types and a more extensive set of data-structuring facilities. A wide
variety of PDLs have been defined; normal practice is to select one that is well-matched to the
target programming language.
Top-down and bottom-up are both strategies of information processing and knowledge
ordering, used in a variety of fields including software, humanistic and scientific theories (see
systemics), and management and organization. In practice, they can be seen as a style of
thinking, teaching, or leadership.
Top-down design starts with a generalized model of system and keeps on defining the more
specific part of it. When all components are composed the whole system comes into existence.
Top-down design is more suitable when the software solution needs to be designed from scratch
and specific details are unknown.
A top-down approach (also known as stepwise design and in some cases used as a synonym of
decomposition) is essentially the breaking down of a system to gain insight into its compositional
sub-systems in a reverse engineering fashion. In a top-down approach an overview of the system
Problem Solving & Computer Programming TEAM MCA 2016
is formulated, specifying, but not detailing, any first-level subsystems. Each subsystem is then
refined in yet greater detail, sometimes in many additional subsystem levels, until the entire
specification is reduced to base elements. A top-down model is often specified with the
assistance of "black boxes", which make it easier to manipulate. However, black boxes may fail
to elucidate elementary mechanisms or be detailed enough to realistically validate the model.
Top down approach starts with the big picture. It breaks down from there into smaller segments.
Bottom-up strategy is more suitable when a system needs to be created from some existing
system, where the basic primitives can be used in the newer system.
A bottom-up approach is the piecing together of systems to give rise to more complex systems,
thus making the original systems sub-systems of the emergent system. Bottom-up processing is a
type of information processing based on incoming data from the environment to form a
perception. From a Cognitive Psychology perspective, information enters the eyes in one
direction (sensory input, or the "bottom"), and is then turned into an image by the brain that can
be interpreted and recognized as a perception (output that is "built up" from processing to final
cognition). In a bottom-up approach the individual base elements of the system are first specified
in great detail. These elements are then linked together to form larger subsystems, which then in
turn are linked, sometimes in many levels, until a complete top-level system is formed. This
strategy often resembles a "seed" model, by which the beginnings are small but eventually grow
in complexity and completeness. However, "organic strategies" may result in a tangle of
elements and subsystems, developed in isolation and subject to local optimization as opposed to
meeting a global purpose.
Both, top-down and bottom-up approaches are not practical individually. Instead, a good
combination of both is used.
Object oriented design works around the entities and their characteristics instead of functions
involved in the software system. This design strategies focuses on entities and its characteristics.
The whole concept of software solution revolves around the engaged entities.
Structured Design
Modular Programming
Modular programming is the process of subdividing a computer program into separate sub-
programs.
A module is a separate software component. It can often be used in a variety of applications and
functions with other components of the system. Similar functions are grouped in the same unit of
programming code and separate functions are developed as separate units of code so that the
code can be reused by other applications.
Modules in modular programming enforce logical boundaries between components and improve
maintainability. They are incorporated through interfaces. They are designed in such a way as to
minimize dependencies between different modules. Teams can develop modules separately and
do not require knowledge of all modules in the system.
Each and every modular application has a version number associated with it. This provides
developers flexibility in module maintenance. If any changes have to be applied to a module,
only the affected subroutines have to be changed. This makes the program easier to read and
understand.
A set of statements is in turn generally structured as a block, which in addition to grouping also
defines a lexical scope.A statement that is used to control the flow of execution in a program is
called control structure. It combines instruction into logical unit. Logical unit has one entry point
and one exit point.
Introduction to C programming:
C is an offspring of Basic Combined Programming Language (BCPL) called B, developed in
the 1960s at Cambridge University. B language was modified by Dennis Ritchie and was
implemented at Bell Laboratories in 1972.The new language was named as C. Since it was
developed along with UNIX operating system, it is strongly associated with UNIX. It can run
under various operating systems including MSDOS.
C language is a middle level Language. It combines the features of high level language and
functionality like assembly language. It reduces the gap between high level language and low-
level language that is why it is known as middle level language. It is well suited for writing both
application software and system software.
Importance of C:
1. It is robust language.
2. Rich set of built-in functions and operators are available.
3. Easy to create complex programs.
4. Suitable to write both application software as well as system software because it combines the
features of assembly language with high level language features.
5. It is highly portable. Because C programs written for one computer it can be run on another
with little or no modification.
6. It is well suited for structured programming. This makes the programmer to think in terms of
modules or blocks. This in turn makes program debugging, testing and maintaining easier.
7. It can extend itself.
8. Programs written in C are efficient and faster. This is due to the variety of data type and
powerful operators.
9. It is many times faster than BASIC. For example a program to increment a variable from 0 to
15,000 takes 1 second in C where as more than 50 seconds in the BASIC interpreter.
10.There are 32 keywords and the strength lies in the built-in functions available for developing
the programs.
Structure of C:
Documentation section
Link section
Definition section
Global declaration section
main( ) function section
Problem Solving & Computer Programming TEAM MCA 2016
{
declaration part
executable part
}
Subprogram section
function 1
function 2
function 3 User Defined functions
.
.
function n
A sample C Program:
// This is a program to show the structure of C Single line comment
#include<stdio.h>
#include<conio.h> Link section
#define PI 3.14 Definition section
int a;
main()
{
Problem Solving & Computer Programming TEAM MCA 2016
Character Set In C
A character denotes any alphabet, digit or special symbol used to represent information. The
followings shows the valid alphabets, numbers and special symbols allowed in C
1. Letters - upper case AZ,lower case a..z
2. Digits - all decimal digits 0..9
3. Special characters -
. - period $ - dollar sign
, - comma : - colon
; - semi colon - apostrophe
- quotation mark # - number sign
+ - plus ( - left parenthesis
- - minus ) - right parenthesis
* - asterisk { - left brace
} - right brace [ - left bracket ]-right bracket
4. white spaces -
a) blank space
b) horizontal tab
c) carriage return
d) new line
e) form feed etc.
Trigraph characters:
Many non-English keyboards do not support all the characters mentioned above. So C introduces
the concept of trigraph characters that provide a way to enter characters not available on some
keyboards. Each trigraph character consists of 3 characters (two question marks followed by any
other character)
Example:
Trigraph character Translation
??= number sign (#)
?? caret (^)
Problem Solving & Computer Programming TEAM MCA 2016
C Tokens
The smallest individual units in C are called tokens. C has 6 types of tokens as shown below
C Tokens
Keywords
Identifiers
Constants
Strings
Special symbols
Operators
Keywords:
Keywords have a constant and fixed meaning and the meanings cannot be changed. The
keywords serve as building blocks for program statements. All keywords must be written in
lowercase.
Example: goto, while , if, else, register, return etc.,
Identifiers:
Identifiers refer to the name of variables, functions and arrays. They are user-defined names
consisting of a sequence of letters, digits with the letter as the first character. Underscore can be
used to link two words.
Example: a, stu_no, marks_1, names etc.,
Constants:
Problem Solving & Computer Programming TEAM MCA 2016
Constants refer fixed values that do not change during the execution of program. Constants
consist of the following categories.
Integer constants:
It refers to a sequence of digits.
Types of integer constants
1. Decimal integer constants (set of digits from 0 to 9 with an optional + or sign)
2. Octal integer constants (consists of digits from 0 to 7 with a leading 0).
3. Hexa decimal integer constants (consists of the digits 0 to 9 and the letters a to f
preceded by 0X or 0x)
Real constants:
Problem Solving & Computer Programming TEAM MCA 2016
Backslash character constants are used in output functions. Each backslash character constants
contains two characters to represent a single character. These combinations are called escape
sequences.
Examples:
1) \n- new line
2) \t-horizontal tab
3) \v-vertical tab
4) \0-null
Data types:
A programming language is proposed to help programmer to process certain kinds of data and to
provide useful output. A program usually contains different types of data types (integer, float,
character etc.) and need to store the values being used in the program. C language is rich of data
types. A C programmer has to employ proper data type as per his requirement.
C has different data types for different types of data and can be broadly classified as :
1. Primary data types
2. Secondary data types
Primary data types consist following data types.
Problem Solving & Computer Programming TEAM MCA 2016
Integer types:
Integers are whole numbers with a range of values, range of values are machine dependent.
Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to
+32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for
number. To control the range of numbers and storage space,C has three classes of integer storage
namely short int, int and long int. All three data types have signed and unsigned forms. A short
int requires half the amount of storage than normal integer. Unlike signed integer, unsigned
integers are always positive and use all the bits for the magnitude of the number. Therefore the
range of an unsigned integer will be from 0 to 65535.
The long integers are used to declare a longer range of values and it occupies 4 bytes of storage
space.Syntax: int <variable name>; like int num1;short int num2;long int num3;Example: 5, 6,
100, 2500.
Character Type:
Character type variable can hold a single character. As there are singed and unsigned int (either
short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but
having different ranges. Unsigned characters have values between 0 and 255, signed characters
have values from 128 to 127.Syntax: char <variable name>; likechar ch = a;Example: a, b, g,
S, j.
Problem Solving & Computer Programming TEAM MCA 2016
Variables:
A variable is a data name that may be used to hold a data value. A variable may take different
values at different times during the program execution.
Rules for forming a variable:
1. The starting character should be a letter. The first character may be followed by a sequence of
letters or digits.
2. The number of characters differs from compiler to compiler.
3. Upper and lower case are significant. Example: TOTAL is not same as total or Total.
4. The variable should not be a keyword.
5. White space is not allowed.
6. Special characters except _(underscore) symbol are not allowed.
Examples:
Valid Invalid
1. john 1868(The first character should be a letter )
2. value (area)(Special characters are not allowed)
3. tot_amt 27th(The first character should be a letter)
4. a1 %(Special characters are not allowed)
Declaration of variables:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Syntax:
v1,v2,v3.vn- variables
Example:
Problem Solving & Computer Programming TEAM MCA 2016
1. int count;
2. int a,b;
3. float area,volume;
4. char array;
5. double a1;
data_type variable_name;
or
where data_type is any valid c data type and variable_name is any valid identifier.
Eg : int a;
Initialization of Variable
C variables declared can be initialized with the help of assignment operator =.
Syntax
data_type variable_name=constant/literal/expression;
or
variable_name=constant/literal/expression;
Eg : int a=10;
Assignment statements:
Values can be assigned to variables using the assignment operator = as follows
variable _name =constant;
Examples:
a=5;
b=10;
P=s=z=0 ; (multiple assignment statement)
It is possible to assign the values during declaration time as follows:
Example:
data-type v1,v2,v3.vn;
data type variable_name = constant or expression or variable ;
int final=100;
Problem Solving & Computer Programming TEAM MCA 2016
char yes=x;
double balance=39.98;
Array
Array is called as a homogenous data structure. Arrays a kind of data structure that can store a
fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of
the same type.
Declaring Arrays
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type.
Initializing Arrays
Expression :
1. In programming, an expression is any legal combination of symbols that represents a
value.
2. C Programming Provides its own rules of Expression, whether it is legal expression or
illegal expression. For example, in the C language x+5 is a legal expression.
3. Every expression consists of at least one operand and can have one or more operators.
4. Operands are values and Operators are symbols that represent particular actions.
Problem Solving & Computer Programming TEAM MCA 2016
C Programming code gets compiled firstly before execution. In the different phases of compiler,
c programming expression is checked for its validity.
Expressions Validity
a+b Expression is valid since it contain + operator which is binary operator
++a+b Invalid Expression
In order to solve any expression we should have knowledge of C Programming Operators and
their priorities.
Types of Expression :
In Programming, different verities of expressions are given to the compiler. Expressions can be
classified on the basis of Position of Operators in an expression
Examples of Expression :
Now we will be looking into some of the C Programming Expressions, Expression can be
created by combining the operators and operands
Each of the expression results into the some resultant output value. Consider few expressions in
below table
Expression Examples,Explanation
n1 + n2,This is an expression which is going to add two numbers and we can assign the result of
addition to another variable.
x = y,This is an expression which assigns the value of right hand side operand to left side
variable
v = u + a * t,We are multiplying two numbers and result is added to u and total result is
assigned to v
x <= y,This expression will return Boolean value because comparison operator will give us
Problem Solving & Computer Programming TEAM MCA 2016
output either true or false ++j,This is expression having pre increment operator\, it is used to
increment the value of j before using it in expression.
L-Value of Expression
L-Value of Expression :
#include<stdio.h>
int main()
{
int num;
num = 5;
return(0);
}
R-Value of Expression ?
int main()
{
int num;
num = 5;
return(0);
}
Statements
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input
Labeled Statements
A statement can be preceded by a label. Three types of labels exist in C.
Problem Solving & Computer Programming TEAM MCA 2016
A simple identifier followed by a colon (:) is a label. Usually, this label is the target of a goto
statement.
Compound Statements
A compound statement is the way C groups multiple statements into a single statement.
It consists of multiple statements and declarations within braces (i.e. { and })
Expression Statements
An expression statement consists of an optional expression followed by a semicolon (;).
If the expression is present, the statement may have a value. If no expression is present, the
statement is often called the null statement.
Selection Statements
Three types of selection statements exist in C:
if ( expression ) statement
In this type of if-statement, the sub-statement will only be executed iff the expression is non-
zero.
if ( expression ) statement else statement
Iteration Statements
C has three kinds of iteration statements. The first is a while-statement with the form
while ( expression ) statement
The substatement of a while runs repeatedly as long as the control expression evaluates to non-
zero at the beginning of each iteration. If the control expression evaluates to zero the first time
through, the substatement may not run at all.
The second is a do-while statement of the form
do statement while ( expression ) ;
This is similar to a while loop, except that the controlling expression is evaluated at the end of
the loop instead of the beginning and consequently the sub-statement must execute at least once.
The third type of iteration statement is the for-statement. In ANSI C 1989, it has the form
for ( expressionopt ; expressionopt ; expressionopt ) statement
Jump Statements
C has four types of jump statements. The first, the goto statement, is used sparingly and has the
form
goto identifier ;
This statement transfers control flow to the statement labeled within the given identifier.
The second, the break statement, with the form
break ;
is used within iteration statements and switch statements to pass control flow to the statement
following the while, do-while, for, or switch.
The third, the continue statement, with the form
continue ;
is used within the substatement of interation statements to transfer control flow to the place just
before the end of the substatement. In for statements the iteration expression will then be
executed before the controlling expression is evaluated.
Problem Solving & Computer Programming TEAM MCA 2016
The fourth type of jump statement is the return statement with the form
return expressionopt ;
This statement returns from the function. If the function return type is void, the function may not
return a value; otherwise, the expression represents the value to be returned.
Simple statements
assertion: assert(ptr != NULL);
assignment: A:= A + 5
goto: goto next;
return: return 5;
call: CLEARSCREEN()
Compound statements
block: begin integer NUMBER; WRITE('Number? '); READLN(NUMBER); A:=
A*NUMBER end
do-loop: do { computation(&i); } while (i < 10);
for-loop: for A:=1 to 10 do WRITELN(A) end
if-statement: if A > 3 then WRITELN(A) else WRITELN("NOT YET"); end
switch-statement: switch (c) { case 'a': alert(); break; case 'q': quit(); break; }
while-loop: while NOT EOF DO begin READLN end
with-statement: with open(filename) as f: use(f)
Symbolic constant
A symbolic constant is name that substitute for a sequence of character that cannot
be changed. The character may represent a numeric constant, a character constant, or a string.
When the program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence. They are usually defined at the beginning of the program. The
symbolic constants may then appear later in the program in place of the numeric constants,
character constants, etc., that the symbolic constants represent.
#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the program
is preprocessed, all occurrences of the symbolic constant PI are replaced with the replacement
text 3.141593.
Problem Solving & Computer Programming TEAM MCA 2016
Note that the preprocessor statements begin with a #symbol, and are not end with a semicolon.
By convention, preprocessor constants are written in UPPERCASE.
Example: 1
#include<stdio.h>
#include<conio.h>
#define TRUE 1
#define PI 3.141593
void main()
{
float a;
float b;
float c;
float d=PI;
clrscr();
if(TRUE)
{
a=100;
b=a*10;
c=b-a;
}
printf("\na=%f\nb=%f\nc=%f\nPI=%f",a,b,c,d);
getch();
}
Some of the "commands" in C are not really "commands" at all but are functions. For example,
we have been using printf and scanf to do input and output, and we have used rand to generate
random numbers - all three are functions.
There are a great many standard functions that are included with C compilers and while these are
not really part of the language, in the sense that you can re-write them if you really want to, most
C programmers think of them as fixtures and fittings. A list of the most common libraries and a
brief description of the most useful functions they contain follows:
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
operations. They are used to manipulate data.
Types:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Arithmetic operators:
Arithmetic operators are used to perform arithmetic operations like addition, subtraction,
multiplication , division and to find the remainder in division. The corresponding symbols are
+(addition or unary plus), - (subtraction or unary minus), *, /,%(modulo division). C does not
have an operator for exponentiation.
Relational operators:
It is used to relate any two or more quantities.
Operator Meaning
< is less than
> is greater than
>= is greater than or equal to
<= is lesser than or equal to
== is equal to
!= is not equal to
Logical operators:
It is used to combine two or more relational expressions.
Operator Meaning
&& logical and
|| logical or
! logical not
Assignment operators:
= is used to assign value to a variable. In addition to this C has a set of shorthand assignment
operators.
Syntax:
v op =exp;
a=a+1 a+=1
a=a-1 a-=1
a=a*1 a*=1
a=a/1 a/=1
a=a%b a%=b
Advantages:
1. No need to repeat the operator again in the right hand side.
2. The statement is more concise and clear.
3. The statement is more efficient.
4. It is easy to read.
Conditional operator:
A ternary operator pair ?: is used to construct conditional expressions
Syntax:
exp1?exp2:exp3
Example :
x=(a>b)?a:b;
In the above the condition is evaluated first. If true then a will be assigned to x or else b will be
assigned to x. The above syntax is equivalent to if else statement.
Bitwise operators:
Manipulates the data at bit level.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise EXCLUSIVE OR
Problem Solving & Computer Programming TEAM MCA 2016
Special operators:
Sizeof() - to determine the size of the variable
Unary Operator
A unary operator, is an operator that takes a single operand in an expression or a statement. The
unary operators are +, -,!, ~, ++, -- and the cast operator.
Unary Plus Operator (+): The result of an operation on a numeric type is the value of the
operand itself. This operator has been predefined for all numeric types.
Unary Minus Operator (-): This operator can be used to negate numbers of the integer,
floating-point and decimal type.
Logical Complement (negation) Operator (!): This operator can be used only with
operands of Boole type.
Bitwise Complement (negation) Operator (~): This operator can be used with integer,
unit, long and ulong operand types. The result of the operation is a bitwise complement
(inverse of the binary representation) of the operand.
Prefix Increment (++) and Decrement (--) Operator: The operand can be a variable,
property access, or an indexer access. With an increment operator, the result of the
operation for operands of integer type would be the value incremented by 1. With a
Problem Solving & Computer Programming TEAM MCA 2016
decrement operator, the result would be the value decremented by 1 from the operand.
The increment/decrement operator can also be used with postfix notation
Cast Operator: Used to build cast expressions for conversion to a given type. This
operator is represented by the symbol, "T," where T is the type to which the operand or
the result of the expression must be converted
Expressions:
Combination of both operand and operator.
Types:
1. Arithmetic
2. Relational
3. Logical
Arithmetic expression:
Operand combined with arithmetic operators are called as arithmetic expressions.
Examples:
a+b
c-d
Types:
1. Integer arithmetic
2. Real arithmetic
3. Mixed arithmetic
Integer arithmetic:
Arithmetic operator combined with integer operands.
Example:
a + b; where a and b are of type integer.
Real arithmetic:
Arithmetic operator combined with real operands.
Example:
a + b where a and b are of type real.
variable = expression;
o The expression is evaluated first and the results are placed on the variable on the
left.
o All variables must be assigned values before they are used in an expression.
o Spaces before and after an operator is optional. It is used to enhance the readability
Problem Solving & Computer Programming TEAM MCA 2016
of the statement
Casting a value:
If we need to force the type conversion explicitly then it is called as casting.
Example:
ratio=(float) number1/number2;
Where number 1 and number2 are of type integer type, ratio is of type float.
Example:
x = ( int ) 7.5 = 7 (truncation)
a = ( int ) 21.3 / ( int ) 4.5
= 21 / 4
=5
Problem Solving & Computer Programming TEAM MCA 2016
The control string contains the format of data being received. The ampersand
symbol (&) before the variable name is an operator that specifies the variable names
address.
Example :
scanf(%d,&number);
%d - represents integer value
%f - float number
%c - character
%lf - double
%u - unsigned int
Reading a character:
The simplest of all input/output is reading a character from the standard input
unit(keyboard). Reading a single character is done through the getchar function.
Syntax:
variable_name = getchar ();
Getch Function
The getch = get character. This function is used to get a single character input from the user
during execution of program. It also force to wait the output to stay on screen until any key
pressed from keyboard.
Problem Solving & Computer Programming TEAM MCA 2016
Syntax:
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
char m;
printf("Enter character:");
m=getch();
printf("The character you Entered=%c",m );
getch();
}
Output:
Enter character:
The character u Entered=a
Getche Function
The getche() = get character echo. It is also used to get a single character from the keyboard
during the program execution. When this function is executed, the character entered by the user
is displayed on the screen.
Problem Solving & Computer Programming TEAM MCA 2016
Output
enter any character:x
the character u entered=x
#include <stdio.h>
int main(void)
{
int ch1;
char ch2;
#include <stdio.h>
#define MAX_LENGTH 80
int main(void)
{
char string[MAX_LENGTH];
Eg:
bytes_read = getline(&string, &bytes_number, stdin);
For precise output formatting, every printf() call contains a format control string that describes
the output format.
Problem Solving & Computer Programming TEAM MCA 2016
Conversion specifiers.
Flags.
Field widths.
Precisions.
Literal characters.
Together with percent sign (%), these, form conversion specifications. Function printf()
can perform the following formatting capabilities:
Aligning a column of numbers with decimal points appearing one above the other.
Displaying all types of data with fixed-size field widths and precisions.
Printing Integers
Integer is a whole number, such as 880 or 456, that contains no decimal point.
program example.
Problem Solving & Computer Programming TEAM MCA 2016
#include <stdio.h>
int main()
printf("-------------------------------------\n");
printf("%d\n", 455);
printf("%d\n", +455);
printf("%d\n", -455);
printf("%hd\n", 32000);
printf("%ld\n", 2000000000L);
printf("%o\n", 455);
printf("%u\n", 455);
printf("%u\n", -455);
printf("%x\n", 455);
printf("%X\n", 455);
return 0;
}
Problem Solving & Computer Programming TEAM MCA 2016
Output:
program example.
#include <stdio.h>
void main()
Output:
#include <stdio.h>
Problem Solving & Computer Programming TEAM MCA 2016
int main()
printf("---------------------------------\n");
printf("---------------------------------\n\n");
printf("\nLateral string\n");
printf("%s\n", string);
printf("%s\n", stringPtr);
return 0;
Output:
Problem Solving & Computer Programming TEAM MCA 2016
#include <stdio.h>
int main()
{
Problem Solving & Computer Programming TEAM MCA 2016
printf("---------------------------------------\n\n");
printf("%4d\n", 1);
printf("%4d\n", 12);
printf("%4d\n", 123);
printf("%4d\n", 1234);
printf("%4d\n\n", 12345);
printf("%4d\n", -1);
printf("%4d\n", -12);
printf("%4d\n", -123);
printf("%4d\n", -1234);
printf("%4d\n", -12345);
return 0;
Output:
Problem Solving & Computer Programming TEAM MCA 2016
int main()
{
printf("Right justifying and left justifying values.\n");
printf(" Compare the output with the source code.\n");
printf("--------------------------------------------\n\n");
printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23);
printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23);
return 0;
}
Problem Solving & Computer Programming TEAM MCA 2016
Output:
#include <stdio.h>
int main(void)
{
int char1 = 65; /*Typically, the numeric value of A*/
char char2 = 'A';
#include <stdio.h>
#define MAX_LENGTH 80
int main(void)
{
char string[MAX_LENGTH];
The process of getting something from the computer is known as output. The output is mostly
showed on monitor. The term standard output refers to the output showed on the monitor. The
result of a program is the output of the program. C language provides many functions to show
output to the user. Some important functions for output are as follows:
printf();
puts();
The functions used for input and output are stored in the header file stdio.h. If a program uses for
input or output function, it is necessary to include this header file in the program.
Reading, processing and writing of data are the three essential functions of a computer
program.The programs take some data as input and display the processed data and provide the
information or results.
C has built in input/output operations through functions like scanf and printf. These functions are
included in the standard library stdio.h (standard input output header file) and are included
through the statement as follows
#include<stdio.h>
It tells the compiler to search for the file called stdio.h and place its contents at the required place
in the program.
There are many manipulations that can be done on the character obtained. These
character functions are in the header file ctype.h. Some of the functions available are
Example:
//program to check the character type
#include<stdio.h>
#include<ctype.h>
void main()
{
char c;
printf(Enter a character\n);
scanf(%c,c);
if(isdigit (c)) //checks if the character is a digit or not
printf( the character entered is a digit);
if(isalpha (c))
printf(the character entered is an alphabet);
if(ispunct (c))
printf(the character entered is a punctuation character);
}
Sample output:
Enter a character
1
The character entered is a digit
Problem Solving & Computer Programming TEAM MCA 2016
Similarly to write a single character on the screen the function putchar is used.
Syntax:
putchar(variable_name);
Example:
//program to change the lower case letters to uppercase and vice versa
#include<stdio.h>
#include<ctype.h>
void main()
{
char c;
scanf(%c,&c);
if(isupper( c ) )
putchar(tolower( c ));
else
putchar(toupper( c ));
}
Sample Output:
A
a
Interactive programming
Interactive programming is the procedure of writing parts of a program while it is already active.
This focuses on the program text as the main interface for a running process, rather than an
interactive application, where the program is designed in development cycles and used thereafter
(usually by a so-called "user", in distinction to the "developer"). Consequently, here, the activity
of writing a program becomes part of the program itself. It thus forms a specific instance of
interactive computation as an extreme opposite to batch processing, where neither writing the
program nor its use happens in an interactive way. The principle of rapid feedback in Extreme
Programming is radicalized and becomes more explicit
Interactive programming techniques are especially useful in cases where no clear specification of
the problem that is to be solved can be given in advance. In such situations (which are not
unusual in research), the formal language provides the necessary environment for the
development of an appropriate question or problem formulation.
Interactive programming has also been used in applications that need to be rewritten without
stopping them, a feature which the computer language Smalltalk is famous for. Generally,
dynamic programming languages provide the environment for such an interaction, so that
typically prototyping and iterative and incremental development is done while other parts of the
program are running.
Problem Solving & Computer Programming TEAM MCA 2016
Using dynamic programming languages for sound and graphics, interactive programming is also
used as an improvisational performance style live coding, mainly in algorithmic music and
video..