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

UNIT I

Fundamentals of Programming- Flowcharts. Programming Strategies


(Introduction) :Top-Down, Structured Programming, Object Oriented
Programming.
C Data Types - C Compilation and Execution - Operators: Hierarchy of
Operators, Associativity of Operators - Expressions - Single
Dimensional Arrays - Console I/O functions: Formatted I/O:
scanf(),printf(),getchar(),putchar().
Fundamentals of Programming
•Problem solving is a process of identifying a problem and
finding the best solution for it.
•Computers are used as a tool to solve complex problems by
developing computer programs.
•Computer programs contain different instruction for
computer.
•A programmer writes instructions and computer executes
these instructions to solve a problem.
Algorithm
• An algorithm is a set of instruction for a specific task .
• An algorithm is a set of instructions used for solving problems in a
step-by-step manner
• Algorithm is a finite and ordered sequence of steps.
• It can be implemented in many different languages by using different
methods and programs.
• It is a description of a process independent of any programming
language.
Characteristics of Algorithm
• Each and every instruction should be precise and unambiguous.
• The instruction should not be repeated infinitely.
• Ensure that the algorithm will ultimately terminate.
• It should be written in sequence.
• It looks like normal English.
• The desired result should be obtained only after the algorithm
terminates.
Structure
• Statements
• State
• Control flow
• Sequential control
• Selection or conditional control
• Repetition or control flow

• Functions
Flowchart

• 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.
• Different symbols are used to draw each type of flowchart.
Flow chart symbols
Rules for drawing a flow chart

• The standard symbols should only be used .


• The arrowheads in the flowchart represents the direction of flow of
control in the problem
• The usual direction of the flow of procedure is from top to bottom or
left to right.
• Only one flow line should come to a process symbol and only one
flow line should be out from a process symbol.
Pseudocode
• Pseudocode is a kind of structured english for designing
algorithm.
• Pseudocodes came from two words.
– Pseudo -> imitation
– Code -> refer to instructions.
• Pseudocode cannot be compiled nor executed, and there
are no real formatting or syntax rules.
• The benefit of pseudo code is that it enables the
programmer to concentrate on the algorithms without
worrying about all the syntactic details of a particular
programming language.
• It is a mix of programming language and preferred
human language.
Rules for Pseudocode

• Write only one statement per line


• Capitalize initial keyword
• Indent to show hierarchy
• End multi line structures
• Keep statements language independent
Example 1 – Add 2 Numbers

Algorithm
STEP 1: Start Flowchart

STEP 2: Input first number as A

STEP 3: Input second number as B

STEP 4: Compute sum=A+B

STEP 5: Print sum


Pseudocode
STEP 6: Stop BEGIN

INPUT first number as A


INPUT second number as B

COMPUTE sum=A+B

PRINT sum

STOP
Example 2 - To print first 10 natural
numbers
STEP 1: Start
Algorithm
STEP 2: Set I=1
STEP 3: while I<=10, Repeat Step 4 and 5
Logic:
STEP 4: Print I
I=1 STEP 5: I=I+1
while I<=10 BEGIN
STEP 6: Stop
Print I SET I=1
I=I+1 WHILE I<=10
PRINT I
I=I+1

ENDWHILE
END Pseudoco
de
Programming Strategies
• Programming refers to the method of creating a sequence of instructions
to enable the computer to perform a task.
• A programming practice refers to the way of writing a program and is
used along with coding style guidelines.
• Some of the commonly used programming practices include
• Top-down programming,
• Bottom-up programming,
• Structured programming, and
• Object Oriented Programming
Top-down programming

Top-down programming focuses on the use of modules. It is therefore also


known as modular programming.
The program is broken up into small modules so that it is easy to trace a
particular segment of code in the software program.
The implementation of modules starts with the main module. After the
implementation of the main module, the subordinate modules are
implemented and the process follows in this way.
Example:C,FORTRAN
Bottom-up programming
Bottom-up programming refers to the style of programming
where an application is constructed with the description of
modules.
The description begins at the bottom of the hierarchy of modules
and progresses through higher levels until it reaches the top.
Example:C++,Java,Python
Structured Programming
• Structured Programming Languages are based on the top down methodology in which a
system is further divided into subsystem these are Typically Called as Functions.
• Top down analysis for problem solving: It focuses on dividing the problem into sub parts
and hence simplifies the problem solving.
• Modularization for program structure and organization: It organizes large instructions by
breaking them into separate and smaller section of modules, sub routines and
subprograms.
• Structured code for the individual modules Control structures are used to determine the
exact order in which the set of instructions are to be executed.
• By Introducing Modularity maintaining of Code and Debugging of Codes is became Easy.
and Readability of Code also Increased.
• Example: C Programming
Object oriented Programming

Object-Oriented Programming or OOPs refers to languages that use objects in


programming.
Object-oriented programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming.
The main aim of OOP is to bind together the data and the functions that operate on them
so that no other part of the code can access this data except that function.
Example:C++,Java,Python
Introduction
• C was developed in the early 1970s by “Dennis Ritchie” at Bell
Laboratories
• C was initially developed for writing system software
• Today, C has become a popular language and various software
programs are written using this language.
• Many other commonly used programming languages such as C++ and
Java are also based on C
Characteristics of C

• A high level programming language


• C is a Stable language, Core language, Portable language and Extensible
language
• Small size. C has only 32 keywords. This makes it relatively easy to learn
• Makes extensive use of function calls
• C is well suited for structured programming.
• Unlike PASCAL it supports loose typing (as a character can be treated as an
integer and vice versa)
• Facilitates low level (bitwise) programming
• Supports pointers to refer computer memory, array, structures and
functions.
Structure of C Program
// This is my first program in C

#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
return 0;
}
Identifier

• Identifiers are names given to program elements such as variables, arrays and functions.

Rules for forming identifier name


• it cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except
the underscore"_".
• There cannot be two successive underscores
• Keywords cannot be used as identifiers
• The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
• It must begin with an alphabet or an underscore.
• It can be of any reasonable length. Though it should not contain more than 31 characters.
• Example: roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code
Variables
• A variable is defined as a meaningful name given to the data storage location in computer memory.
• When using a variable, we actually refer to address of the memory where the data is stored.
• Declaring Variable
• To declare a variable specify data type of the variable followed by its name.
• Variable names should always be meaningful and must reflect the purpose of their usage in the program.
• Variable declaration always ends with a semicolon.
• Example,
• int emp_num;
• float salary;
• char grade;
• double balance_amount;
• unsigned short int acc_no;
Keywords
C has a set of 32 reserved words often known as keywords. All keywords
are basically a sequence of characters that have a fixed meaning.
By convention all keywords must be written in lowercase (small) letters.
Example: for, while, do-while, auto break, case, char, continue, do,
double, else, enum, extern, float, goto, if, int, long, register, return, short,
signed, sizeof, static, struct, switch, typedef, union, unsigned, void,
volatile
Data Types
DATA TYPE SIZE IN BYTES RANGE

char 1 -128 to 127

unsigned char 1 0 to 255

signed char 1 -128 to 127

int 2 -32768 to 32767

unsigned int 2 0 to 65535

signed short int 2 -32768 to 32767

signed int 2 -32768 to 32767

short int 2 -32768 to 32767

unsigned short int 2 0 to 65535

long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

signed long int 4 -2147483648 to 2147483647

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932


Integer

• Integers are whole numbers that can have both zero, positive and
negative values but no decimal values. For example, 0, -5, 10
• We can use int for declaring an integer variable.
• Example :int id;
• Here, id is a variable of type integer.
• You can declare multiple variables at once in C programming. For
example,
• int id, age;
Example
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{ {
int a=10; int a=10,b=20,c;
int b=20; c=a+b;
printf("answer:%d",c);
int c;
return 0;
c=a+b; }
printf("answer:%d",c);
return 0;
}
Character
• Keyword char is used for declaring character type variables.
• For example,
• char test = 'h';
• The size of the character variable is 1 byte.
Example
#include <stdio.h>
int main()
{
char test = 'h';
printf("answer:%c",test);
return 0;
}
Float and Double

•Float and double are used to hold real numbers.


• Example: float salary;
double price;
Example
#include <stdio.h>
int main()
{
float a, b, product;
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
// Calculating product
product = a * b;
// %.2lf displays number up to 2 decimal point
printf("Product = %.2lf", product);
return 0;
}
Compilation and Execution in C
The compilation and execution process of C can be divided in to multiple steps:

• Preprocessing - Using a Preprocessor program to convert C source code in expanded


source code. "#includes" and "#defines" statements will be processed and replaced
actually source codes in this step.
• Compilation - Using a Compiler program to convert C expanded source to assembly
source code.
• Assembly - Using a Assembler program to convert assembly source code to object code.
• Linking - Using a Linker program to convert object code to executable code. Multiple
units of object codes are linked to together in this step.
• Loading - Using a Loader program to load the executable code into CPU for execution.
• Here is a simple table showing input and output of each step in the compilation and
execution process:
•source code > Preprocessor > expanded source code
•expanded source code > Compiler > assembly source code
•assembly code > Assembler > object code
•object code > Linker > executable code
•executable code > Loader > execution
Operators in C
C language supports a lot of operators to be used in expressions. These
operators can be categorized into the following major groups:
Arithmetic operators
Relational Operators
Equality Operators
Logical Operators
Unary Operators
Conditional Operators
Bitwise Operators
Assignment operators
Comma Operator
Sizeof Operator
Arithmetic Operator

OPERATION OPERATOR SYNTAX COMMENT RESULT


result = a *
Multiply * a * b
b
27

result = a /
Divide / a / b
b
3

result = a +
Addition + a + b
b
12

Subtracti - a - b
result = a –
6
on b

result = a %
Modulus % a % b
b
0
Relational Operator
Also known as a comparison operator, that compares two
values.
Expressions that contain relational operators are called
relational expressions.
Relational operators return true or false value, depending on
whether the conditional relationship between the two operands
holds or not.
OPERATOR MEANING EXAMPLE
< LESS THAN 3 < 5 GIVES 1

> GREATER THAN 7 > 9 GIVES 0

>= LESS THAN OR EQUAL TO 100 >= 100 GIVES 1

GREATER THAN EQUAL


<= 50 >=100 GIVES 0
TO
Equality Operator
C language supports two kinds of equality operators to
compare their operands for strict equality or inequality.
They are equal to (==) and not equal to (!=) operator.
The equality operators have lower precedence than the
relational operators.

OPERATOR MEANING

== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0 OTHERWISE

RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME VALUE, 0


!=
OTHERWISE
Logical Operator
C language supports three logical operators.
They are- Logical AND (&&), Logical OR (||) and Logical
NOT (!).
Logical expressions are evaluated from left to right.

A B A &&B A B A || B
A !A

0 0 0 0 0 0
0 1
0 1 0 0 1 1

1 0 0 1 0
1 0 1

1 1 1 1 1 1
Unary Operator
Unary operators act on single operands.
C language supports three unary operators. They are unary minus,
increment and decrement operators.
When an operand is preceded by a minus sign, the unary operator negates
its value.
The increment operator is a unary operator that increases the value of its
operand by 1. Similarly, the decrement operator decreases the value of its
operand by 1. For example,
int x = 10, y; y = ++x;
y = x++;

is equivalent to writing is equivalent to writing


y = x; x = x + 1;
x = x + 1; y = x;
Example
• a = 5, b = 10, c = 15, d = 20;
•result1 = a++ + --b - c-- + ++d;
•result2 = --a - d++ + ++b - c--;
Conditional Operator
The conditional operator operator (?:) is just like an if .. else statement that
can be written within expressions.
The syntax of the conditional operator is
exp1 ? exp2 : exp3
Here, exp1 is evaluated first. If it is true then exp2 is evaluated and
becomes the result of the expression, otherwise exp3 is evaluated and
becomes the result of the expression.
For example, large = ( a > b) ? a : b
Conditional operators make the program code more compact, more
readable, and safer to use.
Conditional operator is also known as ternary operator as it is neither a
unary nor a binary operator; it takes three operands.
Bitwise Operator
Bitwise operators perform operations at bit level. These operators include: bitwise
AND, bitwise OR, bitwise XOR and shift operators.
The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
The bitwise OR operator ( | ) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
The bitwise NOT ( ~ ), or complement, is a unary operation that performs logical
negation on each bit of the operand. By performing negation of each bit, it actually
produces the ones' complement of the given binary value.
The bitwise XOR operator ( ^ ) performs operation on individual bits of the
operands. The result of XOR operation is shown in the table
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise Shift Operator
In bitwise shift operations, the digits are moved, or shifted, to the left or
right.
The CPU registers have a fixed number of available bits for storing
numerals, so when we perform shift operations; some bits will be "shifted
out" of the register at one end, while the same number of bits are "shifted
in" from the other end.
In a left arithmetic shift, zeros are shifted in on the right.
For example;
unsigned int x = 11000101;
Then x << 2 = 00010100
• Right Shift Operators:
• 212 = 11010100 (In binary)
• 212 >> 2 = 00110101 (In binary)
• 212 >> 7 = 00000001 (In binary)
• 212 >> 8 = 00000000
• 212 >> 0 = 11010100 (No Shift)
• Left Shift Operator
• 212 = 11010100 (In binary)
• 212<<1 = 110101000 (In binary) [Left shift by one bit]
• 212<<0 = 11010100 (Shift by 0)
• 212<<4 = 110101000000 (In binary) =3392(In decimal)
Assignment Operator
The assignment operator is responsible for assigning values to the variables.
While the equal sign (=) is the fundamental assignment operator, C also supports
other assignment operators that provide shorthand ways to represent common
variable assignments.
They are shown in the table.

OPERATOR SYNTAX EQUIVALENT TO

/= variable /= expression variable = variable / expression

\= variable \= expression variable = variable \ expression


*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount
Comma Operator
The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the
result of the expression.
Comma separated operands when chained together are evaluated in left-to-right
sequence with the right-most value yielding the result of the expression.
Among all the operators, the comma operator has the lowest precedence.
For example,
int a=2, b=3, x=0;
x = (++a, b+=a);
// here it will evaluate first expression now a=3,
then second expression b+=a i.e., [b=a+b]
= 3 +3
Now, the value of x = 6.
Sizeof Operator
‘sizeof’ is a unary operator used to calculate the sizes of Data Types.
It can be applied to all data types.
The operator returns the size of the variable, data type or expression in bytes.
'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take.
For example,
‘sizeof(char)’ returns 1, that is the size of a character data type.
Example
int a = 10;
unsigned int result;
result = sizeof(a); // now ‘a’ is of the type integer
then result = 2,
Operator Precedence and Associativity
Operator Precedence & Associativity

Operator Description Associativity


() Parentheses (function call)
[] Brackets (array subscript)
. Member selection via object name left-to-right
-> Member selection via pointer
++ -- Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value
of type) right-to-left
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this
implementation
Operator Precedence & Associativity

Operator Description Associativity


* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal


to left-to-right
> >= Relational greater than/greater than or
equal to
== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right


Operator Precedence & Associativity

Operator Description Associativity


^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

, Comma (separate expressions) left-to-right


Operator Precedence & Associativity

Operator Description Associativity


= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment right-to-left
^= |= Bitwise exclusive/inclusive OR
assignment
<<= >>= Bitwise shift left/right assignment
Expression
•An expression is a combination of operators, constants and
variables. An expression may consist of one or more
operands, and zero or more operators to produce a value.
•Example:
•a+b-c
•a*b/c
•c=a+b
•x<y
•6*2/( 2+1 * 2/3 +6) +8 * (8/4)
•25+23*10/11-3+([++3]-5*2-1)
•110 + 22 / 14 - 3 * 10
•12<<4
Input and output statements in C
• Formatted I/O
• Printf()
• Scanf()
• Unformatted I/O
• getch()
• getche()
• getchar()
• putchar()
• gets()
• puts()
• putch()
getch()
•getch() function reads a single character from the keyboard
by the user but doesn’t display that character on the console
screen and immediately returned without pressing enter key.
•getch() is also used for hold the screen.
•Syntax:
•getch(); or variable-name = getch();
Example
int main()
{
printf("Enter character: ");
getch();
return 0;
}
getche():
•getche() function reads a single character from the keyboard
by the user and displays it on the console screen and
immediately returns without pressing the enter key.
•Syntax:
•getche(); or variable-name = getch();
Example
int main()
{
printf("Enter any character: ");
getche();
return 0;
}
getchar():

•The getchar() function is used to read only a first single


character from the keyboard whether multiple characters is
typed by the user and this function reads one character at one
time until and unless the enter key is pressed.
•Syntax:
•variable-name = getch();
int main()
{
char ch;
printf("Enter the character: ");
ch = getchar();
printf("%c", ch);
return 0;
}
putchar():

•The putchar() function is used to display a single character at


a time by passing that character directly to it or by passing a
variable that has already stored a character.
•Syntax:
•putchar(variable_name);
Example
int main()
{
char ch;
printf("Enter any character: ");
ch = getchar();
putchar(ch);
return 0;
}
gets():

•gets() function reads a group of characters or strings from the


keyboard by the user and these characters get stored in a
character array.
•This function allows us to write space-separated texts or
strings.
•Syntax:
•char str[length of string in number];
•gets(str);
Example
int main()
{
char name[50];

printf("Please enter some texts: ");


gets(name);
printf("You have entered: %s",name);
return 0;
}
puts():

•puts() function is used to display a group of characters or


strings which is already stored in a character array.
•Syntax:
• puts(identifier_name );
putch():

•putch() function is used to display a single character which is


given by the user and that character prints at the current
cursor location. This function is declared in conio.h(header
file)
•Syntax:
•putch(variable_name);
Example
int main()
{
char ch;
printf("Enter any character:\n ");
ch = getch();
printf("\nEntered character is: ");
putch(ch);
return 0;
}

You might also like