SlideShare a Scribd company logo
1 of 88
Download to read offline
Slots 05-06-07: Lesson 3
Basic Logics: Module-C-Logic
Logic Constructs /Programming Style /Walkthroughs
Objectives
• How to develop a C- program? → Logic
constructs
• When I develop a C-program, what are things
that I should follow? → Programming styles
• How I can understand a program? →
Walkthroughs
Contents
1- Logic constructs
2- Programming Styles
3-Walkthroughs
4-Bonus – Redirect a
Program ( a technique is
used in the ACM Contest)
3
Review
• A variable is a name referencing to a memory
location.
• A data type defines: How the values are stored
and how the operations on those values are
performed.
• 4 primitive data types in C: int, char, float,
double
• Data stored are in binary format
• Declare a variable in C: type var [=initialValue];
• An identifier begin with a letter or ‘_’, the later
symbols can be letters, digits and ‘_’
• An user-defined identifier must not a C
keyword.
• Expression is a valid association of constants,
variables, operators and functions.
4
Basic Logics
Creativity in Algorithms
• Creativity has to do with both the process you invent (an algorithm) to
solve a new problem in a given context and how you implement that
• Selection:
• most commonly seen in if-statements
• The JUMP...IF command in the Human Machine Language is a form of
selection. It gives us a way to compare two things (numbers) and take
action if one thing was true.
• Iteration:
• also known as "looping“
• The JUMP command in the Human Machine Language allows us to
move to a different point in the program and start executing from
there. This allows us to re-use lines of code, and this is a form of
iteration or looping.
• Sequencing:
• Sequencing is the application of each step of an algorithm in the
order in which the statements are given.“
• The sequencing is simply implied by the fact that we number the
instructions with the intent to execute them in order.
5
Basic Logics
Logic Constructs
• Logic constructs: Expressions enable us to write programs
that perform creative algorithm (calculations and execute
statements) in a sequential order.
• Structured Programming
• Logic constructs:
• Sequence constructs
• Selection constructs
• Iteration constructs
6
Basic Logics
Structured Programming
• Structure of a program code
should be organized in a manner
so that it is understandable,
testable and readily modifiable.
➔It consists of simple logical
constructs, each of which has one
entry point and one exit point.
• The beginning step for
developing a program is
DESIGN using
• pseudo-coding or
• flow charting
7
Basic Logics
Structured Programming: Pseudo-code
• Example: Calculating the absolute value of an integer
inputted from the keyboard.
1. Prompt the user for an integer value
2. Accept an integer value from the user
and store it in x
3. If x is negative number then x = -x
4. Display x
8
Basic Logics
Structured Programming: Flowcharting
• A flowchart is a diagram that depicts
the “flow of control” of a program.
• Three types of symbols in this
flowchart
• rounded rectangles
• parallelograms
• a rectangle
• Terminals
• represented by rounded
rectangles
• indicate a starting or ending point
9
Basic Logics
Structured Programming: Flow chart symbols
• Flow chart symbols Selection (Decision diamond)
• A 2-way branch. An if or another decision. The condition appears inside the diamond.
Example: x<y? Two arrows lead out of the decision. These arrows may be labeled
with Yes and No, meaning the then and else branch, respectively.
• Flow chart symbols Iteration
• Start of a repeated block. A for statement or similar. The end of the loop body connects
back to the loop symbol. How many times the loop executes depends on what is written
inside the loop symbol.
10
Basic Logics
Sequence Constructs
• Tells the processor which statement is to
be executed next.
• the statement follows first statement
in the program.
• use a goto statement to jump
• computer programming (1950's to
early 1960's)
• A sequence is either a simple statement
or a code block.
• Simple Statements
expression ;
• Code Blocks: A code block is a set of
statements enclosed in curly braces.
{statements; }
11
Basic Logics
Creative thinking
• Write a C program to check
whether a given number is even or
odd.
• Write a C program to check
whether a student can pass or fail
based on his/her mark
• Selection Constructs
Selection Constructs
13
Basic Logics
• Gives a program the ability to
choose which instruction(s) to
next execute based on
conditions
• Types:
• single-selection statement (if
statement)
• double-selection statement
(if-else statement)
• multiple-selection statement
(nested if-else)
• multiple-selection statement
(switch/case)
• If the condition is a value
of char/integer
Selection Constructs : if statement
14
Basic Logics
• single-selection statement (if statement)
• Syntax
if (condition)
{
statements;
}
condition
evaluated
statement
true
false
• The if selection statement either
performs statements if a condition is
true or skips the statements if the
condition is false.
Selection Constructs: if Examples
15
Basic Logics
Selection Constructs : if-else statement
16
Basic Logics
• double-selection statement (if-else statement)
• Syntax
if (condition)
{ statements 1;
} else
{ statements 2;
}
• The if…else selection statement
performs statements 1 if a condition is
true and performs a statements 2 if
the condition is false.
condition
statement1
true false
statement2
Selection Constructs: if-else Examples
17
Basic Logics
Selection Constructs: if … else errors
The compiler can not
determine the if statement
before the else statement.
18
Basic Logics
Selection Constructs : nested if-else statement
19
Basic Logics
• multiple-selection statement
• Syntax
if (condition 1)
{ statements;
}
else if (condition2)
{ statements;
}
else
{ statements;
}
Nested if
• Buying N T-shirts with promotion:
• N<=3: 120000$/item
• From 4th to 6th:
90000$/item
• From 7th to 10th:
85000$/item
• From 11th : 70000$/item
• Describe the expression that
will compute the paid value.
Let N: number of T-shirts bought, t: money must be paid.
if (N <=3) t = N*120000 ;
else if (N<=6) t= 3*120000 + (N-3) * 90000;
else if (N<=10)
t= 3*120000 + 3*90000 + (N-6)*85000;
else
t= 3*120000 + 3*90000 + 4*85000 + (N-10)*70000;
Selection Constructs: Dangling Else
• Ambiguity may arise in the case of nested if else constructs.
• The rule in C is that an else always belongs to the innermost if
available. Use { } to explicitly determine statements
20
Basic Logics
Exercises
• Write a C program to check whether a
given number is even or odd.
• Write a C program to accept the height
of a person in centimeter and categorize
the person according to their height.
• Write a C program to check whether a
character is an alphabet, digit or special
character.
Please Goto Workshop 02
Exercises Code
Selection Constructs: Operator ? :
24
Basic Logics
(condition) ? True_Value : False_Value
Selection Construct: The switch statement
switch (variable or expression)
{
case constant :
statement(s);
break;
case constant :
statement (s);
break;
default:
statement (s);
}
char / int
25
Basic Logics
• The switch statement evaluates an expression, then attempts to match
the result to one of several possible cases
• The match must be an exact match
• A break statement causes control to transfer to the end of the switch
statement
• If the break statement is missed, the next statements are executed
until a break is detected or all statements in the body of the switch are
executed.
• Each case is an entry of a selection
• If the break statement is missed, the next statements are executed
until a break is detected or all statements in the body of the switch are
executed.
• Each case is an entry of a selection
Selection Construct: The switch statement
26
Basic Logics
If input is 8, what are outputs?
a) 200000 , 2
b) 300000, 3
c) 0, 0
d) 1000000, 4
e) 1500000, 10
f) None of the others
If input is 7, what are outputs
Selection Construct: The switch statement
• Write a program that allows
user inputting a simple
expression containing one of
four operators +, -, *, / then
the result is printed out to
the monitor.
• Input format:
num1 operator num2,
Example: 4*5
27
Basic Logics
Exercises
• Write a program in C which is a Menu-
Driven Program to compute the area of
the various geometrical shape.
• Write a program in C which is a Menu-
Driven Program to perform a simple
calculation.
Please Goto Workshop 02
Exercises Code
Exercises Code
Chapter 2: Program Correctness and Efficiency 32
Syntax Errors
• Syntax errors: grammatical mistakes
in a program
• The compiler detects syntax errors
• Executable code will not be created
until you correct all of the syntax
errors
• Most frequent syntax errors are:
• Missing Parenthesis (})
• Printing the value of variable
without declaring it
• Missing semicolon
Creative
thinking
• Want to do some
repetitive sequence of
actions:
• print vertical line of *s
*
*
*
*
*
• Corresponding
program:
printf(“*n”);
printf(“*n”);
printf(“*n”);
printf(“*n”);
printf(“*n”);
Creative
thinking
• Write a program in
C to display the first
10 natural numbers.
• Corresponding
program:
printf(“1 n”);
printf(“2 n”);
printf(“3 n”);
printf(“4 n”);
printf(“5 n”);
printf(“6 n”);
printf(“7 n”);
printf(“8 n”);
printf(“9 n”);
printf(“10 n”);
Creative
thinking
How could you write a
program that display
4000 number?
Iteration (loop) Constructs
• A loop is a programming construct that executes lines of code
repeatedly while condition is met.
• Three loop constructs make it possible to iterate over code or
execute it more than once:
• for loops.
• while loops.
• do … while loops.
• Structure of a loop:
• First: Initial block.
• Second: Condition.
• Third: Task in each execution.
• Types of iteration: fixed loops, variable loops
36
Basic Logics
Iteration (loop) Constructs
• Structure of a loop:
• First: Initial block: i=0
• Second: Condition: i<=10
• Third: Task in each execution: printf(“%d”,i); i=i+1;
• Types of iteration: fixed loops, known the number of repetition
line of code.
37
Basic Logics
Creative
thinking
How could you write a
program that would read
in five values and display
the average?
Creative
thinking
• How hard would it be to change
the program to average four
thousand values?
• How hard would it be to change
the program so it could read in
the number of values to be read
and then compute the average?
Iteration…
40
Basic Logics
• Structure of a loop:
• First: Initial block:
i=0,S=0
• Second: Condition: i<=n
• Third: Task in each
execution: S=S+i;i=i+1;
• Types of iteration: fixed
loops, known the number
of repetition line of code.
Iteration…
• What we need to know for a
loop
- How many time that these
lines of code need to be
executed?
• Identify a loop for an
expression:
• Left side → Initial block
• Right side → Condition to
run these lines of code
• An operation and
preparations for the next
iteration: Tasks (lines of
code) in each iteration.
41
Basic Logics
Left side
Right side
An operation
Iteration…
42
Basic Logics
Iteration: for statement
InitBlock
Condition?
Task1
Task2
yes
no
43
Basic Logics
• A for loop is used when a loop is to be executed
a known number of times
• for (InitBlock; Condition; Task2) Task1;
• for ( Init1, Init2; Condition ; Task1, Task2);
• InitBlock;
for ( ; Condition ; Task2) Task1;
• InitBlock;
for ( ; Condition ;)
{
Task1;
Task2;
}
• The InitBlock set the initial
value of the loop control
variable.
• The Condition test the value
of the loop control variable.
• The Task2 update the loop
control variable
• The Task1 might be the
repeated Tasks in some
cases
The condition will be tested
before tasks are performed.
Iteration for() Example
• Write a program in C to display the first 10 natural numbers.
44
Basic Logics
Iteration for() Example
• Write a program that will print out the
ASCII table.
ASCII code : 0 → 255
Initialize: int code =0
Condition: code <256
Task:
Print the code using 4 format: %c, %d, %o, %X
code = code +1
45
Basic Logics
Iteration for() Example Code
46
Basic Logics
Iteration for() Example
• Write a program in C to display the first 10 natural numbers.
47
Basic Logics
Iteration for() Example
• Write a program that will calculate 1+2+3+…+n.
Accepted variable: int n
Sum 1 .. N → int sum
Algorithm
Accept n
Loop:
Initialize i=1, sum=0
Condition i<=n
Tasks: sum += i; i++;
Print out sum
48
Basic Logics
Exercises
• Write a program in C to display the n
terms of odd natural number and their
sum like:
1 3 5 7 ... N
• Write a program in C to display the n
terms of harmonic series and their
sum. The series is :
1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms
Basic Logics 49
Exercises Codes
50
Basic Logics
Exercises
• Write a program in C to Check Whether
a Number can be perfect Numbers.
Basic Logics 51
Exercises(nested loop)
• nested loop: A loop placed inside another
loop.
• Write a program in C to make such a pattern like
right angle triangle with “*”.
Basic Logics 52
Iteration: while() statements
The condition will be tested
after tasks are performed.
/* Initializations */
while (condition)
{ statements;
}
53
Basic Logics
• If the condition is true, the
statement is executed
• Then the condition is
evaluated again, and if it is
still true, the statement is
executed again
• The statement is executed
repeatedly until the
condition becomes false
We can test multiple conditions
using logical operator inside while
loop
InitBlock
Condition?
Task1
Task2
yes
no
while() statements
Exercises Codes
Basic Logics 55
Iteration: do…while() statements
The condition will be tested
after tasks are performed.
/* Initializations */
do
{ statements;
}
while (condition) ;
InitBlock
Condition?
Task1
Task2
yes no
56
Basic Logics
• The statement is executed
repeatedly while the
condition becomes false
Computer Science: A Structured
Programming Approach Using C 57
while() vs do…while() statements
• First, the while statement evaluates expression, which must return a boolean value.
If the expression returns true, the while statement executes the statement(s) in
the while block. The while statement continues testing the expression and executing
its block until the expression returns false.
• Instead of evaluating the expression at the top of the loop, do-while evaluates the
expression at the bottom. Thus, the statements within the block associated with
a do-while are executed at least once.
Iteration do while()
• Write a program that will print
out the sum of integers
inputted by user. The input will
terminate if user enters the
value 0.
Nouns: inputted integer → int x,
sum of integers → int
sum
Tasks (algorithm)
Begin
sum =0
do
{ accept x;
sum += x;
}
while (x!=0);
Print out sum
End
Implement it
by yourself.
58
Basic Logics
The following program print numbers
between 1 and 100 which are multiple
of 3 using the do while loop:
Iteration
• Write a program that permits user entering some characters until the ENTER
key (code 10) is pressed. The program will print out the number of digits,
number of letters, number of other keys were pressed. Accept a character:
c=getchar();
Nouns:
character inputted → char c, Number of digits → int noDigits
Number of letters → noLetters, Number of other keys → noOthers
#define ENTER 10
Algorithm
Begin
noDigits = noLetters = noOthers = c= 0
printf(“Enter a string:”);
While (c!=ENTER)
{ accept c;
if ( c>=‘0’ && c <=‘9’) noDigits++;
else if ( (c>=‘a’ && c <=‘z’) || (c>=‘A’ && c <=‘Z’) ) noLetters++;
else noOthers++;
}
Print out noDigits, noLetters, noOthers
End
Implement
it by
yourself.
The while statement is
intentionally used. So,
c=0 is assigned and the
condition c!=ENTER is
evaluated to TRUE
59
Basic Logics
Input form:
abc1234fGH+-*/?(ENTER)
Iteration Summary
• When a loop is needed, what loop statement should be
used?
➔ All of them can be used to satisfy your requirement.
60
Basic Logics
Iteration: Break/ Bypass a loop
61
Basic Logics
Iteration Constructs: Flags
• The one entry, one exit principle is fundamental to
structured programming.
• C includes three keywords that allow jumps across
statements: goto, continue, and break. Using any of these
keywords, except for break in a switch construct, violates
the one entry, one exit principle of structured
programming.
62
Basic Logics
Iteration Constructs: Flags…
• To improve readability, programmers advocated:
• the use of whitespace to identify the logical structure of
the code
• the abolition of all goto statements
• the abolition of all continue statements
• the abolition of all break statements, except with switch
• A technique for avoiding jumps is called flagging. A flag is a
variable that keeps track of a true or false state.
63
Basic Logics
Iteration Constructs: Flags…
Use if instead of continue
64
Basic Logics
Iteration Constructs: Flags…
Loop infinitively
65
Basic Logics
Iteration Constructs: Flags…
No flag is
used.
A flag is used.
66
Basic Logics
Programming Styles
• Habits in programming
• A well-written program is a pleasure to read. Other
programmers can understand it without significant
effort. The coding style is consistent and clear
throughout.
• Develop your own style guide or adopt the style outlined
here or elsewhere, but adopt some style.
Recommendations on
• Naming
• Indentation
• Comments
• Magic Values
• General Guidelines
67
Basic Logics
Programming Styles: Naming
•Adopt names that are self-descriptive so that
comments clarifying their meaning are unnecessary
•Use names that describe identifiers completely,
avoiding cryptic names
•Prefer nouns for variable names
•Keep variable names short - studentName rather
than theNameOfAStudent
•Keep the names of indices very short - treat them as
mathematical notation
68
Basic Logics
Programming Styles: Indentation
•Indent the body of any construct that is embedded
within another construct. For example,
•Use in-line
opening braces or
start opening
braces on a
newline but don't
mix the two
styles.
69
Basic Logics
Programming Styles: Comment
•Use comments to declare what is done, rather than
describe how it is done.
•Comments introduce what follows.
•Keep them brief and avoid decoration.
70
Basic Logics
Programming Styles: Magic Values
•These may be mathematical constants, tax rates,
default values or names.
•To improve readability, assign symbolic names to
these magic values and refer to the symbolic names
throughout the code.
•Use the directive
#define SYMBOLIC_NAME value
71
Basic Logics
Programming Styles: Magic Values…
• Compiler Idiosyncracies
• Use #define to manage idiosyncracies (đặc điểm) across
platforms.
• For example, the Borland 5.5 compiler does not recognize
the long long data type. Instead, it recognizes an _int64
data type. To improve portability, #define the data type
using a symbolic name such as LONG_LONG and embed
that name throughout our code.
72
Basic Logics
Programming Styles: Guidelines
• Limit line length to 80 characters - both comments and
code
• Avoid global variables
• Select data types for variables wisely and carefully
• Initialize a variable when declaring it only if the initial
value is part of the semantic of the variable.
• If the initial value is part of an algorithm, use a separate
assignment statement.
• Avoid goto, continue, break except in switch.
• Avoid using the character encodings for a particular
machine.
• Use a single space or no spaces either side of an
operator.
73
Basic Logics
Programming Styles: Guidelines
•Use in-line opening braces or start opening braces
on a newline but don't mix the two styles.
•Initialize iteration variables in the context of the
iteration
•Avoid assignments nested inside logical expressions
•Avoid iterations with empty bodies - reserve the
body for the algorithm
•Limit the initialization and iteration clauses of a for
statement to the iteration variables
•Distribute and nest complexity
74
Basic Logics
Programming Styles: Guidelines
•Avoid fancy algorithms that may be efficient but are
difficult to read
•Add additional comments where code has been fine
tuned for efficient execution
•Add an extra pair of parentheses where an
assignment is also used as a condition
•Remove unreferenced variables
•Remove all commented code and debugging
statements from release and production code
75
Basic Logics
3- Walkthroughs
• Understand code is a skill of programmer.
• To understand code, we should know how the code
execute.
• To know how the code execute, we should perform each
instruction.
• A walkthrough is
• a record of the changes that occur in the values of
program variables as a program executes and
• a listing of the output, if any, produced by the program.
Ways to perform a walkthrough
• Memory Map → You knew that
• Walkthrough Tables → A simpler way
76
Basic Logics
Walkthroughs: Demo.
77
Basic Logics
Walkthroughs: Demo.
int n, i, S=0;
scanf(“%d”, &n);
for (i=1; i<=n; i+=3)
if (i%2!=0 && i%3!=0) S+=i;
printf(“%d”, S);
What is the output if the input is 15?
n 15
i 1 4 7 10 13 16
S 0+1 → 1 1+7 → 8 8+13→21
S=21
78
Basic Logics
Walkthroughs: Demo.
int m,n, i, S=0;
scanf(“%d%d”, &n, &m);
for (i=m; i<=n; i++) S+=i;
printf(“%d”, S);
What is the output if the input are 8 12?
Test the program:
int m,n, i, S=0;
scanf(“%da%d”, &n, &m);
for (i=m; i<=n; i++) S+=i;
printf(“%d”, S);
What is the output if the input are 8a12?
Modify Input
“%d %d” 12 8
“%d%d” 12 8
“%d%d” 12
8
“%d-%d” 12-8
79
Basic Logics
Walkthroughs: Demo.
Study the following code:
int n=15;
int S=0;
i=1;
while (i<2*n)
{ S+= i;
i*=4;
}
Give your opinion.
a) S=21
b) S= 85
c) A syntax error
80
Basic Logics
i= 1
2
3
4
5
6
Extra Demo: Print star characters
Print out 1*, “n”
Print out 2*, “n”
Print out 3*, “n”
Print out 4*, “n”
Print out 5*, “n”
Print out 6*, “n”
i
Accept N;
for ( i=1; i<=N; i++)
{ for (j=1; j<=i; j++) printf(“*”);
printf (“n”);
}
N=6
*
**
***
****
*****
******
81
Basic Logics
Extra Demo: Multiplication Table
N=5
5x 1= 5
5x 2=10
5x 3=15
5x 4=20
5x 5=25
5x 6=30
5x 7=37
5x 8=40
5x 9=45
5x10=50
Accept n;
for ( i=1; i<=10; i++)
Print out “%dx%2d=%2dn”, n, i, n*i
82
Basic Logics
4- Redirect a Program
• A characteristic is supported by the operating system and it is
used in the ACM International contest.
➔ So, pay attention to input/output formats.
83
Basic Logics
Diamond Pattern
• Print out the following diamond pattern
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Diamond Pattern
• Sub-problem:
• print out the upper half
• print out the lower half
• Print out upper half:
• row 1: print 4 spaces, 1 star; *
• row 2: print 3 spaces, 3 stars; * * *
• row 3: print 2 spaces, 5 stars; * * * * *
• row 4: print 1 space, 7 stars; * * * * * * *
• row 5: print 0 spaces, 9 stars; * * * * * * * * *
• Print out lower half:
• row 4: print 1 space, 7 stars; * * * * * * *
• row 3: print 2 spaces, 5 stars; * * * * *
• row 2: print 3 spaces, 3 stars; * * *
• row 1: print 4 spaces, 1 star; *
Diamond Pattern
• Algorithm for upper half:
• row 1: print (5-row)spaces, (2*row - 1) stars; *
• row 2: print (5-row)spaces, (2*row - 1) stars; * * *
• row 3: print (5-row)spaces, (2*row - 1) stars; * * * * *
• row 4: print (5-row)spaces, (2*row - 1) stars; * * * * * * *
• row 5: print (5-row)spaces, (2*row - 1) stars; * * * * * * * * *
• Algorithm for lower half:
• row 4: print (5-row)spaces, (2*row - 1) stars; * * * * * * *
• row 3: print (5-row)spaces, (2*row - 1) stars; * * * * *
• row 2: print (5-row)spaces, (2*row - 1) stars; * * *
• row 1: print (5-row)spaces, (2*row - 1) stars; *
Diamond Pattern
int row, space, star;
for(row=1; row<=5; row++){ //top half
for(space=1; space<=5-row; space++)
cout << " ";
for(star=1; star<=2*row-1; star++)
cout << "*";
cout << endl ;
}
for(row=4; row>=1; row--){ //bottom half
for(space=1; space<=5-row; space++)
cout << " ";
for(star=1; star<=2*row-1; star++)
cout << "*";
cout << endl ;
}
Summary
• Logic constructs = Statements can be used in a program.
• 3 Basic constructs: Sequence, selection constructs (if,
if…else, ?:, switch), Iteration constructs (for/ while/ do …
while)
• Walkthrough: Code are executed by yourself, Tasks in a
walkthrough: a record of the changes that occur in the
values of program variables and listing of the output, if any,
produced by the program.
88
Basic Logics

More Related Content

Similar to C Program Lesson 3 Basic Logic Constructs

Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxEyasu46
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing TechniquesAppili Vamsi Krishna
 
Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Ahmad Bashar Eter
 
final Unit 1-1.pdf
final Unit 1-1.pdffinal Unit 1-1.pdf
final Unit 1-1.pdfprakashvs7
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
Algorithms for c nit jamshedpur first year
Algorithms for c nit jamshedpur first yearAlgorithms for c nit jamshedpur first year
Algorithms for c nit jamshedpur first yearPallavSuman
 
Top 40 C Programming Interview Questions
Top 40 C Programming Interview QuestionsTop 40 C Programming Interview Questions
Top 40 C Programming Interview QuestionsSimplilearn
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaAdan Hubahib
 
Introduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonIntroduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonPriyankaC44
 
COM1407: Structured Program Development
COM1407: Structured Program Development COM1407: Structured Program Development
COM1407: Structured Program Development Hemantha Kulathilake
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartPrasanna R Kovath
 
Code Analysis-run time error prediction
Code Analysis-run time error predictionCode Analysis-run time error prediction
Code Analysis-run time error predictionNIKHIL NAWATHE
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codeshermiraguilar
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Object oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureObject oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureVaibhav Khanna
 

Similar to C Program Lesson 3 Basic Logic Constructs (20)

Fundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptxFundamentals of Programming Lecture #1.pptx
Fundamentals of Programming Lecture #1.pptx
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Lecture1
Lecture1Lecture1
Lecture1
 
Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1Acm aleppo cpc training introduction 1
Acm aleppo cpc training introduction 1
 
Lesson 5 .1 selection structure
Lesson 5 .1 selection structureLesson 5 .1 selection structure
Lesson 5 .1 selection structure
 
final Unit 1-1.pdf
final Unit 1-1.pdffinal Unit 1-1.pdf
final Unit 1-1.pdf
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
Algorithms for c nit jamshedpur first year
Algorithms for c nit jamshedpur first yearAlgorithms for c nit jamshedpur first year
Algorithms for c nit jamshedpur first year
 
Top 40 C Programming Interview Questions
Top 40 C Programming Interview QuestionsTop 40 C Programming Interview Questions
Top 40 C Programming Interview Questions
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
Introduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- PythonIntroduction to Problem Solving Techniques- Python
Introduction to Problem Solving Techniques- Python
 
COM1407: Structured Program Development
COM1407: Structured Program Development COM1407: Structured Program Development
COM1407: Structured Program Development
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chart
 
Pc module1
Pc module1Pc module1
Pc module1
 
Code Analysis-run time error prediction
Code Analysis-run time error predictionCode Analysis-run time error prediction
Code Analysis-run time error prediction
 
Algorithm and pseudo codes
Algorithm and pseudo codesAlgorithm and pseudo codes
Algorithm and pseudo codes
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Object oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structureObject oriented programming 11 preprocessor directives and program structure
Object oriented programming 11 preprocessor directives and program structure
 

More from ssusere19c741

0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdfssusere19c741
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdfssusere19c741
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdfssusere19c741
 
0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdfssusere19c741
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdfssusere19c741
 
0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdfssusere19c741
 
Intro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramIntro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramssusere19c741
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Servicessusere19c741
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communicationssusere19c741
 
Building Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor PagesBuilding Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor Pagesssusere19c741
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETssusere19c741
 
Asynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETAsynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETssusere19c741
 
Networking Programming
Networking ProgrammingNetworking Programming
Networking Programmingssusere19c741
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializingssusere19c741
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Applicationssusere19c741
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Applicationssusere19c741
 

More from ssusere19c741 (19)

0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf0-Slot18-19-20-ContiguousStorage.pdf
0-Slot18-19-20-ContiguousStorage.pdf
 
0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf0-Slot14-15-16-Libraries.pdf
0-Slot14-15-16-Libraries.pdf
 
0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf0-Slot13-Programming-With-Menu.pdf
0-Slot13-Programming-With-Menu.pdf
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf0-Slot08-09-10-Module-Functions.pdf
0-Slot08-09-10-Module-Functions.pdf
 
0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf0-Slot02-Introduction-to-PFC.pdf
0-Slot02-Introduction-to-PFC.pdf
 
Intro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgramIntro-InstallingTool-FirstProgram
Intro-InstallingTool-FirstProgram
 
Background Tasks with Worker Service
Background Tasks with Worker ServiceBackground Tasks with Worker Service
Background Tasks with Worker Service
 
Real-Time Communication
Real-Time CommunicationReal-Time Communication
Real-Time Communication
 
Building Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor PagesBuilding Websites Using ASP.NET Core Razor Pages
Building Websites Using ASP.NET Core Razor Pages
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 
Asynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NETAsynchronous and Parallel Programming in .NET
Asynchronous and Parallel Programming in .NET
 
Networking Programming
Networking ProgrammingNetworking Programming
Networking Programming
 
Working with XML and JSON Serializing
Working with XML and JSON SerializingWorking with XML and JSON Serializing
Working with XML and JSON Serializing
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Application
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 
Building Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) ApplicationBuilding Windows Presentation Foundation (WPF) Application
Building Windows Presentation Foundation (WPF) Application
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 

Recently uploaded

Storytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyStorytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyOrtega Alikwe
 
Application deck- Cyril Caudroy-2024.pdf
Application deck- Cyril Caudroy-2024.pdfApplication deck- Cyril Caudroy-2024.pdf
Application deck- Cyril Caudroy-2024.pdfCyril CAUDROY
 
The Next Things To Immediately Do About Mating Press
The Next Things To Immediately Do About Mating PressThe Next Things To Immediately Do About Mating Press
The Next Things To Immediately Do About Mating Pressmatingpress170
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证diploma001
 
Protection of Children in context of IHL and Counter Terrorism
Protection of Children in context of IHL and  Counter TerrorismProtection of Children in context of IHL and  Counter Terrorism
Protection of Children in context of IHL and Counter TerrorismNilendra Kumar
 
Back on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveBack on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveMarharyta Nedzelska
 
AICTE PPT slide of Engineering college kr pete
AICTE PPT slide of Engineering college kr peteAICTE PPT slide of Engineering college kr pete
AICTE PPT slide of Engineering college kr peteshivubhavv
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作ss846v0c
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一A SSS
 
Jumark Morit Diezmo- Career portfolio- BPED 3A
Jumark Morit Diezmo- Career portfolio- BPED 3AJumark Morit Diezmo- Career portfolio- BPED 3A
Jumark Morit Diezmo- Career portfolio- BPED 3Ajumarkdiezmo1
 
LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024Bruce Bennett
 
Introduction to Political Parties (1).ppt
Introduction to Political Parties (1).pptIntroduction to Political Parties (1).ppt
Introduction to Political Parties (1).pptSohamChavan9
 
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证nhjeo1gg
 
Spanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceSpanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceFluent Fast Academy
 
Crack JAG. Guidance program for entry to JAG Dept. & SSB interview
Crack JAG. Guidance program for entry to JAG Dept. & SSB interviewCrack JAG. Guidance program for entry to JAG Dept. & SSB interview
Crack JAG. Guidance program for entry to JAG Dept. & SSB interviewNilendra Kumar
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书saphesg8
 
定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一z zzz
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...nitagrag2
 
Nathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathanBaughman3
 

Recently uploaded (20)

Storytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary PhotographyStorytelling, Ethics and Workflow in Documentary Photography
Storytelling, Ethics and Workflow in Documentary Photography
 
Application deck- Cyril Caudroy-2024.pdf
Application deck- Cyril Caudroy-2024.pdfApplication deck- Cyril Caudroy-2024.pdf
Application deck- Cyril Caudroy-2024.pdf
 
The Next Things To Immediately Do About Mating Press
The Next Things To Immediately Do About Mating PressThe Next Things To Immediately Do About Mating Press
The Next Things To Immediately Do About Mating Press
 
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
原版定制卡尔加里大学毕业证(UC毕业证)留信学历认证
 
Protection of Children in context of IHL and Counter Terrorism
Protection of Children in context of IHL and  Counter TerrorismProtection of Children in context of IHL and  Counter Terrorism
Protection of Children in context of IHL and Counter Terrorism
 
Back on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental LeaveBack on Track: Navigating the Return to Work after Parental Leave
Back on Track: Navigating the Return to Work after Parental Leave
 
AICTE PPT slide of Engineering college kr pete
AICTE PPT slide of Engineering college kr peteAICTE PPT slide of Engineering college kr pete
AICTE PPT slide of Engineering college kr pete
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作
 
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
办理学位证(Massey证书)新西兰梅西大学毕业证成绩单原版一比一
 
Jumark Morit Diezmo- Career portfolio- BPED 3A
Jumark Morit Diezmo- Career portfolio- BPED 3AJumark Morit Diezmo- Career portfolio- BPED 3A
Jumark Morit Diezmo- Career portfolio- BPED 3A
 
LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024LinkedIn for Your Job Search in April 2024
LinkedIn for Your Job Search in April 2024
 
Students with Oppositional Defiant Disorder
Students with Oppositional Defiant DisorderStudents with Oppositional Defiant Disorder
Students with Oppositional Defiant Disorder
 
Introduction to Political Parties (1).ppt
Introduction to Political Parties (1).pptIntroduction to Political Parties (1).ppt
Introduction to Political Parties (1).ppt
 
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
原版快速办理MQU毕业证麦考瑞大学毕业证成绩单留信学历认证
 
Spanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceSpanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable Price
 
Crack JAG. Guidance program for entry to JAG Dept. & SSB interview
Crack JAG. Guidance program for entry to JAG Dept. & SSB interviewCrack JAG. Guidance program for entry to JAG Dept. & SSB interview
Crack JAG. Guidance program for entry to JAG Dept. & SSB interview
 
办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书办理哈珀亚当斯大学学院毕业证书文凭学位证书
办理哈珀亚当斯大学学院毕业证书文凭学位证书
 
定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一定制英国克兰菲尔德大学毕业证成绩单原版一比一
定制英国克兰菲尔德大学毕业证成绩单原版一比一
 
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
Escorts Service Near Surya International Hotel, New Delhi |9873777170| Find H...
 
Nathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editor
 

C Program Lesson 3 Basic Logic Constructs

  • 1. Slots 05-06-07: Lesson 3 Basic Logics: Module-C-Logic Logic Constructs /Programming Style /Walkthroughs
  • 2. Objectives • How to develop a C- program? → Logic constructs • When I develop a C-program, what are things that I should follow? → Programming styles • How I can understand a program? → Walkthroughs
  • 3. Contents 1- Logic constructs 2- Programming Styles 3-Walkthroughs 4-Bonus – Redirect a Program ( a technique is used in the ACM Contest) 3
  • 4. Review • A variable is a name referencing to a memory location. • A data type defines: How the values are stored and how the operations on those values are performed. • 4 primitive data types in C: int, char, float, double • Data stored are in binary format • Declare a variable in C: type var [=initialValue]; • An identifier begin with a letter or ‘_’, the later symbols can be letters, digits and ‘_’ • An user-defined identifier must not a C keyword. • Expression is a valid association of constants, variables, operators and functions. 4 Basic Logics
  • 5. Creativity in Algorithms • Creativity has to do with both the process you invent (an algorithm) to solve a new problem in a given context and how you implement that • Selection: • most commonly seen in if-statements • The JUMP...IF command in the Human Machine Language is a form of selection. It gives us a way to compare two things (numbers) and take action if one thing was true. • Iteration: • also known as "looping“ • The JUMP command in the Human Machine Language allows us to move to a different point in the program and start executing from there. This allows us to re-use lines of code, and this is a form of iteration or looping. • Sequencing: • Sequencing is the application of each step of an algorithm in the order in which the statements are given.“ • The sequencing is simply implied by the fact that we number the instructions with the intent to execute them in order. 5 Basic Logics
  • 6. Logic Constructs • Logic constructs: Expressions enable us to write programs that perform creative algorithm (calculations and execute statements) in a sequential order. • Structured Programming • Logic constructs: • Sequence constructs • Selection constructs • Iteration constructs 6 Basic Logics
  • 7. Structured Programming • Structure of a program code should be organized in a manner so that it is understandable, testable and readily modifiable. ➔It consists of simple logical constructs, each of which has one entry point and one exit point. • The beginning step for developing a program is DESIGN using • pseudo-coding or • flow charting 7 Basic Logics
  • 8. Structured Programming: Pseudo-code • Example: Calculating the absolute value of an integer inputted from the keyboard. 1. Prompt the user for an integer value 2. Accept an integer value from the user and store it in x 3. If x is negative number then x = -x 4. Display x 8 Basic Logics
  • 9. Structured Programming: Flowcharting • A flowchart is a diagram that depicts the “flow of control” of a program. • Three types of symbols in this flowchart • rounded rectangles • parallelograms • a rectangle • Terminals • represented by rounded rectangles • indicate a starting or ending point 9 Basic Logics
  • 10. Structured Programming: Flow chart symbols • Flow chart symbols Selection (Decision diamond) • A 2-way branch. An if or another decision. The condition appears inside the diamond. Example: x<y? Two arrows lead out of the decision. These arrows may be labeled with Yes and No, meaning the then and else branch, respectively. • Flow chart symbols Iteration • Start of a repeated block. A for statement or similar. The end of the loop body connects back to the loop symbol. How many times the loop executes depends on what is written inside the loop symbol. 10 Basic Logics
  • 11. Sequence Constructs • Tells the processor which statement is to be executed next. • the statement follows first statement in the program. • use a goto statement to jump • computer programming (1950's to early 1960's) • A sequence is either a simple statement or a code block. • Simple Statements expression ; • Code Blocks: A code block is a set of statements enclosed in curly braces. {statements; } 11 Basic Logics
  • 12. Creative thinking • Write a C program to check whether a given number is even or odd. • Write a C program to check whether a student can pass or fail based on his/her mark • Selection Constructs
  • 13. Selection Constructs 13 Basic Logics • Gives a program the ability to choose which instruction(s) to next execute based on conditions • Types: • single-selection statement (if statement) • double-selection statement (if-else statement) • multiple-selection statement (nested if-else) • multiple-selection statement (switch/case) • If the condition is a value of char/integer
  • 14. Selection Constructs : if statement 14 Basic Logics • single-selection statement (if statement) • Syntax if (condition) { statements; } condition evaluated statement true false • The if selection statement either performs statements if a condition is true or skips the statements if the condition is false.
  • 15. Selection Constructs: if Examples 15 Basic Logics
  • 16. Selection Constructs : if-else statement 16 Basic Logics • double-selection statement (if-else statement) • Syntax if (condition) { statements 1; } else { statements 2; } • The if…else selection statement performs statements 1 if a condition is true and performs a statements 2 if the condition is false. condition statement1 true false statement2
  • 17. Selection Constructs: if-else Examples 17 Basic Logics
  • 18. Selection Constructs: if … else errors The compiler can not determine the if statement before the else statement. 18 Basic Logics
  • 19. Selection Constructs : nested if-else statement 19 Basic Logics • multiple-selection statement • Syntax if (condition 1) { statements; } else if (condition2) { statements; } else { statements; } Nested if • Buying N T-shirts with promotion: • N<=3: 120000$/item • From 4th to 6th: 90000$/item • From 7th to 10th: 85000$/item • From 11th : 70000$/item • Describe the expression that will compute the paid value. Let N: number of T-shirts bought, t: money must be paid. if (N <=3) t = N*120000 ; else if (N<=6) t= 3*120000 + (N-3) * 90000; else if (N<=10) t= 3*120000 + 3*90000 + (N-6)*85000; else t= 3*120000 + 3*90000 + 4*85000 + (N-10)*70000;
  • 20. Selection Constructs: Dangling Else • Ambiguity may arise in the case of nested if else constructs. • The rule in C is that an else always belongs to the innermost if available. Use { } to explicitly determine statements 20 Basic Logics
  • 21. Exercises • Write a C program to check whether a given number is even or odd. • Write a C program to accept the height of a person in centimeter and categorize the person according to their height. • Write a C program to check whether a character is an alphabet, digit or special character.
  • 24. Selection Constructs: Operator ? : 24 Basic Logics (condition) ? True_Value : False_Value
  • 25. Selection Construct: The switch statement switch (variable or expression) { case constant : statement(s); break; case constant : statement (s); break; default: statement (s); } char / int 25 Basic Logics • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • The match must be an exact match • A break statement causes control to transfer to the end of the switch statement • If the break statement is missed, the next statements are executed until a break is detected or all statements in the body of the switch are executed. • Each case is an entry of a selection • If the break statement is missed, the next statements are executed until a break is detected or all statements in the body of the switch are executed. • Each case is an entry of a selection
  • 26. Selection Construct: The switch statement 26 Basic Logics If input is 8, what are outputs? a) 200000 , 2 b) 300000, 3 c) 0, 0 d) 1000000, 4 e) 1500000, 10 f) None of the others If input is 7, what are outputs
  • 27. Selection Construct: The switch statement • Write a program that allows user inputting a simple expression containing one of four operators +, -, *, / then the result is printed out to the monitor. • Input format: num1 operator num2, Example: 4*5 27 Basic Logics
  • 28. Exercises • Write a program in C which is a Menu- Driven Program to compute the area of the various geometrical shape. • Write a program in C which is a Menu- Driven Program to perform a simple calculation.
  • 32. Chapter 2: Program Correctness and Efficiency 32 Syntax Errors • Syntax errors: grammatical mistakes in a program • The compiler detects syntax errors • Executable code will not be created until you correct all of the syntax errors • Most frequent syntax errors are: • Missing Parenthesis (}) • Printing the value of variable without declaring it • Missing semicolon
  • 33. Creative thinking • Want to do some repetitive sequence of actions: • print vertical line of *s * * * * * • Corresponding program: printf(“*n”); printf(“*n”); printf(“*n”); printf(“*n”); printf(“*n”);
  • 34. Creative thinking • Write a program in C to display the first 10 natural numbers. • Corresponding program: printf(“1 n”); printf(“2 n”); printf(“3 n”); printf(“4 n”); printf(“5 n”); printf(“6 n”); printf(“7 n”); printf(“8 n”); printf(“9 n”); printf(“10 n”);
  • 35. Creative thinking How could you write a program that display 4000 number?
  • 36. Iteration (loop) Constructs • A loop is a programming construct that executes lines of code repeatedly while condition is met. • Three loop constructs make it possible to iterate over code or execute it more than once: • for loops. • while loops. • do … while loops. • Structure of a loop: • First: Initial block. • Second: Condition. • Third: Task in each execution. • Types of iteration: fixed loops, variable loops 36 Basic Logics
  • 37. Iteration (loop) Constructs • Structure of a loop: • First: Initial block: i=0 • Second: Condition: i<=10 • Third: Task in each execution: printf(“%d”,i); i=i+1; • Types of iteration: fixed loops, known the number of repetition line of code. 37 Basic Logics
  • 38. Creative thinking How could you write a program that would read in five values and display the average?
  • 39. Creative thinking • How hard would it be to change the program to average four thousand values? • How hard would it be to change the program so it could read in the number of values to be read and then compute the average?
  • 40. Iteration… 40 Basic Logics • Structure of a loop: • First: Initial block: i=0,S=0 • Second: Condition: i<=n • Third: Task in each execution: S=S+i;i=i+1; • Types of iteration: fixed loops, known the number of repetition line of code.
  • 41. Iteration… • What we need to know for a loop - How many time that these lines of code need to be executed? • Identify a loop for an expression: • Left side → Initial block • Right side → Condition to run these lines of code • An operation and preparations for the next iteration: Tasks (lines of code) in each iteration. 41 Basic Logics Left side Right side An operation
  • 43. Iteration: for statement InitBlock Condition? Task1 Task2 yes no 43 Basic Logics • A for loop is used when a loop is to be executed a known number of times • for (InitBlock; Condition; Task2) Task1; • for ( Init1, Init2; Condition ; Task1, Task2); • InitBlock; for ( ; Condition ; Task2) Task1; • InitBlock; for ( ; Condition ;) { Task1; Task2; } • The InitBlock set the initial value of the loop control variable. • The Condition test the value of the loop control variable. • The Task2 update the loop control variable • The Task1 might be the repeated Tasks in some cases The condition will be tested before tasks are performed.
  • 44. Iteration for() Example • Write a program in C to display the first 10 natural numbers. 44 Basic Logics
  • 45. Iteration for() Example • Write a program that will print out the ASCII table. ASCII code : 0 → 255 Initialize: int code =0 Condition: code <256 Task: Print the code using 4 format: %c, %d, %o, %X code = code +1 45 Basic Logics
  • 46. Iteration for() Example Code 46 Basic Logics
  • 47. Iteration for() Example • Write a program in C to display the first 10 natural numbers. 47 Basic Logics
  • 48. Iteration for() Example • Write a program that will calculate 1+2+3+…+n. Accepted variable: int n Sum 1 .. N → int sum Algorithm Accept n Loop: Initialize i=1, sum=0 Condition i<=n Tasks: sum += i; i++; Print out sum 48 Basic Logics
  • 49. Exercises • Write a program in C to display the n terms of odd natural number and their sum like: 1 3 5 7 ... N • Write a program in C to display the n terms of harmonic series and their sum. The series is : 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms Basic Logics 49
  • 51. Exercises • Write a program in C to Check Whether a Number can be perfect Numbers. Basic Logics 51
  • 52. Exercises(nested loop) • nested loop: A loop placed inside another loop. • Write a program in C to make such a pattern like right angle triangle with “*”. Basic Logics 52
  • 53. Iteration: while() statements The condition will be tested after tasks are performed. /* Initializations */ while (condition) { statements; } 53 Basic Logics • If the condition is true, the statement is executed • Then the condition is evaluated again, and if it is still true, the statement is executed again • The statement is executed repeatedly until the condition becomes false We can test multiple conditions using logical operator inside while loop InitBlock Condition? Task1 Task2 yes no
  • 56. Iteration: do…while() statements The condition will be tested after tasks are performed. /* Initializations */ do { statements; } while (condition) ; InitBlock Condition? Task1 Task2 yes no 56 Basic Logics • The statement is executed repeatedly while the condition becomes false
  • 57. Computer Science: A Structured Programming Approach Using C 57 while() vs do…while() statements • First, the while statement evaluates expression, which must return a boolean value. If the expression returns true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression returns false. • Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at the bottom. Thus, the statements within the block associated with a do-while are executed at least once.
  • 58. Iteration do while() • Write a program that will print out the sum of integers inputted by user. The input will terminate if user enters the value 0. Nouns: inputted integer → int x, sum of integers → int sum Tasks (algorithm) Begin sum =0 do { accept x; sum += x; } while (x!=0); Print out sum End Implement it by yourself. 58 Basic Logics The following program print numbers between 1 and 100 which are multiple of 3 using the do while loop:
  • 59. Iteration • Write a program that permits user entering some characters until the ENTER key (code 10) is pressed. The program will print out the number of digits, number of letters, number of other keys were pressed. Accept a character: c=getchar(); Nouns: character inputted → char c, Number of digits → int noDigits Number of letters → noLetters, Number of other keys → noOthers #define ENTER 10 Algorithm Begin noDigits = noLetters = noOthers = c= 0 printf(“Enter a string:”); While (c!=ENTER) { accept c; if ( c>=‘0’ && c <=‘9’) noDigits++; else if ( (c>=‘a’ && c <=‘z’) || (c>=‘A’ && c <=‘Z’) ) noLetters++; else noOthers++; } Print out noDigits, noLetters, noOthers End Implement it by yourself. The while statement is intentionally used. So, c=0 is assigned and the condition c!=ENTER is evaluated to TRUE 59 Basic Logics Input form: abc1234fGH+-*/?(ENTER)
  • 60. Iteration Summary • When a loop is needed, what loop statement should be used? ➔ All of them can be used to satisfy your requirement. 60 Basic Logics
  • 61. Iteration: Break/ Bypass a loop 61 Basic Logics
  • 62. Iteration Constructs: Flags • The one entry, one exit principle is fundamental to structured programming. • C includes three keywords that allow jumps across statements: goto, continue, and break. Using any of these keywords, except for break in a switch construct, violates the one entry, one exit principle of structured programming. 62 Basic Logics
  • 63. Iteration Constructs: Flags… • To improve readability, programmers advocated: • the use of whitespace to identify the logical structure of the code • the abolition of all goto statements • the abolition of all continue statements • the abolition of all break statements, except with switch • A technique for avoiding jumps is called flagging. A flag is a variable that keeps track of a true or false state. 63 Basic Logics
  • 64. Iteration Constructs: Flags… Use if instead of continue 64 Basic Logics
  • 65. Iteration Constructs: Flags… Loop infinitively 65 Basic Logics
  • 66. Iteration Constructs: Flags… No flag is used. A flag is used. 66 Basic Logics
  • 67. Programming Styles • Habits in programming • A well-written program is a pleasure to read. Other programmers can understand it without significant effort. The coding style is consistent and clear throughout. • Develop your own style guide or adopt the style outlined here or elsewhere, but adopt some style. Recommendations on • Naming • Indentation • Comments • Magic Values • General Guidelines 67 Basic Logics
  • 68. Programming Styles: Naming •Adopt names that are self-descriptive so that comments clarifying their meaning are unnecessary •Use names that describe identifiers completely, avoiding cryptic names •Prefer nouns for variable names •Keep variable names short - studentName rather than theNameOfAStudent •Keep the names of indices very short - treat them as mathematical notation 68 Basic Logics
  • 69. Programming Styles: Indentation •Indent the body of any construct that is embedded within another construct. For example, •Use in-line opening braces or start opening braces on a newline but don't mix the two styles. 69 Basic Logics
  • 70. Programming Styles: Comment •Use comments to declare what is done, rather than describe how it is done. •Comments introduce what follows. •Keep them brief and avoid decoration. 70 Basic Logics
  • 71. Programming Styles: Magic Values •These may be mathematical constants, tax rates, default values or names. •To improve readability, assign symbolic names to these magic values and refer to the symbolic names throughout the code. •Use the directive #define SYMBOLIC_NAME value 71 Basic Logics
  • 72. Programming Styles: Magic Values… • Compiler Idiosyncracies • Use #define to manage idiosyncracies (đặc điểm) across platforms. • For example, the Borland 5.5 compiler does not recognize the long long data type. Instead, it recognizes an _int64 data type. To improve portability, #define the data type using a symbolic name such as LONG_LONG and embed that name throughout our code. 72 Basic Logics
  • 73. Programming Styles: Guidelines • Limit line length to 80 characters - both comments and code • Avoid global variables • Select data types for variables wisely and carefully • Initialize a variable when declaring it only if the initial value is part of the semantic of the variable. • If the initial value is part of an algorithm, use a separate assignment statement. • Avoid goto, continue, break except in switch. • Avoid using the character encodings for a particular machine. • Use a single space or no spaces either side of an operator. 73 Basic Logics
  • 74. Programming Styles: Guidelines •Use in-line opening braces or start opening braces on a newline but don't mix the two styles. •Initialize iteration variables in the context of the iteration •Avoid assignments nested inside logical expressions •Avoid iterations with empty bodies - reserve the body for the algorithm •Limit the initialization and iteration clauses of a for statement to the iteration variables •Distribute and nest complexity 74 Basic Logics
  • 75. Programming Styles: Guidelines •Avoid fancy algorithms that may be efficient but are difficult to read •Add additional comments where code has been fine tuned for efficient execution •Add an extra pair of parentheses where an assignment is also used as a condition •Remove unreferenced variables •Remove all commented code and debugging statements from release and production code 75 Basic Logics
  • 76. 3- Walkthroughs • Understand code is a skill of programmer. • To understand code, we should know how the code execute. • To know how the code execute, we should perform each instruction. • A walkthrough is • a record of the changes that occur in the values of program variables as a program executes and • a listing of the output, if any, produced by the program. Ways to perform a walkthrough • Memory Map → You knew that • Walkthrough Tables → A simpler way 76 Basic Logics
  • 78. Walkthroughs: Demo. int n, i, S=0; scanf(“%d”, &n); for (i=1; i<=n; i+=3) if (i%2!=0 && i%3!=0) S+=i; printf(“%d”, S); What is the output if the input is 15? n 15 i 1 4 7 10 13 16 S 0+1 → 1 1+7 → 8 8+13→21 S=21 78 Basic Logics
  • 79. Walkthroughs: Demo. int m,n, i, S=0; scanf(“%d%d”, &n, &m); for (i=m; i<=n; i++) S+=i; printf(“%d”, S); What is the output if the input are 8 12? Test the program: int m,n, i, S=0; scanf(“%da%d”, &n, &m); for (i=m; i<=n; i++) S+=i; printf(“%d”, S); What is the output if the input are 8a12? Modify Input “%d %d” 12 8 “%d%d” 12 8 “%d%d” 12 8 “%d-%d” 12-8 79 Basic Logics
  • 80. Walkthroughs: Demo. Study the following code: int n=15; int S=0; i=1; while (i<2*n) { S+= i; i*=4; } Give your opinion. a) S=21 b) S= 85 c) A syntax error 80 Basic Logics
  • 81. i= 1 2 3 4 5 6 Extra Demo: Print star characters Print out 1*, “n” Print out 2*, “n” Print out 3*, “n” Print out 4*, “n” Print out 5*, “n” Print out 6*, “n” i Accept N; for ( i=1; i<=N; i++) { for (j=1; j<=i; j++) printf(“*”); printf (“n”); } N=6 * ** *** **** ***** ****** 81 Basic Logics
  • 82. Extra Demo: Multiplication Table N=5 5x 1= 5 5x 2=10 5x 3=15 5x 4=20 5x 5=25 5x 6=30 5x 7=37 5x 8=40 5x 9=45 5x10=50 Accept n; for ( i=1; i<=10; i++) Print out “%dx%2d=%2dn”, n, i, n*i 82 Basic Logics
  • 83. 4- Redirect a Program • A characteristic is supported by the operating system and it is used in the ACM International contest. ➔ So, pay attention to input/output formats. 83 Basic Logics
  • 84. Diamond Pattern • Print out the following diamond pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  • 85. Diamond Pattern • Sub-problem: • print out the upper half • print out the lower half • Print out upper half: • row 1: print 4 spaces, 1 star; * • row 2: print 3 spaces, 3 stars; * * * • row 3: print 2 spaces, 5 stars; * * * * * • row 4: print 1 space, 7 stars; * * * * * * * • row 5: print 0 spaces, 9 stars; * * * * * * * * * • Print out lower half: • row 4: print 1 space, 7 stars; * * * * * * * • row 3: print 2 spaces, 5 stars; * * * * * • row 2: print 3 spaces, 3 stars; * * * • row 1: print 4 spaces, 1 star; *
  • 86. Diamond Pattern • Algorithm for upper half: • row 1: print (5-row)spaces, (2*row - 1) stars; * • row 2: print (5-row)spaces, (2*row - 1) stars; * * * • row 3: print (5-row)spaces, (2*row - 1) stars; * * * * * • row 4: print (5-row)spaces, (2*row - 1) stars; * * * * * * * • row 5: print (5-row)spaces, (2*row - 1) stars; * * * * * * * * * • Algorithm for lower half: • row 4: print (5-row)spaces, (2*row - 1) stars; * * * * * * * • row 3: print (5-row)spaces, (2*row - 1) stars; * * * * * • row 2: print (5-row)spaces, (2*row - 1) stars; * * * • row 1: print (5-row)spaces, (2*row - 1) stars; *
  • 87. Diamond Pattern int row, space, star; for(row=1; row<=5; row++){ //top half for(space=1; space<=5-row; space++) cout << " "; for(star=1; star<=2*row-1; star++) cout << "*"; cout << endl ; } for(row=4; row>=1; row--){ //bottom half for(space=1; space<=5-row; space++) cout << " "; for(star=1; star<=2*row-1; star++) cout << "*"; cout << endl ; }
  • 88. Summary • Logic constructs = Statements can be used in a program. • 3 Basic constructs: Sequence, selection constructs (if, if…else, ?:, switch), Iteration constructs (for/ while/ do … while) • Walkthrough: Code are executed by yourself, Tasks in a walkthrough: a record of the changes that occur in the values of program variables and listing of the output, if any, produced by the program. 88 Basic Logics