SlideShare a Scribd company logo
Fundamentals of Programming
Lecture 1
Book by : Computer, Architecture and Organizations, 8th
Edition ,William Stalling
Original Slides by : Adrian J Pullin
Introduction
Objectives
• Understand the different types of programming languages.
• Understand the basic procedures in a program as input,
processing and output.
• Understand the importance of variables.
• Understand a basic map of the program development cycle.
Computer Components
• CPU Central Processing Unit
• RAM (Random Access Memory)
• Mass storage devices
• Input devices
• Output Devices
Software
•Application Software
– Word Processors
– Spreadsheets
– Painting programs
– Web browsers, email
programs
•System Software
– Operating Systems
• Windows
• Macintosh OS
• Unix
• Linux
– Drivers
Software is comprised of instructions that get a
computer to perform a task.
Programming Languages
• Programming languages allow programmers to code software.
• The three major families of languages are:
 Machine languages
 Assembly languages
 High-Level languages
Machine Languages
• Comprised of 1s and 0s
• The “native” language of a computer
• Difficult to program – one misplaced 1 or 0 will cause the
program to fail.
• Example of code:
1110100010101 111010101110
10111010110100 10100011110111
Assembly Languages
• A step towards easier programming.
• Comprised of a set of elemental commands
 tied to a specific processor.
• Assembly language code needs to be translated to machine
language before the computer processes it.
• Example:
ADD 1001010, 1011010
High-Level Languages
• High-level languages represent a giant leap towards easier
programming.
• The syntax of HL languages is similar to English.
• Historically, we divide HL languages into two groups:
 Procedural languages
 Object-Oriented languages (OOP)
Procedural Languages
• Procedural languages
 The focus of such languages is on sequence of activities to be
carried out.
 Based on specifying the steps the program must take to reach the
desired state.
 Examples include C, COBOL, Fortran, LISP, Perl, HTML, VBScript
Object-Oriented Languages
• Object-oriented languages:
 Focus on modeling data.
 Programmers code using “blueprints” of data models called classes.
 Examples of OOP languages include C++, Visual Basic.NET and
Java.
Compiling
• All HL programs need to be translated to machine code
 so that a computer can process the program.
• Programs may be translated using
 a compiler:
translated all at once
 An interpreter
translated line by line
• Compiled programs typically execute more quickly than interpreted
programs, but have a slower translation speed.
• On the other hand, interpreted programs generally translate
quicker than compiled programs, but have a slower execution
speed.
Programming Example
• Simple programming problem: Convert a length from feet
into meters.
• Pseudocode:
Input the length of an item, LengthInFeet, in feet and Compute
the length of the item in meters:
Write “Enter the length in feet”
Input LengthInFeet
Set LengthInMeters = LengthInFeet * .3048
Write LengthInMeters
Programming Example
 Partial Code in C:
 float LengthInFeet;
 LengthInMeters = LengthInFeet * .3048;
 printf (“%f”, LengthInMeters);
Input & Variables
• Input operations get data into the programs
• A user is prompted to enter data:
 Write “Enter the length in feet”
 Input LengthInFeet
• Computer programs store data in named sections of memory
called variables.
• In the example above, the variables are named LengthInFeet
& LengthInMeters.
 The value of a variable can, and often does, change throughout the
program.
Variables
• Needed because we might want the program to run using
different values:
 E.g. we might want to calculate LengthInMeters for different values of
LengthInFeet
 Each value for which computation is to be carried out will be stored in
the variable LengthInFeet one-by-one
 Referring to the variable LengthInFeet by its name gives the value
stored in it.
Constants
• Many a time we need to used fixed values for certain
computations.
• E.g. in the program given above
 the conversion from miles to meters requires the length in miles to be
multiplied by .3048
 a value that doesn’t (need to) change
 Such values are constants
• We may also give names to constants: such constants are
called named constants
Types of Data
• Numeric Data
 Integer data, I.e., whole numbers, 10 25 -45 0
 Floating point data – have a decimal point 23.0, -5.0
• Character data (alphanumeric)
 All the characters you can type at the keyboard
 Letters & numbers not used in calculations
• Boolean data
 TRUE/FALSE
Data Processing and Output
• LengthInMeters = .3048 * LengthInFeet
 The above statement is a processing statement.
 Take the value in the variable LengthInFeet,
 Multiply by .3048, and
 Set the value of the variable LengthInMeters to the result of the
multiplication.
Also stated as assign the result of multiplication to the variable
LengthInMeters
• Write LengthInMeters
 Output the value in LengthInMeters to the monitor.
Assignment Statements
• If the variable being assigned to already contains a data value,
 the previously stored value is overwritten
 E.g. the following statements:
Age= 12;
Age=15;
Have an effect of storing 15 in the variable Age.
 Reason: The value 12 (stored as an effect of the first assignment
statement) gets overwritten after the execution of the second
statement.
Assignment Statements
• The statement
 Age = Age + 1
 Changes the value of the variable Age in such a way
that the new value is one greater than the previous value.
• Working: Take the value of Age, add 1, and store the result
back in the same variable.
Operations on Data
• Operator is a symbol that is used to perform certain operations
• Data values on which operation is performed are termed as
operands
• Operators generally work on many types of variables or constants,
 though some are restricted to work on certain types.
 some may even exhibit different behaviors with different data
types
• Operators in C may be:
 Unary: Work on single operand
 Binary: Work on two operands
 Ternary: Work on three operands
Operators
• C, like most programming languages, supports operators to
carry out various kinds of operations
• We have operators for:
 Arithmetic operations
 Type Conversions
 Performing Comparisons
 Performing Logical Operations
 Working on individual bits of data
 And many more…
Precedence of Operators
• Operator precedence:
 A set of rules decide the order of operations in an expression
 Like BODMAS rule in mathematics
 Operator Precedence clarifies unambiguously, which operations
should be performed first in a given expression.
 Parentheses i.e. () can always be used to improve clarity
Associativity of Operators
• Operator Associativity:
• Rule used for two operators of equal precedence (i.e. same
importance)
• Associativity may be either of the following
 left to right: left operator is evaluated first
 right to left: right operator is evaluated first
Structured Programming
• A method for designing and coding programs in a systematic,
organized manner.

• It combines
 the principles of top-down design,
 modularity and
 the use of the three accepted control structures of
sequence,
repetition and
selection.
Control Structures
• Sequence –in sequential order.
 The simplest of control structures –
start at the beginning and continue in sequential order.
• Selection – selectively execute statements
 Called a branch,
 it requires a condition to determine when to execute statements.
Control Structures
 Repetition – repeat statements more than once
Called a loop,
It needs a stop condition,
I.e, the program will continue to loop (repeatedly
execute a set of statements) until some condition
is met.
Counter-Controlled Loop:
(Definite Repetition)
• If it is known in advance exactly how many times a loop
will execute, the repetition is said to be counter-
controlled
• Counter-controlled loop:
 Execute a set of statements repeatedly a specified number of
times
 The counter may be advanced according to programmers
requirements .
Event-Controlled Loop: (Indefinite Repetition)
• If it is NOT known in advance exactly how many times a
loop will execute, the loop is said to be event-controlled.
• An event-controlled loop
 Terminates when some event occurs.
 The event may be based upon:
User input
Results of calculation
And many more….
Steps in Developing a
Program
• Developing a Program:
1. Analyze the problem
2. Design the program
3. Code the program
4. Test the program
Step-1 Analyze the
Problem
 Brewster’s Thousands
 The problem: Brewster wants to invest money at a local bank. There
are many options such as interest rates, terms of deposit, compounding
frequencies. He needs a program to compute, for any given initial
investment, the final maturity (value) of the deposit.
What are the inputs? (given data)
What are the outputs? (required data)
How will we calculate the required outputs from the given inputs?
Step-2 Design the
Program
• Create an outline of the program
• An algorithm – a step by step procedure that will provide the required
results from the given inputs.
• Algorithm Examples: Instructions on how to make a cake, use the bank’s
ATM, etc.
Step-3 Code the
Program
• Once the design is completed, write the program code.
• Code is written in some programming language such as BASIC, Pascal,
C++, Java, etc.
Errors in Development
• While writing a program, certain errors may get induced in the
code.
• Errors may be categorized as :
 Syntactical Errors – Incorrect Syntax (wrong grammar), i.e.,
breaking the rules of how to write the language
Forgetting punctuation, misspelling keyword
The program will not run at all with syntax errors
 Semantic Errors: Incorrect Logic:
Using an incorrect formula, incorrect sequence of
statements, etc.
The program runs, but does not produce the expected
results.
Step-4 Testing the
program
• Purpose: Locate any errors (bugs) / problems
• Most of the work should be done before the phase begins – creating of
a testing document – telling what to test & how.
• Two types of testing:
 Testing for errors
 Quality testing
• Testing is done throughout the development cycle
• Desk-checking, or code walkthrough is performed to locate errors in
the code.
 Pretend you are the computer and execute your own code.
• Ultimate test is to run the program to see if the outputs are correct for
the given inputs.
Good Programming Practice
• It is best not to take the “big bang” approach to coding.
• Use an incremental approach by writing your code in
incomplete, yet working, pieces.
• For example, for your projects,
 Don’t write the whole program at once.
 Just write enough to display the user prompt on the screen.
 Get that part working first (compile and run).
 Next, write the part that gets the value from the user, and then just
print it out.
Modular Programming
• Determine the major tasks that the program must accomplish.
 Each of these tasks will be a module.
• Some modules will be complex themselves, and they will be broken into
sub-modules,
 and those sub-modules may also be broken into even smaller
modules.
• This is called top-down design
Code Modules
• A module is an independent, self-contained section of code
that performs a single task.
• The main module is the module that drives the application.
 It “controls” all other modules.
 Typically, the main module calls other modules in order to have them
perform certain tasks.
Program Control & Modules
• When the main module calls another module,
program control transfers to the called module.
• Program control cedes back to the main module
when the called module finishes.
Structure Chart
• A structure chart shows what modules exist and how they are
related.
• A structure chart is a top-down modular design tool
• It is used in structured programming to arrange program
modules into a tree
• It’s a good idea to keep modules short – about 1 page per
module.
• We will have very small modules while getting comfortable with
programming.
Documentation
• Internal Documentation
 Comments explain to the reader the logic and decision processes of
the programmer.
 Comments are ignored by an interpreter or compiler.
• External Documentation
 External documentation includes a user’s guide and, typically, a more
technical system administrator’s guide.
Over to C Fundamentals…
•C Fundamentals
Objectives
• History of C
• Characteristics of C
• Converting a C Program to Executable
• Dissecting a simple C Program
• Defining Variables in C
• Printing Out and Inputting Variables
• Constants & Literals
History of C
• Developed by Brian Kernighan and Dennis Ritchie of
AT&T Bell Labs in 1972
• In 1983 the American National Standards Institute began
the standardization process
• In 1989 the International Standards Organization
continued the standardization process
• In 1990 a standard was finalized, known simply as
“Standard C”
Features of C
• C can be thought of as a “high level assembler”
• Most popular programming language for writing system
software
• Focus on the procedural programming paradigm, with
facilities for programming in a structured style
• Low-level unchecked access to computer memory via the
use of pointers
• And many more…
Writing C Programs
• A programmer uses a text editor to create or modify files
containing C code.
• Code is also known as source code.
• A file containing source code is called a source file.
• After a C source file has been created, the programmer
must invoke the C compiler before the program can be
executed (run)
Getting an executable
program
• The process of conversion from source code to machine
executable code is a multi step process.
• If there are no errors in the source code, the processes called
compilation & linking produce an executable file
• To execute the program, at the prompt, type
<executable file name>
Conversion from .C to executable
1. Preprocessing
2. Compilation
3. Linking
Stage 1:
Preprocessing
 Performed by a program called the preprocessor
 Modifies the source code (in RAM) according to preprocessor
directives (preprocessor commands) embedded in the source
code
 Strips comments and white space from the code
 The source code as stored on disk is not modified
Stage 2: Compilation
 Performed by a program called the compiler.
 Checks for syntax errors and warnings
 Translates the preprocessor-modified source code into object
code (machine code).
 Saves the object code to a disk file
 If any compiler errors are received, no object code file will be
generated.
 An object code file will be generated if only warnings, not
errors, are received.
Stage 3: Linking
• Combines the program object code with other object code to
produce the executable file.
• The other object code can come from the
– Run-Time Library
– other libraries
– or object files that you have created.
• Saves the executable code to a disk file.
• If any linker errors are received, no executable file is
generated.
Developing a C Program
Modified Source Code in RAM
Source File pgm.c
Program Object Code File
Executable File
Preprocessor
Compiler
Linker
Editor
A Simple C Program
/* Filename: hello.c
Author: --------
Date written: --/--/----
Description: This program prints the greeting
“Hello, World!”
*/
#include <stdio.h>
int main ( void )
{
printf ( “Hello, World!n” ) ;
return 0 ;
}
Structure of a C Program
program header comment
preprocessor directives (if any)
int main ( )
{
statement(s)
return 0 ;
}
Explanation
#include <stdio.h> /* comment */
int main(void)
{
printf("Hellon");
printf("Welcome to the Course!n");
return 0;
}
Hello
Welcome to the Course!
tells compiler about standard input and output functions (i.e. printf + others)
main function
“begin”
“end”
flag success
to operating
system
Tokens
• The smallest element in the C language is the token.
• It may be a single character or a sequence of characters to form
a single item.
Tokens can be any of:
• Numeric Literals
• Character Literals
• String Literals
• Keywords
• Names (identifiers)
• Punctuation
• Operators
Numeric Literals
• Numeric literals are an uninterrupted sequence of
digits
• May contain
 A period,
 A leading + or – sign
 A scientific format number
 A character to indicate data type
• Examples:
 123
 98.6
 1000000
Character Literals
• Singular!
• One character defined character set.
• Surrounded on the single quotation mark.
• Examples:
 ‘A’
 ‘a’
 ‘$’
 ‘4’
String Literals
• A sequence characters surrounded by double quotation
marks.
• Considered a single item.
• Examples:
 “UMBC”
 “I like ice cream.”
 “123”
 “CAR”
 “car”
Keywords
• Sometimes called reserved words.
• Are defined as a part of the C language.
• Can not be used for anything else!
• Examples:
 int
 while
 for
Reserved Words (Keywords) in C
• auto
• case
• const
• default
• double
• enum
• float
• goto
• int
• register
• short
• sizeof
• struct
• typedef
• unsigned
• volatile
• break
• char
• continue
• do
• else
• extern
• for
• if
• long
• return
• signed
• static
• switch
• union
• void
• while
All the C keywords are in small case
Names / Identifiers
• Variables must be declared before use and immediately
after “{”
• Can be of anything length, but only the first 31 are
significant (A very long name is as bad as a very short, un-
descriptive name).
• Are case sensitive: abc is different from ABC
• Must begin with a letter and the rest can be letters, digits,
and underscores.
• Cannot be a reserved word.
Which Are Legal Identifiers?
AREA area_under_the_curve
3D num45
Last-Chance #values
x_yt3 pi
num$ %done
lucky*** continue
Float integer
Punctuation
• Semicolons, colons, commas, apostrophes,
quotation marks, brackets, and parentheses.
• ; : , ‘ “ { } ( )
Things to remember
• Statements are terminated with semicolons
• Indentation is ignored by the compiler
• C is case sensitive - all keywords and Standard Library functions are
lowercase
Variables and Constants in C
Topics
• Variables
 Naming
 Declaring
 Using
• The Assignment Statement
• Constants
• Data Input & Output
Naming Conventions
• Begin variable names with lowercase letters
• Use meaningful names
• Separate “words” within identifiers with underscores or mixed upper and
lower case.
• Use all uppercase for symbolic constants (used in #define
preprocessor directives).
• Be consistent!
 In addition to the conventions one must follow all the naming rules
as discussed in previous sessions.
Note: symbolic constants are not variables,
but make the program easier to read.
Declaring Variables
• All variables need to be declared before they are used.
• The declaration statement includes (apart from other
information) the data type of the variable.
• Examples of variable declarations:
 int meatballs ;
 float area ;
It is required to declare variables before using
as compiler needs this information
Purpose!!!
Declaring Variables
 When we declare a variable
 Space is set aside in memory to hold a value of the specified
data type
 That space is associated with
the variable name
a unique address
 Visualization of the declaration
int age ; age
FE07 int
garbage
More About Variables
 Basic data types available in C are:
 char: stores single character
 int: stores whole numbers
 float: store floating point numbers
 double: store floating point numbers with higher precision
Integer Types in C
• C supports different kinds of integers, like
 signed int
 unsigned int
 long int
 short int
 And more…
• Limits depend upon size in bytes which in turn depends
upon environment
 maxima and minima defined in “limits.h”
• We can work with different bases as well (octal,
hexadecimal).
The int Data Type (Contd.)
 Use
 scanf (“%i”, &ch) ;
 to read a single integer into the variable ch.
 Use
 printf(“%i”, ch) ;
 to display the value of an integer variable.
The char Data Type
• The char data type holds a single character.
 char ch;
• Example assignments:
 char grade, symbol;
 grade = ‘B’;
 symbol = ‘$’;
• The char is held as a one-byte integer in memory. The
ASCII code is what is actually stored, so we can use
them as characters or integers, depending on our need.
The char Data Type (Contd.)
 Use
 scanf (“%c”, &ch) ;
 to read a single character into the variable ch.
 Use
 printf(“%c”, ch) ;
 to display the value of a character variable.
char I/O
 #include <stdio.h>
 int main ( )
 {
 char ch ;
 printf (“Enter a character: “) ;
 scanf (“%c”, &ch) ;
 printf (“The value of %cn.”, ch) ;
 return 0 ;
 }
Input: A
Output : The value of A is 65.
Real Types In C
 C supports different kinds of reals
 maxima and minima are defined in “float.h”
type format minimum maximum
float %f %e %g FLT_MIN FLT_MAX
double %lf %le %lg DBL_MIN DBL_MAX
long double %Lf %Le %Lg LDBL_MIN LDBL_MAX
Notes About Variables
• You must not use a variable until you somehow give it a
value.
• You can not assume that the variable will have a value
before you give it one.
 Some compilers do, others do not! This is the source of many
errors that are difficult to find.
Operators in C
Arithmetic Operators and
their Usage
Name Operator Example
Addition + num1 + num2
Subtraction - initial - spent
Multiplication * fathoms * 6
Quotient of Division / sum / count
Remainder of Division % m % n
% can not be used with reals
Relational Operators
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== is equal to
!= is not equal to
 Relational expressions evaluate to the integer values:
 1 (true) on success
 0 (false) on failure
Logical Operators
• At times we need to test multiple conditions in order to
make a decision.
• Logical operators combine simple conditions to make
complex conditions.
• Result into a 0 (false) or 1 (true)
 && AND if ( x > 5 && y < 6 )
 || OR if ( z == 0 || x > 10 )
 ! NOT if (! (age > 42) )
Truth Table for &&
Expression1 Expression2 Expression1 && Expression2
 0 0 0
 0 nonzero 0
 nonzero 0 0
 nonzero nonzero 1
Exp1 && Exp2 && … && Expn will evaluate to 1 (true) only
if ALL sub-conditions are true.
Truth Table for ||
Expression1 Expression2 Expression1 || Expression2
 0 0 0
 0 nonzero 1
 nonzero 0 1
 nonzero nonzero 1
Exp1 || Exp2 || … || Expn will evaluate to 1 (true) if any one of
the sub-conditions is true.
Truth Table for !
 Expression ! Expression
 0 1
 nonzero 0
Precedence/Associativity
Table
Operator Associativity
() [] -> . left to right
! ~ ++ -- - + (cast) * & sizeof right to left
* / % left to right
+ - left to right
<< >> left to right
< <= >= > left to right
== != left to right
& left to right
| left to right
^ left to right
&& left to right
|| left to right
?: right to left
= += -= *= /= %= etc right to left
, left to right
+ - : unary
User Interaction in C
Functions
• Functions are named code blocks that make reusability of
code possible.
• These are parts of programs that
 Perform a well defined task.
 At times, expect some information in order to complete the task.
 The information is provided in form of parameters (arguments)
 Can return a value to convey result / status of execution
I/O Example
#include <stdio.h>
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf("%i %i", &a, &b);
printf("%i - %i = %in", a, b, a - b);
return 0;
}
create two integer
variables, “a” and “b”
read two integer
numbers into “a”
and “b”
write “a”, “b” and “a-b”
in the format specified
Enter two numbers: 21 17
21 - 17 = 4
Displaying Variables
• A Function that allows us to display formatted data:
 printf( ).
• Needs two pieces of information to display things.
 How to display it
 What to display
• printf( “%fn”, diameter );
printf( “%fn”, diameter );
• The name of the function is “printf”.
• Inside the parentheses are two comma separated
parameters:
 Format specifier: indicates the format in which the output will be
produced
%f => a floating point value
n => a new-line character (escape
sequence)
 The expression diameter whose value is to be displayed.
scanf (“%f”, &meters) ;
• This function is used to
 read values from the standard input; and
 Store them in memory.
• The scanf( ) function also needs two items:
 The input specification “%f”.
 The address of the memory location where the information
is to be stored.
• We can input more than one item at a time if we wish, as long
as we specify it correctly!!!
• Notice the “&” in front of the variable name. Can you
explain its significance!
Format Specifiers
• Format specifiers are normal strings with embedded
“conversion specifications” which are placeholders for
arguments
• Conversion specifications are a ‘%’ and a letter with an
optional set of arguments in between the ‘%’ and letter.
Why are these required!!!
Selection: the if statement
if ( condition )
{
statement(s) /* body of the if statement */
}
• The braces are not required if the body contains only a single
statement.
• However, they are a good idea and are required by the C Coding
Standards.
Examples
 if ( age >= 18 )
 {
 printf(“Vote!n”) ;
 }
if ( value == 0 )
{
printf (“The value you entered was zero.n”);
printf (“Please try again.n”) ;
}
Some Control Constructs in C
Selection: the if-else
statement
if ( condition )
{
statement(s) /* the if clause */
}
else
{
statement(s) /* the else clause
*/
}
Example
 if ( age >= 18 )
 {
 printf(“Vote!n”) ;
 }
 else
 {
 printf(“Maybe next time!n”) ;
 }
Repetition Structure
• There are three repetition structures in C: -
 the while loop
 the for loop
 the do-while loop.
• Either of these structures may be used for counter-controlled /
event-controlled logic, but
• The syntax of for loop makes it more suitable for counter-
controlled repetition
• And, The syntax of while / do-while loops makes them more
suitable for event-controlled repetition
The while Repetition
Structure
 while ( condition )
 {
 statement(s)
 }
• The braces are not required if the loop body contains
only a single statement.
• However, they are a good idea and are required by
the C Coding Standards.
while Loop
• The simplest C loop is the while
• Parentheses must surround the condition
• Condition could be based on user input or some calculation
• Braces must be added if more statements are to be executed
total= 0;
while (number != -1) {
total = total + number;
printf(“Enter another number: “) ;
scanf(“%d”, &number) ;
}
The for Loop
Repetition Structure
• The for loop handles details of the counter-controlled loop
“automatically”.
• The following are handled within the for loop structure
 initialization of the the loop control variable,
 the termination condition test, and
 control variable modification.
 for ( i = 1; i < 101; i = i + 1)
 {

 }
 initialization test modification
A for Loop That Counts
From 0 to 9
 for ( i = 0; i < 10; i = i + 1 )
 {
 printf (“%dn”, i) ;
 }
We Can Count Backwards,
Too
 for ( i = 9; i >= 0; i = i - 1 )
 {
 printf (“%dn”, i) ;
 }
Count By 2’s or 7’s or
Whatever
 for ( i = 0; i < 10; i = i + 2 )
 {
 printf (“%dn”, i) ;
 }
The do-while
Repetition Structure
do
{
 statement(s)
} while ( condition ) ;
• The body of a do-while is ALWAYS executed at least once.
• Is this true of a while loop?
• What about a for loop?
Example
 do
 {
 printf (“Enter a number, 0 to terminate:
“);
 scanf (“%d”, &number) ;
 if (number == 1)
 printf (“n Do Somethingn”) ;
 else if (number == 2)
 printf (“n Do Something Elsen”) ;
 } while ( num != 0 );
An Equivalent while Loop
 printf (“Enter a number, 0 to terminate:“) ;
 scanf (“%d”, &number) ;
 while ( number != 0 )
 {
 if (number == 1)
 printf (“n Do Somethingn”) ;
 else if (number == 2)
 printf (“n Do Something Elsen”) ;
printf (“Enter a number , 0 to terminate:“) ;
scanf (“%d”, &number) ;
 }
Notice that using a while loop in this case requires a priming
read.
An Equivalent for Loop
 printf (“Enter a positive number, 0 to terminate: “)
;
 scanf (“%d”, &number) ;
 for ( ; number != 0; )
 {
 if (number == 1)
 printf (“n Do Somethingn”) ;
 else if (number == 2)
 printf (“n Do Something Elsen”) ;
printf (“Enter a number , 0 to terminate:“) ;
scanf (“%d”, &number) ;
 }
A for loop is a very awkward choice here because the
loop is event-controlled.
So, Which Type of Loop Should One Use?
• Use a for loop for counter-controlled repetition.
• Use a while or do-while loop for event-controlled
repetition.
 Use a do-while loop when the loop must execute at least one
time.
 Use a while loop when it is possible that the loop may never
execute.
 That’s all for now…
 We are ready for writing a simple C program.
Ad

More Related Content

Similar to Programming Fundamentals - Lecture 1.ppt (20)

Problem Solving and Programming using C.pdf
Problem Solving and Programming using C.pdfProblem Solving and Programming using C.pdf
Problem Solving and Programming using C.pdf
PradeepT42
 
introduction to problem solving and programming
introduction to problem solving and programmingintroduction to problem solving and programming
introduction to problem solving and programming
chaudhariresham6
 
CHAPTER-1.ppt
CHAPTER-1.pptCHAPTER-1.ppt
CHAPTER-1.ppt
Tekle12
 
PPS Unit-1.pdf
PPS Unit-1.pdfPPS Unit-1.pdf
PPS Unit-1.pdf
NenavathSurendhar
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
Sangheethaa Sukumaran
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem sloving
Mani Kandan
 
Computer system literature pre_lect1.ppt
Computer system literature pre_lect1.pptComputer system literature pre_lect1.ppt
Computer system literature pre_lect1.ppt
johnlloydvillorente1
 
01CHAP_1.PPT
01CHAP_1.PPT01CHAP_1.PPT
01CHAP_1.PPT
ManoRanjani30
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptx
crAmth
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
MMRF2
 
Java developer trainee implementation and import
Java developer trainee implementation and importJava developer trainee implementation and import
Java developer trainee implementation and import
iamluqman0403
 
First draft programming c++
First draft programming c++First draft programming c++
First draft programming c++
藝輝 王
 
Compiler an overview
Compiler  an overviewCompiler  an overview
Compiler an overview
amudha arul
 
Python Programming-Skill Course - unit-i.pptx
Python Programming-Skill Course - unit-i.pptxPython Programming-Skill Course - unit-i.pptx
Python Programming-Skill Course - unit-i.pptx
KavithaDonepudi
 
ch01_overview computer science and engineering.pdf
ch01_overview computer science and engineering.pdfch01_overview computer science and engineering.pdf
ch01_overview computer science and engineering.pdf
nazibulnabil
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Unit ii
Unit   iiUnit   ii
Unit ii
sathisaran
 
Unit 2 computer software
Unit 2 computer softwareUnit 2 computer software
Unit 2 computer software
Hardik Patel
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Problem Solving and Programming using C.pdf
Problem Solving and Programming using C.pdfProblem Solving and Programming using C.pdf
Problem Solving and Programming using C.pdf
PradeepT42
 
introduction to problem solving and programming
introduction to problem solving and programmingintroduction to problem solving and programming
introduction to problem solving and programming
chaudhariresham6
 
CHAPTER-1.ppt
CHAPTER-1.pptCHAPTER-1.ppt
CHAPTER-1.ppt
Tekle12
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
Sangheethaa Sukumaran
 
Algorithmic problem sloving
Algorithmic problem slovingAlgorithmic problem sloving
Algorithmic problem sloving
Mani Kandan
 
Computer system literature pre_lect1.ppt
Computer system literature pre_lect1.pptComputer system literature pre_lect1.ppt
Computer system literature pre_lect1.ppt
johnlloydvillorente1
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptx
crAmth
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
MMRF2
 
Java developer trainee implementation and import
Java developer trainee implementation and importJava developer trainee implementation and import
Java developer trainee implementation and import
iamluqman0403
 
First draft programming c++
First draft programming c++First draft programming c++
First draft programming c++
藝輝 王
 
Compiler an overview
Compiler  an overviewCompiler  an overview
Compiler an overview
amudha arul
 
Python Programming-Skill Course - unit-i.pptx
Python Programming-Skill Course - unit-i.pptxPython Programming-Skill Course - unit-i.pptx
Python Programming-Skill Course - unit-i.pptx
KavithaDonepudi
 
ch01_overview computer science and engineering.pdf
ch01_overview computer science and engineering.pdfch01_overview computer science and engineering.pdf
ch01_overview computer science and engineering.pdf
nazibulnabil
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Unit 2 computer software
Unit 2 computer softwareUnit 2 computer software
Unit 2 computer software
Hardik Patel
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
Inductive Automation
 

More from FarhanGhafoor7 (15)

603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
FarhanGhafoor7
 
eyeryeryeryeryeyeyeryeryyerye13872085.ppt
eyeryeryeryeryeyeyeryeryyerye13872085.ppteyeryeryeryeryeyeyeryeryyerye13872085.ppt
eyeryeryeryeryeyeyeryeryyerye13872085.ppt
FarhanGhafoor7
 
Lecture-21a discrete structure and mathematics.ppt
Lecture-21a discrete structure and mathematics.pptLecture-21a discrete structure and mathematics.ppt
Lecture-21a discrete structure and mathematics.ppt
FarhanGhafoor7
 
Lecture-20a discrete structure and mathematics.ppt
Lecture-20a discrete structure and mathematics.pptLecture-20a discrete structure and mathematics.ppt
Lecture-20a discrete structure and mathematics.ppt
FarhanGhafoor7
 
Lecture-Discrete Structure and discrete Mathematics.ppt
Lecture-Discrete Structure and discrete Mathematics.pptLecture-Discrete Structure and discrete Mathematics.ppt
Lecture-Discrete Structure and discrete Mathematics.ppt
FarhanGhafoor7
 
Week 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptxWeek 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
CCN - Lecture2 Cyber Security and Cryptology.ppt
CCN - Lecture2 Cyber Security and Cryptology.pptCCN - Lecture2 Cyber Security and Cryptology.ppt
CCN - Lecture2 Cyber Security and Cryptology.ppt
FarhanGhafoor7
 
ESD Lecture introduction to embedded systems -3.pptx
ESD Lecture introduction to embedded systems -3.pptxESD Lecture introduction to embedded systems -3.pptx
ESD Lecture introduction to embedded systems -3.pptx
FarhanGhafoor7
 
Android - Intents and Filters hgfh gfh.pptx
Android - Intents and Filters hgfh gfh.pptxAndroid - Intents and Filters hgfh gfh.pptx
Android - Intents and Filters hgfh gfh.pptx
FarhanGhafoor7
 
Lecture -Introduction to Flutter and Dart.pptx
Lecture -Introduction to Flutter and Dart.pptxLecture -Introduction to Flutter and Dart.pptx
Lecture -Introduction to Flutter and Dart.pptx
FarhanGhafoor7
 
Assambly Language and Data Communication with Cell Phone
Assambly Language and Data Communication with Cell PhoneAssambly Language and Data Communication with Cell Phone
Assambly Language and Data Communication with Cell Phone
FarhanGhafoor7
 
Wireless Communication and Cellular Communication
Wireless Communication and Cellular CommunicationWireless Communication and Cellular Communication
Wireless Communication and Cellular Communication
FarhanGhafoor7
 
Fiber Optical Networks and Data Communication
Fiber Optical Networks and Data CommunicationFiber Optical Networks and Data Communication
Fiber Optical Networks and Data Communication
FarhanGhafoor7
 
Wired LANS - Ethernet and Computer Local Area Networks
Wired LANS - Ethernet and Computer Local Area NetworksWired LANS - Ethernet and Computer Local Area Networks
Wired LANS - Ethernet and Computer Local Area Networks
FarhanGhafoor7
 
Class Scheduling using Generative AI.pptx
Class Scheduling using Generative AI.pptxClass Scheduling using Generative AI.pptx
Class Scheduling using Generative AI.pptx
FarhanGhafoor7
 
603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
603848771-Lecture-1-Intro-to-Flutter-and-Dart.pptx
FarhanGhafoor7
 
eyeryeryeryeryeyeyeryeryyerye13872085.ppt
eyeryeryeryeryeyeyeryeryyerye13872085.ppteyeryeryeryeryeyeyeryeryyerye13872085.ppt
eyeryeryeryeryeyeyeryeryyerye13872085.ppt
FarhanGhafoor7
 
Lecture-21a discrete structure and mathematics.ppt
Lecture-21a discrete structure and mathematics.pptLecture-21a discrete structure and mathematics.ppt
Lecture-21a discrete structure and mathematics.ppt
FarhanGhafoor7
 
Lecture-20a discrete structure and mathematics.ppt
Lecture-20a discrete structure and mathematics.pptLecture-20a discrete structure and mathematics.ppt
Lecture-20a discrete structure and mathematics.ppt
FarhanGhafoor7
 
Lecture-Discrete Structure and discrete Mathematics.ppt
Lecture-Discrete Structure and discrete Mathematics.pptLecture-Discrete Structure and discrete Mathematics.ppt
Lecture-Discrete Structure and discrete Mathematics.ppt
FarhanGhafoor7
 
Week 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptxWeek 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
CCN - Lecture2 Cyber Security and Cryptology.ppt
CCN - Lecture2 Cyber Security and Cryptology.pptCCN - Lecture2 Cyber Security and Cryptology.ppt
CCN - Lecture2 Cyber Security and Cryptology.ppt
FarhanGhafoor7
 
ESD Lecture introduction to embedded systems -3.pptx
ESD Lecture introduction to embedded systems -3.pptxESD Lecture introduction to embedded systems -3.pptx
ESD Lecture introduction to embedded systems -3.pptx
FarhanGhafoor7
 
Android - Intents and Filters hgfh gfh.pptx
Android - Intents and Filters hgfh gfh.pptxAndroid - Intents and Filters hgfh gfh.pptx
Android - Intents and Filters hgfh gfh.pptx
FarhanGhafoor7
 
Lecture -Introduction to Flutter and Dart.pptx
Lecture -Introduction to Flutter and Dart.pptxLecture -Introduction to Flutter and Dart.pptx
Lecture -Introduction to Flutter and Dart.pptx
FarhanGhafoor7
 
Assambly Language and Data Communication with Cell Phone
Assambly Language and Data Communication with Cell PhoneAssambly Language and Data Communication with Cell Phone
Assambly Language and Data Communication with Cell Phone
FarhanGhafoor7
 
Wireless Communication and Cellular Communication
Wireless Communication and Cellular CommunicationWireless Communication and Cellular Communication
Wireless Communication and Cellular Communication
FarhanGhafoor7
 
Fiber Optical Networks and Data Communication
Fiber Optical Networks and Data CommunicationFiber Optical Networks and Data Communication
Fiber Optical Networks and Data Communication
FarhanGhafoor7
 
Wired LANS - Ethernet and Computer Local Area Networks
Wired LANS - Ethernet and Computer Local Area NetworksWired LANS - Ethernet and Computer Local Area Networks
Wired LANS - Ethernet and Computer Local Area Networks
FarhanGhafoor7
 
Class Scheduling using Generative AI.pptx
Class Scheduling using Generative AI.pptxClass Scheduling using Generative AI.pptx
Class Scheduling using Generative AI.pptx
FarhanGhafoor7
 
Ad

Recently uploaded (20)

Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
Kasdorf "Accessibility Essentials: A 2025 NISO Training Series, Session 5, Ac...
National Information Standards Organization (NISO)
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFAExercise Physiology MCQS By DR. NASIR MUSTAFA
Exercise Physiology MCQS By DR. NASIR MUSTAFA
Dr. Nasir Mustafa
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Ad

Programming Fundamentals - Lecture 1.ppt

  • 1. Fundamentals of Programming Lecture 1 Book by : Computer, Architecture and Organizations, 8th Edition ,William Stalling Original Slides by : Adrian J Pullin
  • 3. Objectives • Understand the different types of programming languages. • Understand the basic procedures in a program as input, processing and output. • Understand the importance of variables. • Understand a basic map of the program development cycle.
  • 4. Computer Components • CPU Central Processing Unit • RAM (Random Access Memory) • Mass storage devices • Input devices • Output Devices
  • 5. Software •Application Software – Word Processors – Spreadsheets – Painting programs – Web browsers, email programs •System Software – Operating Systems • Windows • Macintosh OS • Unix • Linux – Drivers Software is comprised of instructions that get a computer to perform a task.
  • 6. Programming Languages • Programming languages allow programmers to code software. • The three major families of languages are:  Machine languages  Assembly languages  High-Level languages
  • 7. Machine Languages • Comprised of 1s and 0s • The “native” language of a computer • Difficult to program – one misplaced 1 or 0 will cause the program to fail. • Example of code: 1110100010101 111010101110 10111010110100 10100011110111
  • 8. Assembly Languages • A step towards easier programming. • Comprised of a set of elemental commands  tied to a specific processor. • Assembly language code needs to be translated to machine language before the computer processes it. • Example: ADD 1001010, 1011010
  • 9. High-Level Languages • High-level languages represent a giant leap towards easier programming. • The syntax of HL languages is similar to English. • Historically, we divide HL languages into two groups:  Procedural languages  Object-Oriented languages (OOP)
  • 10. Procedural Languages • Procedural languages  The focus of such languages is on sequence of activities to be carried out.  Based on specifying the steps the program must take to reach the desired state.  Examples include C, COBOL, Fortran, LISP, Perl, HTML, VBScript
  • 11. Object-Oriented Languages • Object-oriented languages:  Focus on modeling data.  Programmers code using “blueprints” of data models called classes.  Examples of OOP languages include C++, Visual Basic.NET and Java.
  • 12. Compiling • All HL programs need to be translated to machine code  so that a computer can process the program. • Programs may be translated using  a compiler: translated all at once  An interpreter translated line by line • Compiled programs typically execute more quickly than interpreted programs, but have a slower translation speed. • On the other hand, interpreted programs generally translate quicker than compiled programs, but have a slower execution speed.
  • 13. Programming Example • Simple programming problem: Convert a length from feet into meters. • Pseudocode: Input the length of an item, LengthInFeet, in feet and Compute the length of the item in meters: Write “Enter the length in feet” Input LengthInFeet Set LengthInMeters = LengthInFeet * .3048 Write LengthInMeters
  • 14. Programming Example  Partial Code in C:  float LengthInFeet;  LengthInMeters = LengthInFeet * .3048;  printf (“%f”, LengthInMeters);
  • 15. Input & Variables • Input operations get data into the programs • A user is prompted to enter data:  Write “Enter the length in feet”  Input LengthInFeet • Computer programs store data in named sections of memory called variables. • In the example above, the variables are named LengthInFeet & LengthInMeters.  The value of a variable can, and often does, change throughout the program.
  • 16. Variables • Needed because we might want the program to run using different values:  E.g. we might want to calculate LengthInMeters for different values of LengthInFeet  Each value for which computation is to be carried out will be stored in the variable LengthInFeet one-by-one  Referring to the variable LengthInFeet by its name gives the value stored in it.
  • 17. Constants • Many a time we need to used fixed values for certain computations. • E.g. in the program given above  the conversion from miles to meters requires the length in miles to be multiplied by .3048  a value that doesn’t (need to) change  Such values are constants • We may also give names to constants: such constants are called named constants
  • 18. Types of Data • Numeric Data  Integer data, I.e., whole numbers, 10 25 -45 0  Floating point data – have a decimal point 23.0, -5.0 • Character data (alphanumeric)  All the characters you can type at the keyboard  Letters & numbers not used in calculations • Boolean data  TRUE/FALSE
  • 19. Data Processing and Output • LengthInMeters = .3048 * LengthInFeet  The above statement is a processing statement.  Take the value in the variable LengthInFeet,  Multiply by .3048, and  Set the value of the variable LengthInMeters to the result of the multiplication. Also stated as assign the result of multiplication to the variable LengthInMeters • Write LengthInMeters  Output the value in LengthInMeters to the monitor.
  • 20. Assignment Statements • If the variable being assigned to already contains a data value,  the previously stored value is overwritten  E.g. the following statements: Age= 12; Age=15; Have an effect of storing 15 in the variable Age.  Reason: The value 12 (stored as an effect of the first assignment statement) gets overwritten after the execution of the second statement.
  • 21. Assignment Statements • The statement  Age = Age + 1  Changes the value of the variable Age in such a way that the new value is one greater than the previous value. • Working: Take the value of Age, add 1, and store the result back in the same variable.
  • 22. Operations on Data • Operator is a symbol that is used to perform certain operations • Data values on which operation is performed are termed as operands • Operators generally work on many types of variables or constants,  though some are restricted to work on certain types.  some may even exhibit different behaviors with different data types • Operators in C may be:  Unary: Work on single operand  Binary: Work on two operands  Ternary: Work on three operands
  • 23. Operators • C, like most programming languages, supports operators to carry out various kinds of operations • We have operators for:  Arithmetic operations  Type Conversions  Performing Comparisons  Performing Logical Operations  Working on individual bits of data  And many more…
  • 24. Precedence of Operators • Operator precedence:  A set of rules decide the order of operations in an expression  Like BODMAS rule in mathematics  Operator Precedence clarifies unambiguously, which operations should be performed first in a given expression.  Parentheses i.e. () can always be used to improve clarity
  • 25. Associativity of Operators • Operator Associativity: • Rule used for two operators of equal precedence (i.e. same importance) • Associativity may be either of the following  left to right: left operator is evaluated first  right to left: right operator is evaluated first
  • 26. Structured Programming • A method for designing and coding programs in a systematic, organized manner.  • It combines  the principles of top-down design,  modularity and  the use of the three accepted control structures of sequence, repetition and selection.
  • 27. Control Structures • Sequence –in sequential order.  The simplest of control structures – start at the beginning and continue in sequential order. • Selection – selectively execute statements  Called a branch,  it requires a condition to determine when to execute statements.
  • 28. Control Structures  Repetition – repeat statements more than once Called a loop, It needs a stop condition, I.e, the program will continue to loop (repeatedly execute a set of statements) until some condition is met.
  • 29. Counter-Controlled Loop: (Definite Repetition) • If it is known in advance exactly how many times a loop will execute, the repetition is said to be counter- controlled • Counter-controlled loop:  Execute a set of statements repeatedly a specified number of times  The counter may be advanced according to programmers requirements .
  • 30. Event-Controlled Loop: (Indefinite Repetition) • If it is NOT known in advance exactly how many times a loop will execute, the loop is said to be event-controlled. • An event-controlled loop  Terminates when some event occurs.  The event may be based upon: User input Results of calculation And many more….
  • 31. Steps in Developing a Program • Developing a Program: 1. Analyze the problem 2. Design the program 3. Code the program 4. Test the program
  • 32. Step-1 Analyze the Problem  Brewster’s Thousands  The problem: Brewster wants to invest money at a local bank. There are many options such as interest rates, terms of deposit, compounding frequencies. He needs a program to compute, for any given initial investment, the final maturity (value) of the deposit. What are the inputs? (given data) What are the outputs? (required data) How will we calculate the required outputs from the given inputs?
  • 33. Step-2 Design the Program • Create an outline of the program • An algorithm – a step by step procedure that will provide the required results from the given inputs. • Algorithm Examples: Instructions on how to make a cake, use the bank’s ATM, etc.
  • 34. Step-3 Code the Program • Once the design is completed, write the program code. • Code is written in some programming language such as BASIC, Pascal, C++, Java, etc.
  • 35. Errors in Development • While writing a program, certain errors may get induced in the code. • Errors may be categorized as :  Syntactical Errors – Incorrect Syntax (wrong grammar), i.e., breaking the rules of how to write the language Forgetting punctuation, misspelling keyword The program will not run at all with syntax errors  Semantic Errors: Incorrect Logic: Using an incorrect formula, incorrect sequence of statements, etc. The program runs, but does not produce the expected results.
  • 36. Step-4 Testing the program • Purpose: Locate any errors (bugs) / problems • Most of the work should be done before the phase begins – creating of a testing document – telling what to test & how. • Two types of testing:  Testing for errors  Quality testing • Testing is done throughout the development cycle • Desk-checking, or code walkthrough is performed to locate errors in the code.  Pretend you are the computer and execute your own code. • Ultimate test is to run the program to see if the outputs are correct for the given inputs.
  • 37. Good Programming Practice • It is best not to take the “big bang” approach to coding. • Use an incremental approach by writing your code in incomplete, yet working, pieces. • For example, for your projects,  Don’t write the whole program at once.  Just write enough to display the user prompt on the screen.  Get that part working first (compile and run).  Next, write the part that gets the value from the user, and then just print it out.
  • 38. Modular Programming • Determine the major tasks that the program must accomplish.  Each of these tasks will be a module. • Some modules will be complex themselves, and they will be broken into sub-modules,  and those sub-modules may also be broken into even smaller modules. • This is called top-down design
  • 39. Code Modules • A module is an independent, self-contained section of code that performs a single task. • The main module is the module that drives the application.  It “controls” all other modules.  Typically, the main module calls other modules in order to have them perform certain tasks.
  • 40. Program Control & Modules • When the main module calls another module, program control transfers to the called module. • Program control cedes back to the main module when the called module finishes.
  • 41. Structure Chart • A structure chart shows what modules exist and how they are related. • A structure chart is a top-down modular design tool • It is used in structured programming to arrange program modules into a tree • It’s a good idea to keep modules short – about 1 page per module. • We will have very small modules while getting comfortable with programming.
  • 42. Documentation • Internal Documentation  Comments explain to the reader the logic and decision processes of the programmer.  Comments are ignored by an interpreter or compiler. • External Documentation  External documentation includes a user’s guide and, typically, a more technical system administrator’s guide.
  • 43. Over to C Fundamentals…
  • 45. Objectives • History of C • Characteristics of C • Converting a C Program to Executable • Dissecting a simple C Program • Defining Variables in C • Printing Out and Inputting Variables • Constants & Literals
  • 46. History of C • Developed by Brian Kernighan and Dennis Ritchie of AT&T Bell Labs in 1972 • In 1983 the American National Standards Institute began the standardization process • In 1989 the International Standards Organization continued the standardization process • In 1990 a standard was finalized, known simply as “Standard C”
  • 47. Features of C • C can be thought of as a “high level assembler” • Most popular programming language for writing system software • Focus on the procedural programming paradigm, with facilities for programming in a structured style • Low-level unchecked access to computer memory via the use of pointers • And many more…
  • 48. Writing C Programs • A programmer uses a text editor to create or modify files containing C code. • Code is also known as source code. • A file containing source code is called a source file. • After a C source file has been created, the programmer must invoke the C compiler before the program can be executed (run)
  • 49. Getting an executable program • The process of conversion from source code to machine executable code is a multi step process. • If there are no errors in the source code, the processes called compilation & linking produce an executable file • To execute the program, at the prompt, type <executable file name>
  • 50. Conversion from .C to executable 1. Preprocessing 2. Compilation 3. Linking
  • 51. Stage 1: Preprocessing  Performed by a program called the preprocessor  Modifies the source code (in RAM) according to preprocessor directives (preprocessor commands) embedded in the source code  Strips comments and white space from the code  The source code as stored on disk is not modified
  • 52. Stage 2: Compilation  Performed by a program called the compiler.  Checks for syntax errors and warnings  Translates the preprocessor-modified source code into object code (machine code).  Saves the object code to a disk file  If any compiler errors are received, no object code file will be generated.  An object code file will be generated if only warnings, not errors, are received.
  • 53. Stage 3: Linking • Combines the program object code with other object code to produce the executable file. • The other object code can come from the – Run-Time Library – other libraries – or object files that you have created. • Saves the executable code to a disk file. • If any linker errors are received, no executable file is generated.
  • 54. Developing a C Program Modified Source Code in RAM Source File pgm.c Program Object Code File Executable File Preprocessor Compiler Linker Editor
  • 55. A Simple C Program /* Filename: hello.c Author: -------- Date written: --/--/---- Description: This program prints the greeting “Hello, World!” */ #include <stdio.h> int main ( void ) { printf ( “Hello, World!n” ) ; return 0 ; }
  • 56. Structure of a C Program program header comment preprocessor directives (if any) int main ( ) { statement(s) return 0 ; }
  • 57. Explanation #include <stdio.h> /* comment */ int main(void) { printf("Hellon"); printf("Welcome to the Course!n"); return 0; } Hello Welcome to the Course! tells compiler about standard input and output functions (i.e. printf + others) main function “begin” “end” flag success to operating system
  • 58. Tokens • The smallest element in the C language is the token. • It may be a single character or a sequence of characters to form a single item.
  • 59. Tokens can be any of: • Numeric Literals • Character Literals • String Literals • Keywords • Names (identifiers) • Punctuation • Operators
  • 60. Numeric Literals • Numeric literals are an uninterrupted sequence of digits • May contain  A period,  A leading + or – sign  A scientific format number  A character to indicate data type • Examples:  123  98.6  1000000
  • 61. Character Literals • Singular! • One character defined character set. • Surrounded on the single quotation mark. • Examples:  ‘A’  ‘a’  ‘$’  ‘4’
  • 62. String Literals • A sequence characters surrounded by double quotation marks. • Considered a single item. • Examples:  “UMBC”  “I like ice cream.”  “123”  “CAR”  “car”
  • 63. Keywords • Sometimes called reserved words. • Are defined as a part of the C language. • Can not be used for anything else! • Examples:  int  while  for
  • 64. Reserved Words (Keywords) in C • auto • case • const • default • double • enum • float • goto • int • register • short • sizeof • struct • typedef • unsigned • volatile • break • char • continue • do • else • extern • for • if • long • return • signed • static • switch • union • void • while All the C keywords are in small case
  • 65. Names / Identifiers • Variables must be declared before use and immediately after “{” • Can be of anything length, but only the first 31 are significant (A very long name is as bad as a very short, un- descriptive name). • Are case sensitive: abc is different from ABC • Must begin with a letter and the rest can be letters, digits, and underscores. • Cannot be a reserved word.
  • 66. Which Are Legal Identifiers? AREA area_under_the_curve 3D num45 Last-Chance #values x_yt3 pi num$ %done lucky*** continue Float integer
  • 67. Punctuation • Semicolons, colons, commas, apostrophes, quotation marks, brackets, and parentheses. • ; : , ‘ “ { } ( )
  • 68. Things to remember • Statements are terminated with semicolons • Indentation is ignored by the compiler • C is case sensitive - all keywords and Standard Library functions are lowercase
  • 70. Topics • Variables  Naming  Declaring  Using • The Assignment Statement • Constants • Data Input & Output
  • 71. Naming Conventions • Begin variable names with lowercase letters • Use meaningful names • Separate “words” within identifiers with underscores or mixed upper and lower case. • Use all uppercase for symbolic constants (used in #define preprocessor directives). • Be consistent!  In addition to the conventions one must follow all the naming rules as discussed in previous sessions. Note: symbolic constants are not variables, but make the program easier to read.
  • 72. Declaring Variables • All variables need to be declared before they are used. • The declaration statement includes (apart from other information) the data type of the variable. • Examples of variable declarations:  int meatballs ;  float area ;
  • 73. It is required to declare variables before using as compiler needs this information Purpose!!! Declaring Variables  When we declare a variable  Space is set aside in memory to hold a value of the specified data type  That space is associated with the variable name a unique address  Visualization of the declaration int age ; age FE07 int garbage
  • 74. More About Variables  Basic data types available in C are:  char: stores single character  int: stores whole numbers  float: store floating point numbers  double: store floating point numbers with higher precision
  • 75. Integer Types in C • C supports different kinds of integers, like  signed int  unsigned int  long int  short int  And more… • Limits depend upon size in bytes which in turn depends upon environment  maxima and minima defined in “limits.h” • We can work with different bases as well (octal, hexadecimal).
  • 76. The int Data Type (Contd.)  Use  scanf (“%i”, &ch) ;  to read a single integer into the variable ch.  Use  printf(“%i”, ch) ;  to display the value of an integer variable.
  • 77. The char Data Type • The char data type holds a single character.  char ch; • Example assignments:  char grade, symbol;  grade = ‘B’;  symbol = ‘$’; • The char is held as a one-byte integer in memory. The ASCII code is what is actually stored, so we can use them as characters or integers, depending on our need.
  • 78. The char Data Type (Contd.)  Use  scanf (“%c”, &ch) ;  to read a single character into the variable ch.  Use  printf(“%c”, ch) ;  to display the value of a character variable.
  • 79. char I/O  #include <stdio.h>  int main ( )  {  char ch ;  printf (“Enter a character: “) ;  scanf (“%c”, &ch) ;  printf (“The value of %cn.”, ch) ;  return 0 ;  } Input: A Output : The value of A is 65.
  • 80. Real Types In C  C supports different kinds of reals  maxima and minima are defined in “float.h” type format minimum maximum float %f %e %g FLT_MIN FLT_MAX double %lf %le %lg DBL_MIN DBL_MAX long double %Lf %Le %Lg LDBL_MIN LDBL_MAX
  • 81. Notes About Variables • You must not use a variable until you somehow give it a value. • You can not assume that the variable will have a value before you give it one.  Some compilers do, others do not! This is the source of many errors that are difficult to find.
  • 83. Arithmetic Operators and their Usage Name Operator Example Addition + num1 + num2 Subtraction - initial - spent Multiplication * fathoms * 6 Quotient of Division / sum / count Remainder of Division % m % n % can not be used with reals
  • 84. Relational Operators < less than > greater than <= less than or equal to >= greater than or equal to == is equal to != is not equal to  Relational expressions evaluate to the integer values:  1 (true) on success  0 (false) on failure
  • 85. Logical Operators • At times we need to test multiple conditions in order to make a decision. • Logical operators combine simple conditions to make complex conditions. • Result into a 0 (false) or 1 (true)  && AND if ( x > 5 && y < 6 )  || OR if ( z == 0 || x > 10 )  ! NOT if (! (age > 42) )
  • 86. Truth Table for && Expression1 Expression2 Expression1 && Expression2  0 0 0  0 nonzero 0  nonzero 0 0  nonzero nonzero 1 Exp1 && Exp2 && … && Expn will evaluate to 1 (true) only if ALL sub-conditions are true.
  • 87. Truth Table for || Expression1 Expression2 Expression1 || Expression2  0 0 0  0 nonzero 1  nonzero 0 1  nonzero nonzero 1 Exp1 || Exp2 || … || Expn will evaluate to 1 (true) if any one of the sub-conditions is true.
  • 88. Truth Table for !  Expression ! Expression  0 1  nonzero 0
  • 89. Precedence/Associativity Table Operator Associativity () [] -> . left to right ! ~ ++ -- - + (cast) * & sizeof right to left * / % left to right + - left to right << >> left to right < <= >= > left to right == != left to right & left to right | left to right ^ left to right && left to right || left to right ?: right to left = += -= *= /= %= etc right to left , left to right + - : unary
  • 91. Functions • Functions are named code blocks that make reusability of code possible. • These are parts of programs that  Perform a well defined task.  At times, expect some information in order to complete the task.  The information is provided in form of parameters (arguments)  Can return a value to convey result / status of execution
  • 92. I/O Example #include <stdio.h> int main(void) { int a, b; printf("Enter two numbers: "); scanf("%i %i", &a, &b); printf("%i - %i = %in", a, b, a - b); return 0; } create two integer variables, “a” and “b” read two integer numbers into “a” and “b” write “a”, “b” and “a-b” in the format specified Enter two numbers: 21 17 21 - 17 = 4
  • 93. Displaying Variables • A Function that allows us to display formatted data:  printf( ). • Needs two pieces of information to display things.  How to display it  What to display • printf( “%fn”, diameter );
  • 94. printf( “%fn”, diameter ); • The name of the function is “printf”. • Inside the parentheses are two comma separated parameters:  Format specifier: indicates the format in which the output will be produced %f => a floating point value n => a new-line character (escape sequence)  The expression diameter whose value is to be displayed.
  • 95. scanf (“%f”, &meters) ; • This function is used to  read values from the standard input; and  Store them in memory. • The scanf( ) function also needs two items:  The input specification “%f”.  The address of the memory location where the information is to be stored. • We can input more than one item at a time if we wish, as long as we specify it correctly!!! • Notice the “&” in front of the variable name. Can you explain its significance!
  • 96. Format Specifiers • Format specifiers are normal strings with embedded “conversion specifications” which are placeholders for arguments • Conversion specifications are a ‘%’ and a letter with an optional set of arguments in between the ‘%’ and letter. Why are these required!!!
  • 97. Selection: the if statement if ( condition ) { statement(s) /* body of the if statement */ } • The braces are not required if the body contains only a single statement. • However, they are a good idea and are required by the C Coding Standards.
  • 98. Examples  if ( age >= 18 )  {  printf(“Vote!n”) ;  } if ( value == 0 ) { printf (“The value you entered was zero.n”); printf (“Please try again.n”) ; }
  • 100. Selection: the if-else statement if ( condition ) { statement(s) /* the if clause */ } else { statement(s) /* the else clause */ }
  • 101. Example  if ( age >= 18 )  {  printf(“Vote!n”) ;  }  else  {  printf(“Maybe next time!n”) ;  }
  • 102. Repetition Structure • There are three repetition structures in C: -  the while loop  the for loop  the do-while loop. • Either of these structures may be used for counter-controlled / event-controlled logic, but • The syntax of for loop makes it more suitable for counter- controlled repetition • And, The syntax of while / do-while loops makes them more suitable for event-controlled repetition
  • 103. The while Repetition Structure  while ( condition )  {  statement(s)  } • The braces are not required if the loop body contains only a single statement. • However, they are a good idea and are required by the C Coding Standards.
  • 104. while Loop • The simplest C loop is the while • Parentheses must surround the condition • Condition could be based on user input or some calculation • Braces must be added if more statements are to be executed total= 0; while (number != -1) { total = total + number; printf(“Enter another number: “) ; scanf(“%d”, &number) ; }
  • 105. The for Loop Repetition Structure • The for loop handles details of the counter-controlled loop “automatically”. • The following are handled within the for loop structure  initialization of the the loop control variable,  the termination condition test, and  control variable modification.  for ( i = 1; i < 101; i = i + 1)  {   }  initialization test modification
  • 106. A for Loop That Counts From 0 to 9  for ( i = 0; i < 10; i = i + 1 )  {  printf (“%dn”, i) ;  }
  • 107. We Can Count Backwards, Too  for ( i = 9; i >= 0; i = i - 1 )  {  printf (“%dn”, i) ;  }
  • 108. Count By 2’s or 7’s or Whatever  for ( i = 0; i < 10; i = i + 2 )  {  printf (“%dn”, i) ;  }
  • 109. The do-while Repetition Structure do {  statement(s) } while ( condition ) ; • The body of a do-while is ALWAYS executed at least once. • Is this true of a while loop? • What about a for loop?
  • 110. Example  do  {  printf (“Enter a number, 0 to terminate: “);  scanf (“%d”, &number) ;  if (number == 1)  printf (“n Do Somethingn”) ;  else if (number == 2)  printf (“n Do Something Elsen”) ;  } while ( num != 0 );
  • 111. An Equivalent while Loop  printf (“Enter a number, 0 to terminate:“) ;  scanf (“%d”, &number) ;  while ( number != 0 )  {  if (number == 1)  printf (“n Do Somethingn”) ;  else if (number == 2)  printf (“n Do Something Elsen”) ; printf (“Enter a number , 0 to terminate:“) ; scanf (“%d”, &number) ;  } Notice that using a while loop in this case requires a priming read.
  • 112. An Equivalent for Loop  printf (“Enter a positive number, 0 to terminate: “) ;  scanf (“%d”, &number) ;  for ( ; number != 0; )  {  if (number == 1)  printf (“n Do Somethingn”) ;  else if (number == 2)  printf (“n Do Something Elsen”) ; printf (“Enter a number , 0 to terminate:“) ; scanf (“%d”, &number) ;  } A for loop is a very awkward choice here because the loop is event-controlled.
  • 113. So, Which Type of Loop Should One Use? • Use a for loop for counter-controlled repetition. • Use a while or do-while loop for event-controlled repetition.  Use a do-while loop when the loop must execute at least one time.  Use a while loop when it is possible that the loop may never execute.
  • 114.  That’s all for now…  We are ready for writing a simple C program.