Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Computer Programming I-1

Uploaded by

richugeorge9835
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Computer Programming I-1

Uploaded by

richugeorge9835
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 155

Computer Programming I

ICS 2175
Programming Terms & Concepts
• Program: A computer Program is a set of related instructions written in the
language of the computer & is used to make the computer perform a specific task
(or, to direct the computer on what to do).
• Programming is the process of creating a set of instructions that tell a computer
how to perform a task. This is usually done through creation of programs.
• The tools of writing programs are called programming languages. There are a
variety of computer programming languages, such as C, JavaScript, Python, and
C++.
Programming Terms & Concepts
• Programming Language – Is a vocabulary and set of grammatical rules
used to develop software programs, scripts, or other set of instructions for
computers to execute.

• Although many languages share similarities, each has its own syntax.

• Once a programmer learns the language rules, syntax and structure, they
write the source code in a text editor or IDE( Integrated Development
Environment)
Programming Terms & Concepts
• Integrated Development Environment(IDE): The process of editing, compiling,
running, and debugging programs is often managed by a single integrated application
known as an Integrated Development Environment, or IDE for short.

• An IDE is a windows-based program that allows you to easily manage large software
programs, edit files in windows, and compile, link, run, and debug your programs.

• Examples of IDE’s used to create and execute C programs include Code::Blocks, Dev-
C++, Eclipse, VsCode, CodeLite
Programming Paradigms
• Paradigm can be termed as method to solve some problem or do some task.

• A programming paradigm is a style, approach or “way,” of programming.

• Examples of programming paradigms include:-


• Structured programming Language
• Object-Oriented Programming Language.

• Procedural Programming Language.

• Functional Programming Language.

• Scripting Programming Language.

• Logic Programming Language.


Structured Programming
• Structured programming is an approach to writing programs that are easier to read, test, debug
and modify. Programs designed this way can be developed faster.
• The approach assists in the development of large programs through stepwise refinement and
modularity.
• Stepwise Refinement - Stepwise Refinement is the process of breaking down a programming
problem into a series of steps.
• You start with a general set of steps to solve the problem, defining each in turn.
• Once you have defined each of the steps you then break the problem down into a series of smaller sub-steps.
• Once this is complete you keep on going until you have described the problem in such a level of detail that you can
code a solution to the problem.
Structured Programming
• Modularization for program structure and organization: It organizes large instructions
by breaking them into separate and smaller section of modules, sub routines and
subprograms.
• When modules are used to develop large programs, several programmers can work on
different modules, thereby reducing program development time.
• In short, structured programming serves to increase programmer productivity, program
reliability (readability and execution time), program testing, program debugging and
serviceability.
Structured Programming
• C is called a structured programming language because to solve a large problem, C programming
language divides the problem into smaller structural blocks each of which handles a particular
responsibility.

• These structural blocks are :-

• Decision making blocks like if-else-elseif, switch-cases,

• Repetitive blocks like For-loop, While-loop, Do-while loop etc.

• subroutines/procedures - functions

• The program which solves the entire problem is a collection of such structural blocks. Even a
bigger structural block like a function can have smaller inner structural blocks like decisions and
loops.
Program Development Cycle
• When we want to develop a program using follows….

any programming language, we follow a 1. Problem Definition


sequence of steps. These steps are called 2. Problem Analysis
phases in program development.
3. Algorithm Development
• The program development life cycle is a set 4. Coding & Documentation
of steps or phases that are used to develop a
5. Testing & Debugging
program in any programming language.
6. Maintenance
• Generally, the program development life

cycle contains 6 phases, they are as


1. Problem Definition
• In this phase, we define the problem statement and we decide the boundaries of the
problem. In this phase we need to understand the problem statement, what is our
requirement, what should be the output of the problem solution. These are defined in
this first phase of the program development life cycle.

2. Problem Analysis
• In phase 2, we determine the requirements like variables, functions, etc. to solve the
problem. That means we gather the required resources to solve the problem defined in
the problem definition phase. We also determine the bounds of the solution.
3. Algorithm Development

• During this phase, we develop a step by step procedure to solve the problem using the
specification given in the previous phase. This phase is very important for program
development. That means we write the solution in step by step statements. Achieved
through; Stepwise refinement, Structure charts, pseudocode and flow charts

4. Coding & Documentation

• This phase uses a programming language to write or implement the actual programming
instructions for the steps defined in the previous phase. In this phase, we construct the
actual program. That means we write the program to solve the given problem using
programming languages like C, C++, Java, etc.,
5. Testing & Debugging

• During this phase, we check whether the code written in the previous step is solving the
specified problem or not. That means we test the program whether it is solving the problem for
various input data values or not. We also test whether it is providing the desired output or not.

6. Maintenance

• During this phase, the program is actively used by the users. If any enhancements found in this
phase, all the phases are to be repeated to make the enhancements. That means in this phase, the
solution (program) is used by the end-user. If the user encounters any problem or wants any
enhancement, then we need to repeat all the phases from the starting, so that the encountered
problem is solved or enhancement is added.
Algorithms
• In computer programming terms, an algorithm is a set of well-defined instructions to
solve a computational problem. It takes a set of input and produces a desired output.

• An algorithm for a particular task can be defined as “a finite sequence of instructions,


each of which has a clear meaning and can be performed with a finite amount of effort in
a finite length of time”. As such, an algorithm must be precise enough to be understood by
human beings.

• Algorithms can be represented using ​pseudocode​(code-like English text statements) or


a ​flowchart (labelled symbols connected to show the flow of action).
Algorithms

• For example,

• An algorithm to add two numbers:


1. Take two number inputs

2. Add numbers using the + operator

3. Display the result


Qualities of Good Algorithms
• Input and output should be defined precisely.
• Each step in the algorithm should be clear and unambiguous.
• Algorithms should be most effective among many different ways to solve a problem.
• An algorithm shouldn't include computer code. Instead, the algorithm should be
written in such a way that it can be used in different programming languages. -
Algorithms are generally created independent of underlying languages, i.e.. an
algorithm can be implemented in more than one programming language.
Flowcharts
• A flow chart, or flow diagram, is a graphical representation of a process or system that
details the sequencing of steps required to create output.

• It shows the steps as boxes (symbols) of various kinds, and their order by connecting
these symbols with arrows. Flowcharts are used in designing or documenting a process or
program.

• Flowcharts can be used in the analysis, design, documenting or managing a process or


program in various fields. They are also used in designing and documenting complex
processes or programs.
Pseudocodes
• Pseudocode is an informal way of programming description that does not require
any strict programming language syntax or underlying technology considerations.
It is used for creating an outline or a rough draft of a program

• It is a simple way of writing programming code in English. Pseudocode is not


actual programming language. It uses short phrases to write code for programs
before you actually create it in a specific language. Once you know what the
program is about and how it will function, then you can use pseudocode to create
statements to achieve the required results for your program.
Characteristics
• Pseudo code consists of short, readable and formally styled English languages used for
explaining an algorithm.

• It does not include details like variable declaration, subroutines.

• It is easier to understand for the programmer or non programmer to understand the general
working of the program, because it is not based on any programming language.

• It gives us the sketch of the program before actual coding.

• It is not a machine readable

• Pseudo code can’t be compiled and executed


Guidelines for writing pseudo code:

• Write one statement per line

• Capitalize initial keyword

• Indent to hierarchy

• End multiline structure

• Keep statements language independent


Common Keywords Used in Pseudocode
• The following gives common keywords used in pseudocodes.
• //: This keyword used to represent a comment.

• BEGIN,END: Begin is the first statement and end is the last statement.

• INPUT, GET, READ: The keyword is used to inputting data.

• COMPUTE, CALCULATE: used for calculation of the result of the given expression.

• ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.

• OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.

• IF, ELSE, ENDIF: used to make decision.

• WHILE, ENDWHILE: used for iterative statements.

• FOR, ENDFOR: Another iterative incremented/decremented tested automatically.


Advantages & Disadvantages
Advantages
• Pseudo is independent of any language; it can be used by most programmers.
• It is easy to translate pseudo code into a programming language.
• It can be easily modified as compared to flowchart.
• Converting a pseudo code to programming language is very easy as compared with converting a
flowchart to programming language.
Disadvantages
• It does not provide visual representation of the program’s logic.
• There are no accepted standards for writing pseudo codes.
• It cannot be compiled nor executed.
• For a beginner, it is more difficult to follow the logic or write pseudo code as compared to flowchart.
Examples
• Addition of two numbers: • Greatest of two numbers

BEGIN BEGIN
GET a , b READ a , b
ADD c=a + b IF (a>b) THEN
PRINT c
DISPLAY a is greater
END
ELSE

DISPLAY b is greater

END IF

END
Write an algorithm to find area of a rectangle
• Algorithm
Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop

• Pseudocode
BEGIN
READ l,b
CALCULATE A=l*b
DISPLAY A
END
Write an algorithm for Calculating area and
circumference of circle
• Algorithm
Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop
• Pseudocode
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
END
To check greatest of two numbers
Algorithm Pseudocode
Step 1: Start BEGIN

READ a,b
Step 2: get a,b value
IF (a>b) THEN
Step 3: check if(a>b) print a is greater
DISPLAY a is greater
Step 4: else b is greater ELSE

Step 5: Stop DISPLAY b is greater

END IF

END
To check greatest of three numbers
Algorithm
Step1: Start
Step2: Get A, B, C
Step3: if(A>B) goto Step4 else goto step5
Step4: If(A>C) print A else print C
Step5: If(B>C) print B else print C
Step6: Stop

Pseudocode
BEGIN
READ a, b, c
IF (a>b) THEN
IF(a>c) THEN
DISPLAY a is greater
ELSE
DISPLAY c is greater
END IF
ELSE
IF(b>c) THEN
DISPLAY b is greater
ELSE
DISPLAY c is greater
END IF
END IF
END
To check positive or negative number
• Algorithm
Step 1: Start
Step 2: get num
Step 3: check if(num>0) print a is positive
Step 4: else num is negative
Step 5: Stop
• Pseudocode
BEGIN
READ num
IF (num>0) THEN
DISPLAY num is positive
ELSE
DISPLAY num is negative
END IF
END
Write an algorithm to check whether given number is
+ve, -ve or zero.
• Algorithm
• Step 1: Start
• Step 2: Get n value.
• Step 3: if (n ==0) print “Given number is Zero” Else goto step4
• Step 4: if (n > 0) then Print “Given number is +ve”
• Step 5: else Print “Given number is -ve”
• Step 6: Stop
• Pseudocode
• BEGIN
• GET n
• IF(n==0) THEN
• DISPLAY “ n is zero”
• ELSE
• IF(n>0) THEN
• DISPLAY “n is positive”
• ELSE
• DISPLAY “n is positive”
• END IF
• END IF
• END
Advantages Of Using Flowcharts
• 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 analyzed 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
Limitations Of Using Flowcharts
• Complex logic: Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
• Alterations and Modifications: If alterations are required the flowchart
may require re-drawing completely.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
• The essentials of what is done can easily be lost in the technical details of
how it is done.
Basic Structure of a C program
1. Document section
2. Preprocessor/link Section
3. Definition section
4. Global declaration section
5. Function declaration section
6. Main function
7. User-defined function section
C –Program structure
Explaining the Program Structure
1. Documentation Section - It is the section in which you can give comments to make
the program more interactive. The compiler won’t compile this and hence this portion
would not be displayed on the output screen.

2. Preprocessor directives Section - This section involves the use of header with
extension .h which contains C function declarations and macro definitions to be shared
between several source files.

3. Definition section - This section involves the variable definition and declaration in C.

4. Global declaration Section - This section is used to define the global variables to be
used in the programs, that means you can use these variables throughout the program.
Cont..
5. Function prototype declaration section - This section gives the
information about a function that includes, the data type or the return type, the
parameters passed or the arguments.

6. Main function - It is the major section from where the execution of the
program begins. The main section involves the declaration and executable
section.

7. User-defined function section - When you want to define your function


that fulfills a particular requirement, you can define them in this section.
First C Program
• Before we study the basic building blocks of the C programming language, let us look at a bare
minimum C program structure so that we can take it as a reference in the upcoming sections.

• A C program basically consists of the following parts −


• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments

• Let us look at a simple code that would print the words "Hello World"
Hello World !
Understanding your first program
• The first line and second line of the program - is a preprocessor
command, which tells a C compiler to include stdio.h and stdlib.h
files before going to actual compilation. These header files
contain information about printf, scanf and other in-built C
functions.
Cont..
• The next line int main() is the main function. This is where the program execution
begins. All valid C programs must contain the main() function.

• All program statements included between the braces(curly brackets) are taken as
part of the main routine by the system

• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. Such lines are called comments in the program.
Cont..
• printf(...) is function available in C libraries which causes the
message "Hello, World!" to be displayed on the screen. It simply
prints or displays arguments passed to it.

• The printf() is a library function to send formatted output to the


screen. The function prints the string inside quotations.

• To use printf() in our program, we need to include stdio.h header


file using the #include <stdio.h> statement.
Cont…
• The last two characters in the string, namely the backslash (\) and the letter n, are
known collectively as the newline character. A newline character (Example Of
escape sequence)tells the system to do precisely what its name implies— that is,
go to a new line. Any characters to be printed after the newline character then
appear on the next line of the display.

• Semicolons - In a C program, the semicolon is a statement terminator. That is,


each individual statement must be ended with a semicolon. It indicates the end of
one logical entity.
Cont…
• The return 0; statement inside the main() function is the "Exit status"
of the program. It's optional. You can use any integer here. Zero is
used by convention to indicate that the program completed
successfully—that is, without running into any errors.

• NB.C Language is case sensitive - lowercase and uppercase letters are


distinct
Exp
• Write a program that prints the following text at the terminal.
In C, lowercase letters are significant.
main is where program execution begins.
Opening and closing braces enclose program statements in a routine.
All program statements must be terminated by a semicolon.
• What output would you expect from the following programs?
Variables and Datatypes
• A variable is defined as the reserved memory space(container) which stores a
value of a definite datatype.
• The value of a variable is not constant, instead it allows changes. They store the
value which you assign to them which can be numbers, characters, strings of
text etc.
• In C, a variable must be declared before it can be used.
• Variables can be declared at the start of any block of code.
Cont..
• A declaration begins with the data type, followed by the name of one or more
variables. That is:
i. datatype variable; or
ii. datatype variable1,variable2,….variablen; (where there are n variables)
• For example, int high, low, results[20]
• Declarations can be spread out, allowing space for an explanatory comment.
• Variables can also be initialized when they are declared. This is done by adding
an equals sign and the required value after the declaration.
• int high = 250; /* Maximum Temperature */
• int low = -40; /* Minimum Temperature */
• int results[20]; /* Series of temperature readings */
Modify Variables value at the Middle of a
Program
Format specifiers
• Format specifiers are used in C for input and output purposes. A Format Specifier tells
the printf function that we would like to print out a special type of data that is not just
plain text.
• Act as Placeholders for the data to be printed.
• We can use multiple format specifiers in a single statement
Format
Specifier Data Type description Syntax
%d int To print the integer value printf("%d",<int_variable>);
%f float To print the floating number printf("%f",<float_variable>);

%lf double To print the double precision floating number printf("%lf",<double_variable>);


or long float
%c char To print the character value printf("%c",<char_variable>);
Escape Sequences

Escape sequence Description Example Output


\n New line printf("Hello \n Hello
World"); World

\t Horizontal tab printf("Hello \t Hello World


World");

\' Single quote printf("Hello \'World\' Hello 'World'


");

\" Double quote printf("Hello \"World\" Hello "World"


");

\\ Backslash printf("Hello Hello \World


\\World");
Rules For Declaring Variables
• A Variable can have alphabets, digits, and underscore
• A variable name can start with the alphabet, and underscore only. It cannot
start with a digit.
• No whitespace is allowed within the variable name
• A variable name must not be any reserved word or keyword, E.g. int, float,
etc..
• Note: C Language is case sensitive - lowercase and uppercase letters are
distinct
Valid & Invalid Variables
• Valid Variable Names • Invalid Variable Names
• a; • 23
• _ab; • a b;
• a30; • Long
• age_*
• age • +age
• Age • sum$value
• pieceFlag
• 3Spencer
• J5x7
• Number_of_moves • int
DATATYPES in C
• In Programming we deal with a lot of data. We are going to be
storing all sorts of information. The type of data to represent this
information is what we are calling the data type. The Data type
can be defined as a set of value with predefined
characteristics. data types are used to declare variables,
constants, arrays, pointers, and functions. There are different
types of data we can work with in a program.
• Data types in the c programming language are used to specify what
kind of value can be stored in a variable. The memory size and type
of the value of a variable are determined by the variable data type.
Cont..
In a c program, each variable or constant or array must have a data type and this
data type specifies how much memory is to be allocated and what type of values
are to be stored in that variable or constant or array.
In the c programming language, data types are classified as follows...

1.Primary data types (Basic data types OR Predefined data types)


2.Derived data types (Secondary data types OR User-defined data types)
3.Enumeration data types
4.Void data type
Basic Data types
Data Type Description Example Size
int To store an integer value -5, -1, 0, 4 4 bytes
float To store a floating point 10.3, 13.56, -2.45, 1.414 4 bytes
number
or number with fractional parts

double Same as float but bigger space 123456.34534, - 8 bytes


to store number 234345345.244466 etc.

char To store a single character 'a', 'b', 'c', '*', '#' 1 byte

void It's an incomplete datatype. void fun() (i.e..) fun() will not 1 byte
Mainly used in functions. return anything
We will discuss about it in later int main(void) (i.e.) main will
lessons not take argument
Cont…
• Enumerated data type
• An enumerated data type is a user-defined data type that consists of integer constants
and each integer constant is given a name. The keyword "enum" is used to define
the enumerated data type.
• Derived data types
• Derived data types are user-defined data types. The derived data types are also called
as user-defined data types or secondary data types. In the c programming language,
the derived data types are created using the following concepts...
• Arrays
• Structures
• Unions
• Enumeration
C Tokens
Every C program is a collection of instructions and every instruction is a collection of
some individual units. Every smallest individual unit of a c program is called token.
Every instruction in a c program is a collection of tokens. Tokens are used to construct
c programs and they are said to be the basic building blocks of a c program.
In a c program tokens may contain the following...
1.Keywords
2.Constants
3.Strings
4.Special Symbols
5.Identifiers
6.Operators
NB. In a C program, a collection of all the keywords, identifiers,
operators, special symbols, constants, strings, and data values are called
tokens.
Keywords
Are defined as those variables which have a special meaning(used to construct C program
instructions) and are predefined in the C libraries.
They are predefined, you cannot rename, redefine or reprogram.You cannot use them as
variable names.You cannot change the functionality. Keywords are also known as reserved
words in C programming language. Whenever C compiler come across a keyword,
automatically it understands its meaning.
Properties of Keywords
1.All the keywords in C programming language are defined as
lowercase letters so they must be used only in lowercase letters
2.Every keyword has a specific meaning, users can not change that
meaning.
3.Keywords can not be used as user-defined names like variable,
functions, arrays, pointers, etc...
4.Every keyword in C programming language represents something or
specifies some kind of action to be performed by the compiler.
Constants
Constants or Literals are like variables, but the difference is that, the values of
the constants are fixed. Once declared, they cannot be changed
• Syntax
• Const data_type VARIABLE_NAME; or
• const data_type *VARIABLE_NAME;
• Data_type const VARIABLE_NAME;
• Variables Once defined, you can change their values, But if declared with const
Keyword you cannot change their values. Constants in C are the fixed values
that are used in a program, and its value remains the same during the entire
execution of the program.
• It is considered best practice to define constants using only upper-case names.
Example

Putting const either before or after the type is possible and allowed.
In C programming language, a constant can be of any data type like
integer, floating-point, character, string and double, etc.,
Strings
• Strings are defined as a collection of characters defined in form of an array and
end with null character which describe the end of the string to the compiler
• They are character type arrays
• Syntax
• Char string_name[Length_of_the_String]
• Arrays and strings are second-class citizens in C; they do not support the assignment
operator once it is declared. For example,
Special Symbols/ Characters
• Special Characters are symbols (single characters or sequences of characters)
that have a “special” built-in meaning in the language and typically cannot be
used in identifiers.
• They are used in particular segments of code.
• Examples
• %,&,(),{}
List of Special Characters in C
Special Character Description
, (comma) { (opening curly bracket)
. (period) } (closing curly bracket)
; (semi-colon) [ (left bracket)
: (colon) ] (right bracket)
? (question mark) ( (opening left parenthesis)
‘ (apostrophe) ) (closing right parenthesis)
” (double quotation mark) & (ampersand)
! (exclamation mark) ^ (caret)
|(vertical bar) + (addition)
/ (forward slash) – (subtraction)
\ (backward slash) * (multiplication)
~ (tilde) / (division)
_ (underscore) > (greater than or closing angle bracket)

$ (dollar sign) < (less than or opening angle bracket)


% (percentage sign) # (hash sign)
Identifiers
• Identifiers are defined as names that we declare in a program in order to name
a value, variable, function, array e.tc

• Here, money and accountBalance are identifiers.


• Also remember, identifier names must be different from keywords.You cannot
use int as an identifier because int is a keyword.
Rules For Identifiers
1. A valid identifier can have letters (both uppercase and lowercase letters),
digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore.
3. You cannot use keywords like int, while etc. as identifiers.
4. You cannot include a blank space between the name of an identifier(use the
underscore_)
5. There is no rule on how long an identifier can be. However, you may run into
problems in some compilers if the identifier is longer than 31 characters.
Note: You can choose any name as an identifier if you follow the above rule, however, give
meaningful names to identifiers that make sense.
Valid & Invalid Identifiers
• Valid Variable Names • Invalid Variable Names
• a; • 23
• _ab; • a b;
• a30; • Long
• age_*
• age
• +age
• Age • sum$value
• pieceFlag
• 3Spencer
• J5x7
• Number_of_moves • int
Operators
• C offers us a wide variety of operators that we can use to operate on data
and perform various operations.
• An operator is a symbol that operates on a value(operand) or a variable. An
operand is a value on which any operator works.
• For example, when we say 4+5, here, numbers 4 and 5 are operands
whereas + is an operator.
• Different operators work with different numbers of operands like
the + operator requires two operands or values.
Examples of Operators
1. Arithmetic Operators
2. Increment/ Decrement Operators
3. Assignment Operators
4. Relational Operators/Comparison Operators
5. Logical Operators
6. Bitwise Operators
Working with Arithmetic Expressions
• In C, just as in virtually all programming languages, the plus sign (+) is used to
add two values, the minus sign (–) is used to subtract two values, the asterisk (*)
is used to multiply two values, and the slash (/) is used to divide two values.
These operators are known as binary arithmetic operators because they operate
on two values or terms Arithmetic Operation Example
Operators
+ Addition 10 + 2 = 12
– Subtraction 10 – 2 = 8
* Multiplication 10 * 2 = 20
/ Division 10 / 2 = 5
10 % 2 = 0 (Here
Modulus – It returns the
% remainder is zero). If it is
remainder after the division
10 % 3 then it will be 1.
Cont..
• For this C example program, We are using two variables a and b and their
values are 7 and 3. We are going to use these two variables to show the
problems we generally face while performing arithmetic operations on int and
float datatype.
Cont…
• Within the above arithmetic operators in C example, If you notice the result,
we got two different results for the same calculation. Because for the first
result, both a and b are integers and the output is also an integer (integerdiv).
• So the compiler neglects the term after the decimal point and shows answer 2
instead of 2.3333 and a % b is 1 because the remainder is 1.
• Next, we changed the output data type to float (floatdiv), and also converted
the result to float to get our desired result. Please be careful, while using the
division Operator (Type casting plays a major role here)
• Type Casting or Type Conversion is converting one datatype into another
Cont.
• Let us use two variables a and b and their values are 12 and 3.
• We are going to use these two variables to perform various arithmetic operations
present in Programming Language
Cont…
• NOTE: When we are using division (/) operator the result will completely
depend upon the data type it belongs to.
• For example, if the data type is an integer then division arithmetic operators in
c will produce the integer value by rounding the value (9 / 4 = 2).

• If you want the correct result then change the data type to float. Don’t get
confused, let’s see one more example for better understanding
Exp.
Exe.
1. Write a C program that prints the area and Perimeter of a Square and a
Rectangle,
2. Write a C program that prints volume of cube, cuboid, sphere, cone,
The Scanf Function
• When the c program needs to get input from the user, we should
use scanf function.
• To get input from the user, we should instruct the scanf function the following
details,
i. Specify the format i.e.. which data type we are going to get from the user.
ii. Give the variable address where we want to store the value.
• Syntax
• scanf("<format specifier>" , <address of variable>);
• We use the ampersand (&) operator, to get the address of a variable. In C, we
will refer & as address of operator.
cont..
• N.B :In scanf, we must give the address of a variable not variable name.

%x is used to print the address in hexadecimal format.


Sample Program
Program to calculate Area and Circumference
based on user input
Program to calculate Area of a Equilateral Tri.

• In order to calculate the area of equilateral triangle, we must know the side of
the triangle. This program would prompt user to enter the side of the
equilateral triangle and based on the value, it would calculate the area.

• Formula used in the program:


• Area = sqrt(3)/4 * side * side
• Here sqrt refers the “square root”, this is a predefined function of “math.h”
header file. In order to use this function, we have included the “math.h” header
file in the program.
Program - Equilateral Triangle
Program to calculate simple interest
Exercise
1. Write a C program to perform input/output of all basic data types.
2. Write a C program to enter two numbers and find their sum.
3. Write a C program to enter two numbers and perform all arithmetic operations.
4. Write a C program to enter length and breadth of a rectangle and find its perimeter.
5. Write a C program to enter length and breadth of a rectangle and find its area.
6. Write a C program to enter radius of a circle and find its diameter, circumference and area.
7. Write a C program to enter length in centimeter and convert it into meter and kilometer.
8. Write a C program to enter temperature in Celsius and convert it into Fahrenheit.
9. Write a C program to enter temperature in Fahrenheit and convert to Celsius
10.Write a C program to convert days into years, weeks and days.
11.Write a C program to find power of any number x ^ y.
12.Write a C program to enter any number and calculate its square root.
13.Write a C program to enter two angles of a triangle and find the third angle.
14.Write a C program to enter base and height of a triangle and find its area.
15.Write a C program to calculate area of an equilateral triangle.
16.Write a C program to enter marks of five subjects and calculate total & average
17.Write a C program to enter P,T, R and calculate Simple Interest.
18.Write a C program to enter P,T, R and calculate Compound Interest.
Exercise
• Identify the syntactic errors in the following program. Then type in and run
the corrected program to ensure you have correctly identified all the mistakes

• Write a program to evaluate the polynomial shown here: 3x3 - 5x2 + 6 for x =
2.55
Increment/ Decrement Operators
• C programming has two operators increment ++ and decrement -- to change
the value of an operand (constant or variable) by 1.
• Increment ++ increases the value by 1 whereas decrement -- decreases the
value by 1. These two operators are unary operators, meaning they only operate
on a single operand.
• Syntax:
• Increment operator: ++var_name; (or) var_name++;
• Decrement operator: – -var_name; (or) var_name – -;
• Example:
• Increment operator : ++ i ; i ++ ;
• Decrement operator : – – i ; i – – ;
Example
Assignment Operators
• Assignment Operators are used to assign
the values for the variables in C Programming Language.
• The most common assignment operator is =
e.g. int a=10
Assignment Operators

Operator Example Same as


= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Relational Operators/ Comparison Operators
• Relational Operator is a programming language construct or operator that tests
or defines relation between two entities.
• Example - Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not, if (A == B) is not true.
yes then condition becomes true
!= Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the value (A < B) is true
of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
Relational Operators
Logical Operators
• These operators are used to perform logical operations on the given
expressions.
• An expression containing logical operator returns either 0 or 1 depending upon
whether expression results true or false. Logical operators are commonly used
in decision making in C programming.
• These are the 3 basic logical operators in C Language
• Logical AND(&&)
• Logical OR(||)
• Logical NOT(!)
Logical Operators
Operator Meaning Example
If c = 5 and d = 2 then,
Logical AND. True only
&& expression ((c==5) &&
if all operands are true
(d>5)) equals to 0.
Logical OR. True only if If c = 5 and d = 2 then,
|| either one operand is expression ((c==5) ||
true (d>5)) equals to 1.
Logical NOT. True only If c = 5 then, expression
!
if the operand is 0 !(c==5) equals to 0.
Working with Logical Operators
Explanation of logical operator program

• (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1


(true).
• (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
• (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
• (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0
(false).
• !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1
(true).
• !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
Decision and Loop Control Structures.
• Control structures represent the forms by which statements in a program are
executed.
• Three elements give us the power to implement solutions to extremely
complex problems.
1. Sequence
2. Selection or Decision structure
3. Iteration or Looping structure
• Sequence:- is the order in which instructions occur and are processed.
Instructions are executed one after another as they are read
• Selection:- The selection control structure allows one set of statements to be
executed if a condition is true and another set of actions to be executed if a
condition is false. Selection determines which path a program takes when it is
running.

• Looping /Iteration is the repeated execution of a section of code when a


program is running until some condition is satisfied.
Selection/Decision Structure
• Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to
be false.
• C programming language provides the following types of decision making
statements.
a. if statement
b. if...else statement
c. if...else if...else Statement
d. switch statement
if statement
• The syntax of an if statement in C programming language is

• How if statement works?


• The if statement evaluates the test expression inside the parenthesis ().
• If the test expression is evaluated to true, statements inside the body of if are executed.
• If the test expression is evaluated to false, statements inside the body of if are not
executed.
Examples
if...else Statement
• The if statement may have an optional else block. The syntax of the if…else
statement is:

• How if...else statement works?


• If the test expression is evaluated to true,
• statements inside the body of if are executed.
• statements inside the body of else are skipped from execution.
• If the test expression is evaluated to false,
• statements inside the body of else are executed
• statements inside the body of if are skipped from execution.
Example
The if...else if...else Statement(if...else
Ladder)
• The if...else statement executes two different codes depending upon whether the
condition is true or false. Sometimes, a choice has to be made from more than 2
possibilities(this is where if…else if…else comes in).
• The if...else ladder allows you to check between multiple conditions and execute
different statements.
if (Condition1){
//statement(s)
}
else if(condition2){
//statement(s)
}
.
.
.
else{
//statement(s)
}
Example
Nested if...else
• It is possible to include an if...else statement inside the body of another
if...else statement.

• The program given below relates two integers using either <, > and = similar
to the if...else ladder's example. However, we will use a nested if...else
statement to solve this problem.
switch statement
• A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is
checked for each switch case.

• You can do the same thing with the if...else…if ladder. However, the syntax of
the switch statement is much easier to read and write.
Syntax of Switch…Case
How does the switch statement work?
• The expression(condition) is evaluated once and compared with the values of
each case label.
• If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2,
statements after case constant2: are executed until break is encountered.
• If there is no match, the default statements are executed.
• If we do not use break, all statements after the matching label are executed.
• By the way, the default clause inside the switch statement is optional.
Examples
Exercise to do
1. A retail shop offers discounts to its customers according to the following
rules:
• Purchase Amount >= Ksh. 10,000 - Give 10% discount on the amount.
• Ksh. 5, 000 <= Purchase Amount < Ksh. 10,000 - Give 5% discount on the amount.
• Ksh. 3, 000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
• 0 > Purchase Amount < Ksh. 3,000 - Pay full amount.
Write a program that asks for the customer’s purchase amount, then uses if statements to recommend
the appropriate payable amount. The program should cater for negative purchase amounts and display
the payable amount in each case.
2. Write a program that computes the area of a circle, rectangle or triangle
using a switch statement.
Iteration/Looping
• In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.
• There may be a situation, when you need to execute a block of code several
number of times.
• A loop statement allows us to execute a statement or group of statements
multiple times.
• C programming language provides the following types of loops to handle
looping requirements: For Loop, While Loop & do…while loop
Flow Diagram
For Loop
• A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
• The syntax of the for loop is:
for (initialization; condition; increment/decrement)
{
Statement(s) inside the body of loop
}
How it works
• The initialization statement is executed only once.
• Then, the condition is evaluated. If the condition is evaluated to false, the for
loop is terminated.
• However, if the condition(test expression) is evaluated to true, statements
inside the body of the for loop are executed, and the increment expression is
updated.
• Again the condition (test expression) is evaluated.
• This process goes on until the test expression is false. When the condition is
false, the loop terminates.
for loop flow diagram & Examples
Factorial of a Number Using For Loop
Working:
•First the computer reads the number to find the
factorial of the number from the user.
•Then using for loop the value of ‘i’ is multiplied
with the value of ‘f’.
•The loop continues till the value of ‘num’.
•Finally the factorial value of the given number is
printed.
Step by Step working of the above Program Code:
• Let us assume that the number entered by the user f=f*i (f=6*4) So f=24
is 4. i++ (i=i+1) So i=5
1. It assigns the value of num=4 , i=1 , f=1
5. i<=n (5<=4) , for loop condition is false.
2. Then the loop continues till the condition of the for It comes out of the for loop.
loop is false.
1. i<=num (1<=4) , for loop condition is true. 3. Finally it prints as given below
f=f*i (f=1*1) So f=1 • The Factorial of 4 is 24
i++ (i=i+1) So i=2 4. Thus the program execution is completed.
2. i<=num (2<=4) , for loop condition is true.
f=f*i (f=1*2) So f=2
i++ (i=i+1) So i=3
3. i<=num (3<=4) , for loop condition is true.
f=f*i (f=2*3) So f=6
i++ (i=i+1) So i=4
4. i<=num (4<=4) , for loop condition is true.
While Loop
• A while loop statement in C programming language
repeatedly executes a target statement as long as a
given condition is true.
• The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
How it Works
• The while loop evaluates the condition inside the parentheses ().
• If condition is true, statements inside the body of while loop are executed.
Then, condition is evaluated again.
• The process goes on until condition is evaluated to false.
• If condition is false, the loop terminates (ends).
Example
Here, we have initialized i to 1.

When i = 1, the test expression i <= 5 is true. Hence, the body of the
while loop is executed. This prints 1 on the screen and the value of i is
increased to 2.
Now, i = 2, the test expression i <= 5 is again true. The body of the
while loop is executed again. This prints 2 on the screen and the value of
i is increased to 3.
This process goes on until i becomes 6. Then, the test expression i <= 5
will be false and the loop terminates.
do...while loop in C
• Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming language checks its condition at the bottom of the
loop.
• A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
• Syntax The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}
while( condition );
• Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
• If the condition is true, the flow of control jumps back up to do, and the statement(s)
in the loop execute again. This process repeats until the given condition becomes false
Flow Diagram & Example
While vs Do…While Loop Examples
• Note: While loop is executed only when given condition is true. Whereas, do-
while loop is executed for first time irrespective of the condition. After
executing do…while loop for first time, then condition is checked.
Functions
• A function is a self-contained program segment that carries out some specific
well -defined task. Every C program must consists at least one function.
• One of these functions must be called main(the default function).
• Execution of the program will always begin by carrying out the instructions in
main. Additional functions will be subordinate to main, and perhaps to one
another.
• If a program contains multiple functions, their definitions may appear in any
order, though they must be independent of one another. That is, one function
definition cannot be embedded within another.
Why Use Functions
• The use of programmer-defined functions allows a large program to be broken
down to a number of smaller, self-contained components each of which has
some unique identifiable purpose. Thus a C program can be modularized
through the intelligent use of functions.
• Suppose, you need to create a program to create a circle and color it.You can
create two functions to solve this problem:
• create a circle function
• create a color function
• Dividing a complex problem into smaller chunks makes our program easy to
understand and reuse.
Types of Function
• There are two types of function in C programming:
• Standard library functions
• User-defined functions
Standard library functions
• The standard library functions are built-in functions in C programming. These are mostly
input/output functions, character and string manipulation functions, and math functions.
Prototypes are defined for you by the compiler writer for all of the functions that are included with
your compiler.
For example,
• The printf() is a standard library function to send formatted output to the screen (display output on
the screen). This function is defined in the stdio.h header file. Hence, to use the printf()function, we
need to include the stdio.h header file using #include <stdio.h>.
• The sqrt() function calculates the square root of a number. The function is defined in the math.h
header file.
User – defined function
• This is a function created and customized by a programmer for use within a given
program.
• How user-defined function works? The execution of a C program begins from
the main() function.
When the compiler
encounters functionName();, control of the
program jumps to
void functionName()
And, the compiler starts executing the
codes inside functionName().
The control of the program jumps back to
the main() function once code inside the
function definition is executed.
Advantages of functions
• They reduces the complexity of a program and gives it a modular structure.
This makes a program easier to understand, maintain and debug.
• Eliminates Redundancy by allowing Reusable codes that can be used in other
programs.
• Reduction in Program Size: A large program can be divided into smaller
modules. Hence, a large project can be divided among many programmers.
Function Definition
• The general form of a function definition in C programming language is as follows:
return_type function_name( datatype paramter1 , datatype paramter2 , datatype paramter3..);
{
//body of the function
}
• A function definition in C programming language consists of a function header and a function body.
• Here are all the parts of a function:
1. Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
2. Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
3. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. Parameters are optional; that is, a
function may contain no parameters.
4. Function Body: The function body contains a collection of statements that define what the function does.
Function Prototype
• A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function body.
• A function prototype gives information to the compiler that the function may
later be used in the program.
• Syntax of function prototype
return_type function_name( datatype paramter1 , datatype paramter2,...);
Example: int addNumbers(int a, int b);
Function Prototype Cont...
• In the above example,
• int addNumbers(int a, int b); is the function prototype which provides the following
information to the compiler:
• name of the function is addNumbers()
• return type of the function is int
• two parameters or arguments of type int are passed to the function

Note: The function prototype is not needed if the user-defined function is defined before
the main() function.
Example – Use a function to write a program that adds two integers
Calling a function
• While creating a C function, you give a definition of what the function has to
do. To use a function, you will have to call that function to perform the defined
task.
• When a program calls a function, Control of the program is transferred to the
user-defined function by calling it.
• Syntax of function call
• Function_name(argument1, argument2, ...);
• In the above example, the function call is made using addNumbers(n1, n2);
statement inside the main() function.
Passing arguments to a function
• In programming, argument refers to the variable passed to the function. In the
above example, two variables n1 and n2 are passed during the function call.
• The parameters a and b accepts the passed arguments in the function
definition. These arguments are called formal parameters of the function.
• The datatype of arguments passed to a function and the formal parameters
must match, otherwise, the compiler will throw an error.
• If n1 is of char type, a also should be of char type. If n2 is of float type, variable
b also should be of float type.
How to pass arguments to a function
Return Statement
• The return statement terminates the execution of a function and returns a value to
the calling function. The program control is transferred to the calling function after
the return statement.
• In the above example, the value of the result variable is returned to the main
function. The sum variable in the main() function is assigned this value.
• Syntax of return statement
return (expression);
• For example,
• return a;
• return (a+b);
• The type of value returned from the function and the return type specified in the
function prototype and function definition must match.
Return statement Cont…
Examples
Function Returning Max between 2 numbers
Call By Value
• The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the
argument.
• By default, C programming language uses call by value method to pass
arguments. In general, this means that code within a function cannot alter the
arguments used to call the function.
• Consider the function swap() definition as follows.
Swap Numbers: Call by Value
Output
After Compiling we get the following result.

It shows that there are no changes in the values, though


they had been changed inside the function. This is because
In call by value, original value is not modified.
Call by Reference
• The call by reference method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
• To pass the value by reference, argument pointers are passed to the functions
just like any other value. So accordingly you need to declare the function
parameters as pointer types as in the following function swap(), which
exchanges the values of the two integer variables pointed to by its arguments.
Swap Numbers – Call by Reference
Output
Difference between call by value and call
by reference in c
No. Call by value Call by reference
1 A copy of value is passed to the function An address of value is passed to the
function

2 Changes made inside the function is not reflected on other Changes made inside the function is
functions reflected outside the function also

3 Actual and formal arguments will be created in different Actual and formal arguments will be
memory location created in same memory location
C Recursion
• A function that calls itself is known as a recursive function. And, this technique
is known as recursion.
Recursion Cont…
• The recursion continues until some condition is met to prevent it.
• To prevent infinite recursion, if...else statement (or similar approach) can be
used where one branch makes the recursive call, and other doesn’t.
• Recursion makes program elegant. However, if performance is vital, use loops
instead as recursion is usually much slower.
• That being said, recursion is an important concept. It is frequently used in data
structure and algorithms. For example, it is common to use recursion in
problems such as tree traversal.
Variables scope
• When you define a variable in a C program, depending on where you declare
it, it will have a different scope.
• A scope is a region of the program, and the scope of variables refers to the area
of the program where the variables can be accessed after its declaration.
• This means that it will be available in some places, but not in others. The
position determines 2 types of variables:
1. Local variables
2. Global variables
Local Variables
• Local variables are declared at the inside of a code block or a function and are
only accessible from within the function, and when the function ends they stop
their existence. They are cleared from the memory (with some exceptions).
Global Variable
• A variable declared outside of a code block or a function is a global variable.
They are declared in most of the cases, on the top of the C program.
• Global variables are accessible from any function of the program, and they are
available for the whole execution of the program, until it ends. i.e.. They have
scope across the entire program

You might also like