Вы находитесь на странице: 1из 49

Problem Solving & Computer Programming TEAM MCA 2016

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.

Find the area of a Circle of radius r.


Inputs to the algorithm:
Radius r of the Circle.
Expected output:
Area of the Circle
Algorithm:
Step1: Read\input the Radius r of the Circle
Step2: Area PI*r*r // calculation of area
Step3: Print Area

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

General Rules for flowcharting


1. All boxes of the flowchart are connected with Arrows. (Not lines)

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.

5. Connectors are used to connect breaks in the flowchart. Examples are:

From one page to another page.

From the bottom of the page to the top of the same page.

An upward flow of more then 3 symbols

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.

8. All flowcharts end with a terminal or a contentious loop.


Problem Solving & Computer Programming TEAM MCA 2016

Example : Find the area of a circle of radius r.

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.

A program in pseudocode is not an executable program

Consists of natural language-like statements that precisely describe the steps of an algorithm or
program

Statements describe actions

Focuses on the logic of the algorithm or program


Problem Solving & Computer Programming TEAM MCA 2016

Avoids language-specific elements

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

Pseudo Code Example

1.Declare an integer variable called n


2.Declare an integer variable sum
3.Declare an integer variable f1
4.Declare an integer variable f2
5.set sum to 0
6.set f1 and f2 to 1
7.set n to 50
8.repeat n times
a.sum = f1 + f2
b.f2 = f1
c.f1 = sum
d.print sum
9.end loop

Program Development Steps


Define the problem
Outline the solution
Problem Solving & Computer Programming TEAM MCA 2016

Develop the outline into an algorithm


Test the algorithm for correctness
Code the algorithm into a programming language
Run the program on computer
Testing the program to find out the errors if any and rectify it.
Document and maintain the program

Program Development Steps in C


Design and Code Involves designing a program to meet a specified requirement, and creating the
programming language text files that will comprise the program source.

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:

Sequence : ordered statements or subroutines executed in sequence.

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

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

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

Structured design is a conceptualization of problem into several well-organized elements of


solution. It is basically concerned with the solution design. Benefit of structured design is, it
gives better understanding of how the problem is being solved. Structured design also makes it
simpler for designer to concentrate on the problem more accurately.

Function Oriented Design


Problem Solving & Computer Programming TEAM MCA 2016

In function-oriented design, the system is comprised of many smaller sub-systems known as


functions. These functions are capable of performing significant task in the system. The system
is considered as top view of all functions. Function oriented design inherits some properties of
structured design where divide and conquer methodology is used.

Modular Programming
Modular programming is the process of subdividing a computer program into separate sub-
programs.

Modular programming is a software design technique that emphasizes separating the


functionality of a program into independent, interchangeable modules, such that each contains
everything necessary to execute only one aspect of the desired functionality.

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.

The benefits of using modular programming include:

Less code has to be written.


A single procedure can be developed for reuse, eliminating the need to retype the code
many times.
Programs can be designed more easily because a small team deals with only a small part
of the entire code.
Modular programming allows many programmers to collaborate on the same application.
The code is stored across multiple files.
Code is short, simple and easy to understand.
Errors can easily be identified, as they are localized to a subroutine or function.
The same code can be used in many applications.
The scoping of variables can easily be controlled.
Problem Solving & Computer Programming TEAM MCA 2016

Structuring Control flow


In computer science, control flow (or alternatively, flow of control) is the order in which
individual statements, instructions or function calls of an imperative program are executed or
evaluated. The emphasis on explicit control flow distinguishes an imperative programming
language from a declarative programming language.
Types of control flow
1. Sequence structure (straight line paths)
2. Selection structure (one or many branches)
3. Loop structure (repetition of a set of activities)
4. Function call

1. Sequence: Statements are executed in a specified order. No statement is skipped and no


statement is executed more than once.
2. Selection: It selects a statement to execute on the basis of condition. Statement is executed
when the condition is true and ignored when it is false e.g if, if else, switch structures.
3. Repetition:In this structure the statements are executed more than one time. It is also known
as iteration or loop e.g while loop, for loop do-while loops etc.
4. Function call:It is used to invite or call a piece of code or statement. In this case control
jumps from main program to that piece of code and then returns back to main program.

Within an imperative programming language, a control flow statement is a statement whose


execution results in a choice being made as to which of two or more paths should be followed.
For non-strict functional languages, functions and language constructs exist to achieve the same
result, but they are not necessarily called control flow statements.
The kinds of control flow statements supported by different languages vary, but can be
categorized by their effect:

continuation at a different statement (unconditional branch or jump),


executing a set of statements only if some condition is met (choice - i.e., conditional
branch),
executing a set of statements zero or more times, until some condition is met (i.e., loop -
the same as conditional branch),
executing a set of distant statements, after which the flow of control usually returns
(subroutines, coroutines, and continuations),
Problem Solving & Computer Programming TEAM MCA 2016

stopping the program, preventing any further execution (unconditional halt).

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

Basic Structure of a C program


A C program can be viewed as a group of building blocks or functions. Each function
or subroutine includes one or more statements to perform a task. C generally has the
following structure
1. Documentation section This section contains comment lines indicating the name of the
program, the author, the purpose of the program and other details that the
programmer would like to have.
2. Link section This link section instructs to the compiler to link functions from the system
library. To perform the task it uses the statement #include <header file.h>
3. Definition section Definition section is used to deal with symbolic constants. The following
statement does definition - #define symbolic_name constant_name.
4. Global declaration section This section is used to declare global variables a variable that
is used in more than one function.
5. main() function main() is a special function that tells the compiler the start of the program.
Program execution begins at this line. Therefore every program must have only one main
function. Otherwise it will be difficult for the compiler to identify the start of the program. The
empty parenthesis indicate that the function has no arguments. The { denotes the logical
beginning of the block and the } denotes the logical end of the block. All other statements
coming between the { and } constitute the function body.
Function body in turn is divided into
The declaration part which declares all the variables used in program execution
The executable part that contains at least one executable statement.
6. Sub program section This section contains all the user-defined functions.

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

scanf(%d,&a); main section


area();
}
area()
{
float area; User defined functions
area = PI*a*a;
printf(Area is %f\n,area);
}
Programming Style:
C is a free-form language. The compiler does not care where on the line we begin typing.
But the statement has to be delimited with a semicolon.
Programs must be written using lowercase letters.
Uppercase letters can be used for symbolic constants.
Braces are used for grouping statements together and they mark the begin and end of the
functions.

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

??- tilde (~)

Escape sequences and control characters:


Certain ASCII characters are unprintable. These characters perform special
functions like back spacing, returning to a new line, tab etc. the back slash character (\) is called
as the escape sequence character because the character immediately occurring after it takes a
special meaning. Such characters are usually specified within a single quote (character constant)
or double quotes (within a control string).
\a - audible bell
\b - back space
\f - form feed
\n - new line
\r - carriage return
\t - horizontal tab
\v - vertical tab
\ - single quote
\ - double quote
\? - question mark
\\ - back slash
\0 - null

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)

Decimal integer constants examples:-


Valid examples Invalid examples
1. 123 1. 153 43
2. 76565 2. 20,000
3. 0 3. $667
4. +736 4. 9-898

Octal integer constants examples:


Valid examples Invalid examples
1. 034 1.0X2
2. 07 2.0283
3. 07655 3.0987

Hexa decimal integer constants examples:


Valid examples Invalid examples
1. 0x2 1.0xnmjk
2. 0x87665 2.0x1286m
3. 0xabc 3.08972
4. 0x53647 4.0khjdi

Real constants:
Problem Solving & Computer Programming TEAM MCA 2016

The numbers with fractional part is called real or floating-point constants.


Example:
1. 54.98
2. 25.75
Notations used to represent real constants are:
1. Decimal notation
2. Scientific notation
Decimal notation:
1. Whole number followed by a decimal point and fractional part.
2. It is possible to omit the digits before the decimal point.
3. It is possible to omit the digits after the decimal point.
Example:
1) 215.
2) .125
Scientific (exponential) notation:
1.The mantissa is either a real number in decimal notation or an integer.
2. The exponent is an integer with an optional plus or minus sign.
3. The letter e separating mantissa and exponent part.
4. The exponent can be written in either lower or upper case.
Single Character Constant
A character enclosed by single quote marks is called single character constants.
Examples:
1) a
2) #
3) 2
4)
Points to remember:
1. The character constant 2 is not same as the number 2.
2. Blank space enclosed by single quote is also called as character constant.
3. Character constants have integer values known as ASCII values.
Example :
1) Printf (%d,a); - output will be 97 which is the ASCII value of a.
2) Printf(%c,98); - output will be b.
String Constants:
A sequence of characters enclosed by double quotes. The character may be any letter, digits,
special characters and blank space.
Example:
1. Welcome to c programming
2. 2001
3. Well done
4. 34+23
5. d

Backslash character 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.

Floating Point Types:


The float data type is used to store fractional numbers (real numbers) with 6 digits of precision.
Floating point numbers are denoted by the keyword float. When the accuracy of the floating
point number is insufficient, we can use the double to define the number. The double is same as
float but with longer precision and takes double space (8 bytes) than float. To extend the
precision further we can use long double which occupies 10 bytes of memory space. Syntax:
float <variable name>; likefloat num1;double
num2;long double num3;Example: 9.125, 3.1254.

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

Secondary Data Types


Array in C programming An array in C language is a collection of similar data-type, means an
array can hold value of a particular data type for which it has been declared. Arrays can be
created from any of the C data-types int,...
Pointers in C Programming In this tutorial I am going to discuss what pointer is and how to use
them in our C program. Many C programming learner thinks that pointer is one of the difficult
topic in C language but its not...
Structure in C Programming We used variable in our C program to store value but one variable
can store only single piece information (an integer can hold only one integer value) and to store
similar type of values we had to declare...
User defined type declaration C language supports a feature where user can define an identifier
that characterizes an existing data type. This user defined data type identifier can later be used to
declare variables. In short its purpose is to redefine the name of an existing data type.Syntax:
typedef <type><identifier>; liketypedef int number;Now we can use number in lieu of int to
declare integer variable.For example: int x1 or number x1 both statements declaring an
integer variable. We have just changed the default keyword int to declare integer variable to
number

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;

Declaration of variable in c can be done using following syntax:

data_type variable_name;

or

data_type variable1, variable2,,variablen;

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.

Eg: double balance[10];

Initializing Arrays

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

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

Valid C Programming Expression :

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

Priority and 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

Type Explanation Example


Infix Expression in which Operator is in between Operands a+b
Prefix Expression in which Operator is written before Operands +ab
Postfix Expression in which Operator is written after Operands ab+

These expressions are solved using the stack.

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

1. L-Value stands for left value


2. L-Value of Expressions refer to a memory locations
3. In any assignment statement L-Value of Expression must be a container(i.e. must have
ability to hold the data)
4. Variable is the only container in C programming thus L Value must be any Variable.
5. L Value Cannot be Constant,Function or any of the available data type in C

L-Value of Expression :

Example of L-Value of Expression :

#include<stdio.h>

int main()
{
int num;
num = 5;
return(0);
}

R-Value of Expression ?

1. R Value stands for Right value of the expression.


Problem Solving & Computer Programming TEAM MCA 2016

2. In any Assignment statement R-Value of Expression must be anything which is capable


of returning Constant Expression or Constant Value.
3. R Value Can be anything of following

Examples of R-Value of Expression


Variable Constant
Function Macro
Enum Constant Any other data type

Diagram Showing R value :

Example of R-Value of Expression


#include<stdio.h>

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.

For example a C program consists of the following symbolic constant definitions.


#define PI 3.141593
#define TRUE 1
#define FALSE 0

#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();
}

The Standard Library Functions


Library functions in C language are inbuilt functions which are grouped together and
placed in a common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of
writing our own code to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using #include<file_name.h>
command to make use of the functions those are declared in the header files.
When we include header files in our C program using #include<filename.h> command,
all C code of the header files are included in C program. Then, this C program is
compiled by compiler and executed.
Problem Solving & Computer Programming TEAM MCA 2016

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:

1. stdio.h: I/O functions:


1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() used for display or outputting the values
4. scanf() used for reading the values etc.
2. string.h: String functions

1. strcat() concatenates a copy of str2 to str1


2. strcmp() compares two strings
3. strcpy() copys contents of str2 to str1 etc.
3. ctype.h: Character functions

1. isdigit() returns non-0 if arg is digit 0 to 9


2. isalpha() returns non-0 if arg is a letter of the alphabet
3. isalnum() returns non-0 if arg is a letter or digit
4. islower() returns non-0 if arg is lowercase letter
5. isupper() returns non-0 if arg is uppercase letter etc.
4. math.h: Mathematics functions

1. acos() returns arc cosine of arg


2. asin() returns arc sine of arg
3. atan() returns arc tangent of arg
4. cos() returns cosine of arg
5. exp() returns natural logarithim e
6. fabs() returns absolute value of num
7. sqrt() returns square root of num etc.
5. time.h: Time and Date functions

1. time() returns current calender time of system


2. difftime() returns difference in secs between two times
3. clock() returns number of system clock cycles since program execution etc.
6. stdlib.h:Miscellaneous functions

1. malloc() provides dynamic memory allocation, covered in future sections


2. rand() as already described previously
3. srand() used to set the starting point for rand() etc.
Problem Solving & Computer Programming TEAM MCA 2016

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;

Assignment operator. Hand operator.


Problem Solving & Computer Programming TEAM MCA 2016

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.

Increment and Decrement operators:


To decrement the value of the variable by one or to increment the value of the
variable by one.
Operators:
++ - adds 1 to the operand
-- - subtracts 1 unary operators
Example:
++m; (++ used as prefix operator)
m++; (++ as postfix operator)
Consider the following
m=5;
y=++m;
In the above case m and y would be 6.
m=5;
y=m++;
In the above case m would be 6 and y would be 5.
Similarly for the --operator.

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

<< shift left


>> shift right
~ ones complement

Special operators:
Sizeof() - to determine the size of the variable

,(comma) - to link the related expressions together


Example : value=(x=10,y=17,x+y)

. and -> - member selection operator


& and * - pointer operator

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.

In the C family of languages, the following operators are unary:

Increment: ++x, x++


Decrement: x, x
Address: &x
Indirection: *x
Positive: +x
Negative: x
Ones' complement: ~x
Logical negation: !x
Sizeof: sizeof x, sizeof(type-name)
Cast: (type-name) cast-expression

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.

Mixed mode arithmetic:


Expression consists of both integer and real operands.
Example:
a-b where a is of type integer and b is of type real.
An arithmetic expression is a combination of variables, constants and operators. C has no
operator for exponentiation.

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

Precedence of arithmetic operators:


An arithmetic expression without parenthesis is always evaluated from left to right.
An arithmetic expression has two priorities.
The highest priority - /, *, %
The lowest priority - +, -
During the first pass, the high priority operators are evaluated as they are encountered. During
the second pass, the low priority operators are evaluated.

Type conversion in expressions:


C permits mixing of constants and variables in an expression, but stick on to the rule of type
conversion. When the data type of the two operands does not match, then the lower data type is
automatically converted to the higher type and the result is of the higher type.
1. All short and char are converted to int.
2. If one of the operand is long double then other will be converted to long double.
3. If one is double then other will be converted into double.
4. If one is float then other will be float.
5. If one is unsigned long int then other will be unsigned long int.
6. If one is unsigned long int and other one is long int then
a. Unsigned long int will be converted into long int or
b. Long int will be converted into unsigned long int.

The following conversions are possible


1. Float to int results in truncation
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of excess higher order bits.

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.

General form of Casting:

(type name) expression

Example:
x = ( int ) 7.5 = 7 (truncation)
a = ( int ) 21.3 / ( int ) 4.5
= 21 / 4
=5
Problem Solving & Computer Programming TEAM MCA 2016

Input & Output Statements in C


The process of giving something to the computer is known as Input. The input is mostly given by
keyboard. The term standard input refers to the input using keyboard. A program may need
certain inputs from the user for working properly. C language provides many functions to get
input from the
users.

some of the input are as follows:


scanf()
gets()
getch()
getche()
getc

Reading the data from the keyboard:


We can assign values to variables by inputting data through keyboard using the scanf
function.
Syntax:
scanf(control string,&var1,&var2,&varn);

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:

For value input: Variable name= getch();

For screen holding at the end of program: getch();

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

Syntax: Variable name=getche();


Example
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
char p;
printf("enter any character:");
p=getche();
printf("the character u entered=%c",p );
getch();
}

Output
enter any character:x
the character u entered=x

Using the getc function


The getc function reads the next character from a file stream, and returns the character as an
integer.

#include <stdio.h>

int main(void)
{
int ch1;
char ch2;

printf("Please, type in two characters together:\n");


ch1 = getc(stdin);
ch2 = getchar();
printf("The first character you have typed is: %c\n",ch1);
Problem Solving & Computer Programming TEAM MCA 2016

printf("The second character you have typed is: %c\n",ch2);


return 0;
}

Using the gets function


To read character by character from the input we have getc

#include <stdio.h>
#define MAX_LENGTH 80

int main(void)
{
char string[MAX_LENGTH];

printf("Please, write a line of no more than 80 characters:\n");


gets(string);
printf("The entered line is:\n");
puts(string);
return 0;
}

Using the getline function


The GNU library provides the nonstandard getline function that makes it easy to read lines reliably When
you have to read in a line of text from the keyboard, do it with getline; you will avoid future problems.

Eg:
bytes_read = getline(&string, &bytes_number, stdin);

Output Statements in C programming language:


printf()
puts()
putc()
fprintf()
putchar()

Formatting output with printf()


Output using printf:
It is used to display the output as well as to create an interactive program.
Syntax:
printf(control string,var1,var2,varn);

For precise output formatting, every printf() call contains a format control string that describes
the output format.
Problem Solving & Computer Programming TEAM MCA 2016

The format control string consists of:

Conversion specifiers.

Flags.

Field widths.

Precisions.

Literal characters.

Together with percent sign (%), these, form conversion specifications. Function printf()
can perform the following formatting capabilities:

Rounding floating-point values to an indicated number of decimal places.

Aligning a column of numbers with decimal points appearing one above the other.

Right-justification and left-justification of outputs.

Inserting literal characters at precise locations in a line of output.

Representing floating-point number in exponential format.

Representing unsigned integers in octal and hexadecimal format.

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.

Conversion specifier Description


d Display a signed decimal integer
Display a signed decimal integer. (Note: The i and d specifiers are different
i
when used with scanf().)
o Display an unsigned octal integer.
u Display an unsigned decimal integer.
Display an unsigned decimal integer. x causes the digit 0-9 and the letters A-
x or X
F to be displayed, and x causes the digits 0-9 and af to be displayed.
Place before any integer conversion specifier to indicate that a short or long
h or l (letter l)
integer is displayed respectively.

program example.
Problem Solving & Computer Programming TEAM MCA 2016

// using the integer conversion specifiers

#include <stdio.h>

int main()

printf("Various format for integer printing\n");

printf("-------------------------------------\n");

printf("%d\n", 455);

printf("%i\n", 455); //i same as d in printf()

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);

//-455 is read by %u and converted to the unsigned

//value 4294966841 by 4 bytes integer

printf("%x\n", 455);

printf("%X\n", 455);

return 0;

}
Problem Solving & Computer Programming TEAM MCA 2016

Output:

Printing Floating-point Number


Contains the decimal point such as 35.5 or 7456.945.
Conversion
Description
specifier
e or E Display a floating-point value in exponential notation.
f Display floating-point values.
Display a floating-point value in either the floating-point form f or the
g or G
exponential form e ( or E)
Place before any floating-point conversion specifier to indicate that a
l
long double floating-point value is displayed.

program example.

// printing floating-point numbers with floating-point conversion specifiers

#include <stdio.h>

void main()

printf("Printing floating-point numbers with\n");

printf("floating-point conversion specifiers.\n");


Problem Solving & Computer Programming TEAM MCA 2016

printf("Compare the output with source code\n\n");

printf("1. %e\n", 1234567.89);

printf("2. %e\n", +1234567.89);

printf("3. %e\n", -1234567.89);

printf("4. %E\n", 1234567.89);

printf("5. %f\n", 1234567.89);

printf("6. %g\n", 1234567.89);

printf("7. %G\n", 1234567.89);

Output:

Printing Strings And Characters


c and s conversion specifiers are used to print individual characters and strings
respectively.
Conversion specifier c requires a char argument and s requires a pointer to char as an
argument.
s causes characters to be printed until a terminating NULL (\0) character is encountered.
A program example.

// printing strings and characters

#include <stdio.h>
Problem Solving & Computer Programming TEAM MCA 2016

int main()

char character = 'A';

char string[ ] = "This is a string";

char *stringPtr = "This is also a string";

printf("---------------------------------\n");

printf("---Character and String format---\n");

printf("---------------------------------\n\n");

printf("%c <--This one is character\n", character);

printf("\nLateral string\n");

printf("%s\n", "This is a string");

printf("\nUsing array name, the pointer to the first array's element\n");

printf("%s\n", string);

printf("\nUsing pointer, pointing to the first character of string\n");

printf("%s\n", stringPtr);

return 0;

Output:
Problem Solving & Computer Programming TEAM MCA 2016

Other Conversion Specifiers


Conversion
Description
specifier
Display a pointer value (memory address) in an implementation
p
defined manner.
Store the number of characters already output in the current
n printf() statement. A pointer to an integer is supplied as the
corresponding argument. Nothing is displayed.
% Display the percent character.

Printing With Field Widths And Precisions


A field width determines the exact size of a field in which data is printed.
If the field width is larger then the data being printed, the data will normally be right-
justified within that field.
An integer representing the field width is inserted between the percent sign (%) and the
conversion specifier in the conversion specification.
Function printf() also provides the ability to specify the precision with which data is
printed.
Precision has different meanings for different data types.
The following is a program example.

// printing integers right-justified

#include <stdio.h>

int main()

{
Problem Solving & Computer Programming TEAM MCA 2016

printf(" Printing integers right-justified.\n");

printf("Compare the output with the source code\n");

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

Using Flags In The printf() Format Control String


Flags used to supplement its output formatting capabilities.
Five flags are available to be used in format control string as shown in table 5.4 then
followed by program examples.
Flag Description
- (minus sign) Left-justify the output within the specified field
Display a plus sign preceding positive values and a minus sign preceding negative
+ (plus sign)
values.
space Print a space before a positive value not printed with the + flag.
Prefix 0 to the output value when used with the octal conversion specifier o. Prefix 0x or
0X to the output value when used with the hexadecimal conversion specifiers x or X.
# Force a decimal points for a floating-point number printed with e, E, f, g, or G that does
not contain a fractional part. (Normally the decimal point is only printed if a digit
follows it). For g and G specifiers, trailing zeros are not eliminated.
0 (zero) Pad a field with leading zeros.

right justifying and left justifying values


#include <stdio.h>

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:

Using the putc function


The putc function prints out a character on the specified file stream.

#include <stdio.h>

int main(void)
{
int char1 = 65; /*Typically, the numeric value of A*/
char char2 = 'A';

printf("The character whose numeric value is 65 is:\n");


putc(char1,stdout);
printf("And char2 has the character:\n");
putchar(char2);
return 0;
}

Using the puts function


The puts function can be used to write a sequence of characters to the standard output stream

#include <stdio.h>
#define MAX_LENGTH 80

int main(void)
{
char string[MAX_LENGTH];

printf("Please, write a line of no more than 80 characters:\n");


gets(string);
printf("The entered line is:\n");
puts(string);
return 0;
Problem Solving & Computer Programming TEAM MCA 2016

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

Вам также может понравиться