Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views117 pages

CProgramming Bridgecourse Final

The document is a bridge course on the basics of C programming, covering its history, algorithms, flowcharts, pseudo code, structured programming, and various programming concepts. It highlights the popularity of C due to its reliability, simplicity, and versatility in applications such as operating systems and compilers. Additionally, it discusses structured programming principles, advantages, disadvantages, and the character set used in C language.

Uploaded by

reyaramakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views117 pages

CProgramming Bridgecourse Final

The document is a bridge course on the basics of C programming, covering its history, algorithms, flowcharts, pseudo code, structured programming, and various programming concepts. It highlights the popularity of C due to its reliability, simplicity, and versatility in applications such as operating systems and compilers. Additionally, it discusses structured programming principles, advantages, disadvantages, and the character set used in C language.

Uploaded by

reyaramakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 117

Bridge Course - Basics of C

Programming

Presented By,

Ms. Sandhya C,
Assistant Professor
Department of Computer Applications
SNGCE

1
Table of Contents
History of C
Algorithm and Flow chart
 Pseudo code
Structured Programming
Introduction to C Language
Operators and expressions
 Data input and output
 Control statements
 Loops

2
INTRODUCTION

The C programming language is a structure oriented


programming language, developed at Bell Laboratories
in 1972 by Dennis Ritchie

C programming language features were derived from


an earlier language called “B” (Basic Combined
Programming Language – BCPL)

C language was invented for implementing UNIX


operating system

3
Taxonomy of C Language

4
Why “C” is popular ?
Reliable
 Simple and easy to use
Small, block-structured programming language
Portable language, which means that C
programs written on one system can be run on
other systems with little or no modification.
Extremely flexible language—particularly if it is
to be used to write operating systems
High level language

5
Applications
Database systems
 Graphics packages
 Word processors
 Spreadsheets
 Operating system development
Compilers and Assemblers
 Network drivers
 Interpreters
6
ALGORITHM
 An algorithm is a step-by-step method to solve problems. It
includes a set of rules / instructions to be carried out by a
computer program

Example: Add two numbers and display the result.

Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values for num1, num2.
Step 4: Add num1 and num2 and assign the result to a variable
sum.
Step 5: Display sum
Step 6: Stop

7
FLOWCHART
Most widely used graphical representation of an
algorithm and procedural design workflows
 It uses various symbols to show the operations
and decisions to be followed in a program. It flows
in sequential order.
Example: Add two numbers and display the result.

8
FLOWCHART [contd..]

9
FLOWCHART [contd..]
Ex: Add two numbers and display the
result

10
Difference between Algorithm and
Flowchart

11
Pseudo code
 Pseudo code is a method of representing
logic in programming that is independent
of any programming language
 It uses natural language rather than
the rigid syntax of programming
languages since it is intended to be easily
understood by humans

12
Example for Pseudo code – add two
numbers

Start Program
Input two numbers a and b
sum=a+b
Print sum
End Program

13
Algorithm Pseudo code
It is defined as a sequence of It can be understood as one
well-defined steps. These of the methods that helps in
steps provide a solution/ a the representation of an
way to solve a problem in algorithm.
hand.

It is a systematic, and a It is a simpler version of


logical approach, where the coding in a programming
procedure is defined step- language.
wise
Algorithms can be It is written in plain English,
represented using natural and uses short phrases to
language, flowchart and so write the functionalities that
on. s specific line of code would
do.

This solution would be There is no specific syntax


translated to machine code, which is actually present in
which is then executed by other programming
the system to give the languages. This means it
14 relevant output. can't be executed on a
computer.
Algorithm Pseudo code
It is easy to debug. It is relatively
difficult to debug.

Its construction is Its construction is


tough. easy.
There are no rules It has certain rules
to follow while to follow while
constructing it. constructing it.

15
Structured Programming
Structured programming is a programming
paradigm aimed at improving the clarity, quality,
and development time of a computer program
Also called Modular Programming and
Procedural
Programming
 The mechanisms that allow us to control the
flow of execution are called control structures
There are three main categories of control
structures:
Sequence
Selection
Iteration

16
Structured Programming
[contd..]
A sequence is a series of actions that is
completed in a specific order. Action 1 is
performed, then Action 2, then Action 3,
etc., until all of the actions in the sequence
have been carried out

17
Structured Programming
[contd..]
Selection : Instead of following a specific
order of events, they ask a question in
order to figure out which path to take
next

18
Structured Programming
[contd..]
Iteration or Loop : Like selections,
loops ask questions. However, the
difference is that they ask the same
question over and over and over again,
until a certain task is complete.

19
Why C is called Structured
Programming

To solve a large problem, C programming


language divides the problem into smaller
structural blocks each of which handles a
particular responsibility
 C uses structured control flow constructs,
such as selection (if/then/else) and
repetition (while and for) statements,
along with block structures and
subroutines

20
Different Structural blocks in
C
Sequence: Programs are composed of a
sequence of instructions that are executed in
a sequential order. This means that the
instructions are executed one after another,
from top to bottom, unless control flow
statements alter the execution order
Selection: Structured programming includes
conditional statements to control the flow of
execution based on certain conditions.
Common selection statements include "if-
else" and "switch-case." These statements
allow the program to make decisions and
21 choose different paths of execution based on
Different Structural blocks in
C [contd..]
Iteration: Iteration, or looping, is another crucial
element of structured programming. It allows the
repetition of a sequence of instructions based on a
condition. Common loop structures include "for,"
"while," and "do-while" loops. Loops enable the
execution of a block of code repeatedly until a
specified condition is met.
Subroutines or Functions: Structured
programming promotes the use of subroutines or
functions to break down complex programs into
smaller, manageable pieces of code. Functions
encapsulate a specific set of instructions that
perform a particular task. They can be reused
22
multiple times, enhancing code modularity and
reusability.
Different Structural blocks in
C [contd..]
Single Entry and Exit Points: In structured
programming, each subroutine or function
typically has a single entry point and a single
exit point. This principle aims to ensure clear
control flow and avoid complex branching or
jumps within the code, enhancing program
readability and maintainability.

23
Advantages – Structured
Programming
Simple and easy to understand and implement
Programmers do not require to know complex
design concepts to start a new program
Readability: Code is organized into smaller,
coherent structures, making it easier to
understand and follow by programmers
Maintainability: The modular design allows for
easier maintenance, debugging, and updates
without affecting the entire program
Reusability: Functions and subroutines enable
code reuse, reducing redundancy and saving
development time.
24
Advantages – Structured
Programming[contd..]
Efficiency: Utilization of structured control flow
constructs, like loops, leads to optimized and
faster-performing programs
Top-Down Design: Facilitates the breakdown of
complex problems into manageable subproblems,
aiding in a systematic approach to software
development.
Testing: Modular code is conducive to efficient
unit testing, enabling developers to isolate and
verify specific functionality.
Debugging: Smaller, well-defined code blocks
simplify the process of identifying and fixing
errors and issues.
25
Advantages – Structured
Programming[contd..]
Adaptability: Changes in requirements can be
accommodated more easily through well-
structured code blocks.
Code Optimization: The structured design
encourages efficient algorithm implementation
and optimization.
Portability: Well-structured programs are often
more portable and can be adapted to different
environments and platforms with minimal
changes
Scalability: The structured approach provides a
solid foundation for expanding and scaling
software as the project grows.
26
Advantages – Structured
Programming[contd..]
Reduced Complexity: Structured programming
breaks down complex tasks into simpler, manageable
components, reducing cognitive load for developers.
Code Documentation: Clear organization facilitates
better documentation, making it easier to maintain
and understand the codebase over time.
Learning: It serves as an excellent introduction to
programming concepts for beginners due to its
systematic and organized approach.
Standardization: Promotes the adoption of
consistent coding practices and style, enhancing
overall code quality.
Enhanced Software Quality: The advantages of
structured programming lead to higher-quality
27
software with fewer bugs and issues.
Disadvantages
Lack of Object-Oriented Features: Structured
programming lacks the powerful object-oriented
features that provide additional benefits for
software development. Data and methods and not
be bind together in a module.Polymorphism and
inheritance are not available
Code Duplication: Without careful design, code
duplication may occur across multiple functions or
modules, leading to maintenance issues
Overuse of Functions: Excessive use of
functions can lead to a proliferation of small,
specialized functions, making the codebase harder
to manage
28
Disadvantages [contd..]
Limited Real-time Applications: In some real-
time applications, the strict sequential execution
may not be suitable for meeting specific timing
constraints
No Direct Support for Parallelism: Structured
programming does not inherently provide
features for easy parallelization of code, which is
essential in modern multi-core processor
Inter-module Dependencies: Tightly coupled
modules may hinder code maintenance and
updates due to cascading changes

29
Disadvantages [contd..]
Performance Trade-offs: Some
structured constructs may introduce slight
performance overhead compared to lower-
level programming approaches.
Incompatibility with Specific Domains:
Certain specialized domains or specific
programming tasks might require
alternative programming paradigms,
rendering structured programming less
suitable.

30
Examples of Structured
Programming Languages
C
C++
JAVA
Python
C#
Visual Basic
PHP

31
LANGUAGE CHARACTER SET

Character Set : As every language contains a set of


characters used to construct words, statements, etc.
 C language also has a set of characters which
include alphabets, digits, and special symbols. C language
supports a total of 256 characters
C language character set contains the following set of
characters...
Alphabets (upper and lower case alphabets)
Digits (0-9)
Special Symbols -~@#$%^&*()_-+={}[];:'"/?.>,<
\ |, \t, \n, NULL

32
TOKENS

Tokens : Smallest individual element in C

33
1. Reserved words or
Keywords
Identify language entities, they have
special meanings to the compiler. C
reserved words must be typed fully
in lowercase. There are only 32
keywords available in C

34
2. Identifiers
Programmer-defined words. Needed for program
variables, functions, and other program constructs.
gross_income and city_tax are examples. Must be
unique within the same scope
Rules
1. A to Z , a to z , 0 to 9 , and the underscore “_”
2. The first character must be a letter or an
underscore
3. The length of an identifier should be less than 32
characters. Although there is no limit to the length of
an identifier, some compliers support
names/identifiers of up to the first 32 characters only.
4. There can be no embedded blanks
35 5. Reserved words cannot be used as identifiers
Valid Identifiers

 length - It contains only lowercase


alphabets
 _size - It starts with an underscore '_'.
* len_ - Contains lowercase alphabets
and an underscore.
num_2 - It starts with lowercase and
ends with a digit.

36
Identify the valid identifiers in C

 int
Num1
m n
total_sum
\@hello

37
3. Constants : A constant is a quantity
that does not change its value over a period
of time.

38
39
Primary Constants
Constants of type float, integer, and
character are known as Primary constants.
Example for Primary constants:
1, 1.23, "Scaler", 'h', etc.
Numeric Constants
Integer Constants
Integer constants are the numbers with
decimals (base 10), hexadecimal (base 16),
binary (base 2), or octal (base 8). We will
understand this better once we look into each
of the Integer constants.

40
Integer Constants
Decimal Integer
Decimal integers are the constants with base 10.
Non-zero decimal digits (1 to 9) are decimal
integers followed by zero or more decimal digits
(0 to 9 ).
Example: 255,100,69,999, etc.
Octal Integer
Octal integers are the constants with base 8. The
digit zero (0) is followed by zero or more octal
digits (0 to 7).
Example:0, 0125, 034673, 03245, etc.
Hexadecimal Integer
Hexadecimal integers are the constants with base
16. The sequence starts with 0x followed by one
or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7,
41 8, 9, a, A, b, B, c, C, d, D, e, E, f, F).
Real Constants
A constant with the
combination of positive,
negative, or zero followed by a
decimal point and the
fractional part is known as a
real constant.
Example:-89, 0.123, 45, etc.

42
Character Constants
Single Character Constants
Character constants having a single
character enclosed within the ' ' (Single
quote) are known as character constants.
Example: 's', 'c', 'a', 'l', 'e', 'r', etc.
String Constants
Character constants with various special
symbols, digits, characters, and escape
sequences enclosed within the " "(double
quotes) are known as string constants.
Example: "Scaler", "by", "InterviewBit",
"123", "number1" etc.
43
Backslash Character
Constants
Backslash characters or escape sequences
are the types of character constants. A
definite backslash character performs a
specific task

44
45
4. String Literals
characters surrounded by double
quotation marks.
format specifier for output converts the
internal representation of data to readable
characters.( %f ) for example,
City tax is 450.000000 dollars.
precede it with a backslash as
“Jim \”Mac\” MacDonald”
backslash character can be used as a
continuation character
printf(THIS PROGRAM COMPUTES \ CITY
INCOME TAX”);
46
5. Punctuators
A punctuator is used to separate or terminate a
list of elements
[ ] ( ) { } , ; : ………* #

6. Operators
result in some kind of computation or
action.
operators act on operands.

Ex: city_tax = CITY_TAX_TATE *


gross_income ;

47
Operators and Expressions
 Operator performs an operation on data.
They are classified into following −
Arithmetic operators.
Relational operators.
Logical operators.
Assignment operators.
Increment and decrement operators.
Bitwise operators.
Conditional operators.
Special operators.

48
Arithmetic Operators
 These operators are used for numerical
calculations (or) to perform arithmetic
operations like addition, subtraction etc

49
Relational Operators
 These are used for comparing two
expressions.

50
Logical Operators
 These are used to combine 2 (or) more expressions logically.
They are logical AND (&&) logical OR ( || ) and logical NOT (!)

Logical AND

51
Logical Operators
[contd..]
Logical OR

Logical NOT

52
Assignment Operators
 It assigns a value to a variable. The types
of assignment operators are −
Simple assignment
Simple assignment

53
Increment and decrement
operator
Increment operator (++)
This operator increments the value of a
variable by 1
 The two types include −
 pre increment (++ i)
 post increment (i++)
If we place the increment operator before the
operand, then it is pre-increment. Later on, the
value is first incremented and next operation is
performed on it
If we place the increment operator after the
operand, then it is post increment and the value
is incremented after the operation is performed
54
Increment Operator –
Example

55
Decrement operator
It is used to decrement the values of a
variable by 1.
The two types are −
pre decrement
post decrement
If the decrement operator is placed before the
operand, then it is called pre decrement.
Here, the value is first decremented and then,
operation is performed on it.
If the decrement operator is placed after the
operand, then it is called post decrement.
Here, the value is decremented after the
operation is performed.
56
Bitwise Operator
Bitwise operators operate on bits.

57
Left Shift
If the value is left shifted one time, then its value gets doubled.
For example, a = 10, then a<<1 = 20

58
Right Shift
If the value of a variable is right shifted one time, then its value becomes half the
original value.
For example, a = 10, then a>>1 = 5

Ones complement
It converts all ones to zeros and zeros to ones.
For example, a = 5, then ~a=2 [only if 4 bits are considered].

59
Ones complement - Example

60
Conditional operator (? :)

It is also called ternary operator.


The syntax is as follows −
exp1? exp2: exp3
if exp1 is true, exp2 is evaluated.
Otherwise, exp3 is evaluated.

61
Special operations
Some of the special operations are comma,
ampersand (&), size of operators.
Comma ( , ) − It is used as separator for
variables. For example; a=10, b=20
Address (&) − It get the address of a
variables.
Size of ( ) − It used to get the size of a
data type of a variable in bytes.

62
STRUCTURE OF A C PROGRAM
The structure of a C program is a protocol (rules) to the programmer, which he has to follow
while writing a C program. The general basic structure of C program is shown in the figure
below

63
Example:
/* This program accepts a number & displays
it to the user*/

#include <stdio.h>
void main(void)
{
int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;
}
64
#include - Preprocessing statements
 The part of the compiler which actually
gets your program from the source file is
called the preprocessor.
 #include is a pre-processor directive. It is
not really part of our program, but instead it is
an instruction to the compiler to make it do
something. It tells the C compiler to include
the contents of a file (in this case the system
file called stdio.h)
 The compiler knows it is a system file, and
therefore must be looked for in a special
place, by the fact that the filename is
enclosed in <> characters
65
#include - Preprocessing statements
[contd..]
 stdio.h is the name of the standard library
definition file for all STanDard Input and Output
functions.
 Your program will almost certainly want to send
information to the screen and read things from the
keyboard, and stdio.h is the name of the file in which
the functions that we want to use are defined.
The function we want to use is called printf. The
actual code of printf will be tied in later by the linker.
 The ".h" portion of the filename is the language
extension, which denotes an include file.

66
void main(void )
 This literally means that this means nothing. In
this case, it is referring to the function whose
name follows.
Void tells to C compiler that a given entity has no
meaning, and produces no error.
In this particular example, the only function in the
program is called main.
 A C program is typically made up of large number
of functions. Each of these is given a name by the
programmer and they refer to each other as the
program runs
C regards the name main as a special case and will
run this function first i.e. the program execution
starts from main
67
void main(void ) [contd..]

 This is a pair of brackets enclosing the


keyword void.
 It tells the compiler that the function main
has no parameters.
 A parameter to a function gives the
function something to work on.

68
{ ;} Brace and semicolon
 This is a brace (or curly bracket)
As the name implies, braces come in packs
of two - for every open brace there must be
a matching close one
 Braces allow us to group pieces of program
together, often called a block.
 A block can contain the declaration of
variable used within it, followed by a
sequence of program statements.
 In this case the braces enclose the working
parts of the function main

69
{ ;} Brace and semicolon [contd..]

 The semicolon marks the end of the list of


variable names, and also the end of that
declaration statement.
 All statements in C programs are separated by
";" (semicolon) characters.
 The ";" character is actually very important. It
tells the compiler where a given statement
ends.
If the compiler does not find one of these
characters where it expects to see one, then it
will produce an error.

70
scanf()
 In other programming languages, the printing
and reading functions are a part of the
language
In C this is not the case; instead they are
defined as standard functions which are part
of the language specification, but are not a
part of the language itself.
The standard input/output library contains a
number of functions for formatted data
transfer; the two we are going to use are scanf
(scan formatted) and printf (print formatted)

71
printf()
 The printf function is the opposite of
scanf.
 It takes text and values from within the
program and sends it out onto the screen.
 Just like scanf, it is common to all
versions of C and just like scanf, it is
described in the system file stdio.h.
 The first parameter to a printf is the
format string, which contains text, value
descriptions and formatting instructions.

72
FILES USED IN C PROGRAM
 Source File- This file contains the
source code of the program. The file
extension of any c file is .c. The file
contains C source code that defines the
main function & maybe other functions
Header File- A header file is a file with
extension .h which contains the C function
declarations and macro definitions and to
be shared between several source files.

73
FILES USED IN C PROGRAM [contd..]
 Object File- An object file is a file containing
object code, with an extension .o, meaning
relocatable format machine code that is usually
not directly executable.
Object files are produced by an assembler,
compiler, or other language translator, and
used as input to the linker, which in turn
typically generates an executable or library by
combining parts of object files
Executable File- The binary executable file is
generated by the linker. The linker links the
various object files to produce a binary file that
can be directly executed
74
COMPILATION AND EXECUTION OF C PROGRAM

75
FORMATTED DATA INPUT/ OUTPUT

 Using I/O operations, the data is read and written to and from
various sources, including files, keyboards, and screens
 The I/O procedure is known as "formatted I/O". It enables you to read
or write data in a certain format. Printf() and scanf() are two examples of
C routines that handle formatted I/O.
 The type and format of the data to be read or written are specified by
format strings, which are used by these operations. The program's
execution replaces the placeholders for the data found in the format
strings with the actual data
 Syntax:
printf(format string, argument list);

Here the argument list comprises the variables or values to be


printed, and the format string determines the output format.
76
FORMATTED DATA INPUT/ OUTPUT [CONTD..]
 Syntax for scanf()
scanf(format string, argument list);
Example program to illustrate this
#include <stdio.h>
int main() {
char name[20];
int age;
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your age: ");
scanf("%d", &age);
printf("Your name is %s and your age is %d\n", name, age);
return 0;
}

77
FORMATTED DATA INPUT/ OUTPUT
[CONTD..]

Program Output

Enter your name: Seema


Enter your age : 25
Your name is Seema and your age is 25

78
UNFORMATTED DATA INPUT/ OUTPUT

 Unformatted I/O refers to a category of I/O operations


that reads or writes data as a stream of bytes without
regard to any format.

 Unformatted I/O in C is carried out with the aid of


functions like fread() and fwrite(). Without formatting,
these operations are used to read and write data directly to
and from files.

79
Control Statements
They are an essential aspect of programming languages
like C, as they allow programmers to control the flow of
execution of their programs
In C, there are three types of control statements:
selection statements, iteration statements, and jump
statements
Programming constructs that are used to control the
flow of execution in a program
They allow a programmer to specify conditions that
determine which statements are executed and which are
skipped, to loop through statements until a condition is
met, or to jump to a different part of the program
80
If Statements
 If statement enables the programmer to choose a set of
instructions, based on a condition. When the condition is
evaluated to true, a set of instructions will be executed and
a different set of instructions will be executed when the
condition is evaluated to false. We have 4 types of if
Statement which are:
1. If. Else
2. Nested if
3. Else if ladder
4. Simple if or null else

81
If .. Else

82
If .. Else – Example

83
Nested If..Else

84
Nested If .. Else – Example

85
Nested If .. Else – Example
[contd..]

86
Program Output

87
Else..if ladder
Syntax:

88
Else if ladder – Example

89
Else if ladder – Output of
Program

90
Simple if or null else

91
Simple if or null else – Example

92
Simple if or null else – Output

93
Switch Statement

94
Switch Statement - Example

95
Switch Statement – Example
[CONTD..]

96
Switch Statement – Output

Enter the number of the day : 2

Monday

97
Iteration Statements
Iteration statements are used to execute a
particular set of instructions repeatedly
until a particular condition is met or for a
fixed number of iterations
 for statement
while statement
do-while statement

98
For loop
Syntax:

•The initialization expression, which initializes the looping index. The


looping index controls the looping action. The initialization expression
is executed only once, when the loop begins.
•The termination expression, which represents a condition that must
be true for the loop to continue execution.
•The increment/decrement expression is executed after every iteration
to update the value of the looping index.

99
For loop – Example

100
For loop – Example Output

101
While loop
Syntax:

The while statement executes a block of statements


repeatedly while a particular condition is true. The
statements are executed repeatedly until the condition
is true.

102
While loop - Example

103
While loop – Example Output

104
do.. while loop
Syntax:

The do-while statement evaluates the condition at the end of the


loop after executing the block of statements at least once. If the
condition is true the loop continues, else it terminates after the first
iteration.

105
do..while loop - Example

106
do..while loop – Example
output

107
Jump Statements
Jump statement is used to alter the normal
flow of execution of a program. It allows the
program to transfer control to a different
part of the code, such as a different
function or a different block of code within
the same function.
There are three types of jump statements
in C: goto, break, and continue.

108
Go to statement

The goto statement transfers control to the labeled


statement, which is defined elsewhere in the function

109
Go to statement – Example

110
Go to statement – Output

111
Break statement
Syntax:

The break statement is utilized to exit a loop or switch statement


before its normal termination. It is commonly utilized in loops to exit
early if any specific condition is met.

112
Break statement – Example

113
Break statement – Example
Output

114
Continue statement

The continue statement is utilized to skip the remaining code in


a loop for the current iteration and move on to the next
iteration. It is commonly used in loops to skip over certain
elements.
115
Continue statement -
Example

116
Continue statement - Output

117

You might also like