Sunteți pe pagina 1din 67

INTRODUCTION TO

PROGRAMMING

SYLLABUS

UNIT - I
Concept of algorithms, Flow Charts, Overview of the compiler ( preferably
GCC) , Assembler, linker and loader , Structure of a simple Hello World
Program in C ,Overview of compilation and execution process in an IDE
( preferably Code Block)[T1], [T2], [R4][R5]. [No. of hrs 8]
UNIT - II
Programming using C: Preprocessor Directive, C primitive input output
using get char and put char , simple I/O Function calls from library , data
type in C including enumeration , arithmetic, relational and logical
operations, conditional executing using if, else, switch and break .Concept
of loops , for, while and do-while , Storage Classes: Auto, Register, Static
and Extern[T1], [T2], [R7] [No. of hrs 8]

UNIT - III
Arrays (one and two dimensional), 2-d arrays used in matrix
computation. Concept of Sub-programming, functions. Parameter
transmission schemes i.e. call by value and call by reference,
Pointers, relationship between array and pointer, Argument
passing using pointers, Array of pointer, passing arrays as
arguments [T2],[R1], [R7] [No. of hrs 8]
UNIT - IV
Structure and unions , Strings and C string library, File Handling in
C Using File Pointers,fopen( ), fclose(),Input and Output using file
pointers, Character Input and Output with Files , String Input
Output Functions ,
Formatted Input / Output Functions,Block Input / Output Functions,
Sequential Vs Random Access Files , Positioning the File
Pointer[T1], [T2],[R2], [R7]. [No. of hrs 8]

ALGORITHMS
A typical programming task can be divided
into two phases:
Problem solving phase
produce an ordered sequence of steps that
describe solution of problem
this sequence of steps is called an algorithm

Implementation phase
implement the program in some programming
language

Format of an Algorithm
Algorithm name(input,output)
1.
2.
n(Algorithm body which contain
finite no. of steps )
Algorithm can be write in English
language style or English
programming style.

Ex.
Sum(A,B, out)
1. Get the two inputs from the user
2. Assign the inputs to A & B
3. Set out:= A+B or set out <A+B
4. Exit

Algorithm
Example 1: Write an algorithm to
determine a students final grade
and indicate whether it is passing or
failing. The final grade is calculated
as the average of four marks.

Algorithm
Detailed Algorithm

Step 1:
Input M1,M2,M3,M4
Step 2:
GRADE
(M1+M2+M3+M4)/4
Step 3:
if (GRADE < 50) then
Print FAIL
else
Print PASS
endif

Algorithm Analysis
It is analyze in terms of their
efficiency i.e. how much computer
memory space and execution time it
uses, to store and to execute
Space complexity- for fixed and vary
variable
Time complexity- compile time and
run time

The Flowchart
(Dictionary) A schematic representation of a
sequence of operations, as in a manufacturing
process or computer program.
(Technical) A graphical representation of the
sequence of operations in an information system
or program. 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.

The Flowchart
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their
interconnections
e.g. control flow from one action to the
next

Flowchart Symbols
Basi
c

Example
START
Input
M1,M2,M3,
M4
GRADE(M1+M2+M3+M
4)/4
N

IS
GRADE<
50

PRINT
PASS

PRINT
FAIL

STOP

Step 1:
Input M1,M2,M3,M4
Step 2: GRADE
(M1+M2+M3+M4)/4
Step 3: if (GRADE <50) then
Print FAIL
else
Print PASS
endif

Example 2
Write an algorithm and draw a
flowchart to convert the length in
feet to centimeter.

Example 2
Algorithm
Step 1: Input Lft
Step 2: Lcm Lft x 30
Step 3: Print Lcm

Flowchart
START

Input
Lft

Lcm

Lft x
30

Print
Lcm

STOP

Example 4
START

Algorithm:

Step
Step
Step
Step
Step

1:
2:
3:
4:
5:

Input a, b, c
d sqrt ( b b 4 a c
x1 (b + d) / (2 x a)
x2 (b d) / (2 x a)
Print x1, x2

Input
a, b, c

)
d

sqrt(b x b 4 x a x
c)

x1

(b + d) / (2 x a)

X2

(b d) / (2 x a)
Print
x1 ,x2

STOP

The benefits of flowcharts are as follows:


Communication: Flowcharts are better way of communicating
the logic of a system to all concerned.
Effective analysis: With the help of flowchart, problem can be
analysed in more effective way.
Proper documentation: Program flowcharts serve as a good
program documentation, which is needed for various purposes.
Efficient Coding: The flowcharts act as a guide or blueprint
during the systems analysis and program development phase.
Proper Debugging: The flowchart helps in debugging process.
Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart. It helps the
programmer to put efforts more efficiently on that part

Feature of C
Hardware independent
Provide functionality through rich set
of function libraries
Case-sensitive

C language is efficient and fast.


C is highly portable.
C language is well suited for
structured programming.
C is a machine independent
language.
C has the ability to extend itself.

Basic structure of C
programming
Documentation section
Link section
Definition section
Global declaration section
main () Function section
{
Declaration part
Executable part

Subprogram section
Function 1
Function 2
..
..
Function n

(User defined functions)

Basic structure of C
programming
Documentation section
Link section
Definition section
Global declaration section
main () Function section
{
Declaration part
Executable part

Subprogram section
Function 1
Function 2
..
..
Function n

(User defined functions)

i)Documentation section :The documentation section consists


of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use
later.
ii)Link section :The link section provides instructions to the
compiler to link functions from the system library.
iii)Definition section :The definition section defines all symbolic
constants.
iv)Global declaration section :There are some variables that
are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is
outside of all the functions. This section also declares all the userdefined functions.

main () function section :Every C program must have one


main function section. This section contains two parts;
declaration part and executable part.
(a)Declaration part :The declaration part declares all the
variables used in the executable part.
(b)Executable part :There is at least one statement in the
executable part.
These two parts must appear between the opening and
closing braces. The program execution begins at the opening
brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in
the declaration and executable part end with a semicolon.

vi)Subprogram section :The subprogram


section contains all the user-defined functions
that are called in themain()function. Userdefined functions are generally placed
immediately after themain()function, although
they may appear in any order.

All section, except themain()function


section may be absent when they are not
required.

Execution of a C program
Executing a C program involves a
series of steps. They are i)Creating the program.
ii)Compiling the program.
iii)Linking the program with
functions that are needed from the
C library.
iv)Executing the program.

Draw the flow chart of theprocess of


compiling and running a C program

Simple C Program
A program to print Welcome to c
/* A first C Program*/
# include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
printf(Welcome to C\n");
getch();
}

void main()
This statement declares the main
function.
A C program can contain many
functions but must always have one
main function.
A function is a self-contained module
of code that can accomplish some
task.

{
This opening bracket denotes the
start of the program

printf("Welcome to C\n");
printf is a function from a standard C library
that is used to print strings to the standard
output, normally your screen.
The compiler links code from these standard
libraries to the code you have written to
produce the final executable.
The "\n" is a special format modifier that tells
the printf to put a line feed at the end of the
line.
If there were another printf in this program, its
string would print on the next line.

}
This closing bracket denotes the
end of the program.

2.1 Introduction
REVIEW:
A bit is the most basic unit of information in a computer.
It is a state of on or off in a digital circuit.
Sometimes these states are high or low voltage
instead of on or off..
A byte is a group of eight bits.
A byte is the smallest possible addressable (can be found
via its location) unit of computer storage.
A word is a contiguous group of bytes.
Words can be any number of bits (16, 32, 64 bits are
common).
A group of four bits is called a nibble (or nybble).
Bytes, therefore, consist of two nibbles: a high-order
nibble, and a low-order nibble.

Chapter 2: Data Representation

35

Operators and expressions

Assignment Operator
x=3

= is an operator
The value of this expression is 3
= operator has a side effect -- assign 3 to x

The assignment operator =


The side-effect is to assign the value of the right
hand side (RHS) to the left hand side (LHS).
The value is the value of the RHS.

For example:
x = ( y = 3 ) +1;
/* y is assigned 3 */
/* the value of (y=3) is 3 */
/* x is assigned 4 */

Arithmetic operators in C
C operation Algebric C
Addition(+) a+7 a+7
Subtraction (-)
b-c b-c
Multiplication(*) am a*m
Division(/)
x/y
x/y
Modulus(%)
r mod s r%s
Unary +
+a
Unary - -a
An expression is a combination of variables, constants and operators.

Precedence order
Highest to lowest

(left to right in an

expression)
()
*, /, %
+, -

Example:
z = p * r % q + w / x y ;
1 2
4
3 5
a * ( b + c ) + c * ( d + e ) ;
3 1
5 4 2

Operator Precedence and


Associativity
highest: + - (unary)
-i
*
-j
=
(-i)
*
(-j)
* / %
lowest: + - (binary) +i + j / k = (+i) + (j / k)

ft/right associative: it groups from left/right to right/

binary arithmetic operators (*, /, %, + and -) are all left assoc


k = (i j) k
i*j/k
= (i * j) / k

unary arithmetic operators( + and -) are both right associativ


= - ( +i )

Compound(Shorthand) Assignment Operator

Often we use update forms of operators


x=x+1, x=x*2, ...
C offers a short form for this:
Generic Form : variable op= expr
is

equivalent to variable = variable op expr


Operator

Equivalent to:

x *= y

x=x*y

y -= z + 1

y = y - (z + 1)

a /= b

a=a/b

x += y / 8

x = x + (y / 8)

y %= 3

y=y%3

Update forms have value equal to the final


value of expr

Relational Operators
Relational operators allow you to compare two operands
(that can be variables, constants or expressions).
They return a 1 value for true and a 0 for false.
Operator Symbol

Example

Equals== x == y
Greater than > x > y
Less than < x < y
Greater/equals >= x >= y
Less than/equals<= x <= y
Not equal
!=x != y
0 as false
1as true

Relational Operators
Examples :
a<b
a==b+3
d>=5.66
(p+q)<=(t+r-5)
alpha!=t
int a=10,b=20,c=30,d,e;
d=a>b;
e=b<=c;
d=?, e=?

Logical Operators
Combines
the
results
of
evaluation
of
expressions that evaluates to either true or false.
&&
AND - true only if two expressions are
true.
||
OR - true if atleast one of the two
expressions are true.
!
NOT - reverses the value of expression it
operates on.
!,&&, || (order of precedence level),(!- right
associative, &&, || - left associative)
Ex..

!((a>1)&&(a<10))||((a<-1)&&(a>-10))

Operator Precedence
Operator

Precedence level

() 1
~, ++, --, unary - 2
*, /, % 3
+, - 4
<<, >>
5
<, <=, >, >= 6
==, != 7
& 8
^
9
| 10
&& 11
|| 12
=, +=, -=, etc. 13
Well be adding more to this list later on...

Variable Type
C has the following simple data types:

Control Structures

C has the following control


Control
Structures
statements:
1)Sequential
2)Selection/Decision (if, ifelse, nested ifs)
3)Case (switch)
4)Repetition/Iteration/Loop
(while, do-while, for)
5)Jump (break, exit, goto,
continue)

if Statement-example
with simple statement

7.

main( )
{
int grade; //variable declaration
printf("Please input your grade:");
scanf("%d", &grade);
if( grade >= 60)
/* boolean
expression*/
printf("You passed the exam!\n");

8.

1.
2.
3.
4.
5.
6.

//if condition is true, print statement executed

if Statement-example with
compound statement
1.
2.
3.
4.
5.
6.
7.

main( )
{
int grade;
printf("Please input your grade:");
scanf("%d", &grade);
if( grade >= 60)
{
}

8.

printf("You passed the exam!\n");


printf( with grade %d,grade);

The if-else statement


The if-else statement
statements to execute

chooses

which

of

two

The if-else statement has the form:

if (condition)

statement-to-execute-if-true ;
else
statement-to-execute-if-false ;
Either statement (or both) may be a compound
statement
Notice the semicolon after each control statement.

Flowchart for the if-else


statement

true

statement-1

condition?

false

statement-2

if-else Statement example


1.
2.
3.
4.
5.
6.
7.
8.
9.

if( grade >= 60)


{
/* compound statement */
printf("You passed "); //Executed if true
printf("the exam!\n");
}
else
{
printf("You failed!\n"); //executed if false
}

The if Statement
Form 1:

if (expression)

statement1;
next statement;

Form 2:

if (expression)

statement1;
else

statement2;
next statement;

Form 3:

if (expression)

statement1;
else if (expression)

statement2;
else

statement3;
next statement;

Execute statement1
if expression is non-zero
(i.e., it does not have to be exactly 1)

switch Multiple-Selection Structure


switch ( integer/char expression )
{
case constant1 :
statement(s)
break ;
case constant2 :
statement(s)
break ;
...
default:
statement(s)
break ;
}

Flowchart- Switch Statement


case a

true

case a action(s)

break

case b action(s)

break

case z action(s)

break

false

case b

true

false
.
.
.

case z
false
default action(s)

true

Switch-Case Example
switch ( day )
{
case 0: printf (Sunday\n) ;
break ;
case 1: printf (Monday\n) ;
break ;
case 2: printf (Tuesday\n) ;
break ;
case 3: printf (Wednesday\n) ;
break ;
case 4: printf (Thursday\n) ;
break ;
case 5: printf (Friday\n) ;
break ;
case 6: printf (Saturday\n) ;
break ;
default: printf (Error -- invalid day.\n) ;
break ;
}

switch Statement Details


Note: The last statement of each case in
the switch should almost always be a
break.
The break causes program control to jump
to the closing brace of the switch structure.
Without the break, the code flows into the
next case. This is almost never what you
want.
A switch statement will compile without a
default case, but always consider using
one.

ITERATIONS(LOOP CONTROL
POWER)

The while Statement

Generic Form
while (condition)
statement

Executes as expected:
1. condition is evaluated
2. If condition is false (i.e. 0), loop is exited (go to step
5)
3. If condition is true (i.e. nonzero), statement is
executed
4. Go to step 1
5. Next statement

The while Repetition Structure

Flowchart of while loop

true
condition

false

statement

Sum from 1 to 100


(while)
int
START
i=1,sum=0;
while(i<=1
00)
{
sum=sum+i
;

END

The do ... while Loop


Generic Form:
do
statement
while (condition);

Standard repeat until loop

Like a while loop, but with condition test at bottom.


Always executes at least once.

The semantics of do...while:


1.
2.
3.
4.

Execute statement
Evaluate condition
If condition is true go to step 1
Next statement

The do/while Repetition Structure

The do/while repetition structure is


similar to the while structure,
Condition for repetition tested after the body of
the loop is executed

Format:
do {
statement
} while ( condition );

statement

Example (letting counter = 1):


do {
printf(%d,counter);
} while (++counter <= 10);

true
condition

This prints the integers from 1 to 10

false

All actions are performed at least once.

Sum from 1 to 100 (do-while)

int
i=1,sum=0;
do{
sum=sum+i
;
i++;
} while

The for Statement

The most important looping structure in C.


Generic Form:
for (initial ; condition ; increment )
statement

initial, condition, and increment are C expressions.


For loops are executed as follows:
1.
2.
3.
4.
5.
6.

initial is evaluated. Usually an assignment statement.


condition is evaluated. Usually a relational expression.
If condition is false (i.e. 0), fall out of the loop (go to step 6.)
If condition is true (i.e. nonzero), execute statement
Execute increment and go back to step 2.
Next statement

Flowchart for for-loop


Initialize variable

Condition
Test the variable

false

true

statement

Increment variable

S-ar putea să vă placă și