0% found this document useful (0 votes)
245 views59 pages

Slot05-06-07-Basic Logics

The document discusses programming fundamentals using C, including basic logic constructs such as sequence, selection, and iteration constructs; programming styles; and walkthroughs to understand programs. It covers variables, data types, expressions, structured programming with pseudo-code and flowcharts, and selection constructs including if/else statements, the ternary operator, and switch statements. The content provides an overview of key concepts for developing C programs using proper logic and style.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
245 views59 pages

Slot05-06-07-Basic Logics

The document discusses programming fundamentals using C, including basic logic constructs such as sequence, selection, and iteration constructs; programming styles; and walkthroughs to understand programs. It covers variables, data types, expressions, structured programming with pseudo-code and flowcharts, and selection constructs including if/else statements, the ternary operator, and switch statements. The content provides an overview of key concepts for developing C programs using proper logic and style.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Programming Fundamentals using C

Slots 05-06-07
Basic Logics
Module-C-Logic
Logic Constructs
Programming Style
Walkthroughs
Programming Fundamentals using C

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 (%d), char (%c), float (%f), double (%d)
▪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.

Basic Logics 2
Programming Fundamentals using C

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

Basic Logics 3
Programming Fundamentals using C

Content

1- Logic constructs
2- Programming Styles
3- Walkthroughs
4- Bonus – Redirect a Program ( a technique is used in the ACM
Contest)

Basic Logics 4
Programming Fundamentals using C

1- Logic Constructs

Logic constructs: Expressions enable us to write programs that


perform calculations and execute statements in a sequential order.

▪Structured Programming
▪Logic constructs:
▪ Sequence constructs
▪ Selection constructs (1/2, 1/n)
▪ Iteration constructs (loop)

Basic Logics 5
Programming Fundamentals using C

1.1- Structured Programming


• Structure of a program code should be organize 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

Basic Logics 6
Programming Fundamentals using C

Structured Programming: Pseudo-code


• Example: Calculating the absolute value of an integer inputted from
the keyboard.

❖ Prompt the user for an integer value


❖ Accept an integer value from the user and store it in x
❖ If x is negative then x = -x
❖ Display x
• Need to know: integer, input from keyboard, check (selection), print,
absolute number ?

Basic Logics 7
Programming Fundamentals using C

Structured Programming: Flowcharting


• Describe the flow of a program unit symbolically

Basic Logics 8
Programming Fundamentals using C

1.2- Sequence Constructs


• 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
{
statement
...
statement
}
• Note: focus on the level of statement.

Basic Logics 9
Programming Fundamentals using C

1.3- Selection Constructs


Select 1/2 Select 1/n
if switch
if … else
If … else if …. else
? : (operator)

Integral
expression
Condition
?
c1 c2 c3 default
TRUE FALSE
Op1 Op2 Op3 Op4
Operation 1 Operation 2

Basic Logics 10
Programming Fundamentals using C

Selection Constructs: if
if (condition)
{
statements
}

Ex: Calculating the absolute value of an integer inputted from


the keyboard.

Basic Logics 11
Programming Fundamentals using C

Selection Constructs: if … else

if (condition)
{ statements
}
else
{ statements
}

Basic Logics 12
Programming Fundamentals using C

Selection Constructs: if … else


if (condition)
{ statements The compiler can not
} determine the if statement
else before the else statement.
{ statements
}

Basic Logics 13
Programming Fundamentals using C

Selection Constructs: if … else


Begin
N,t → int
⚫ Buying N T-shirts with promotion: Accept N
Nested if
⚫ N<=3: 120000 VND/item Compute t
⚫ From 4th to 6th: 90000 VND/item Print out t
if (condition 1) ⚫ From 7th to 10th: 85000 VND/item End
{ ⚫ From 11th : 70000 VND/item
statements ⚫ Describe the expression that will compute the
} paid value.
else if (condition2)
{ Let N: number of T-shirts bought, t: money must be paid.
statements if (N <=3) t = N*120000 ;
} else if (N<=6) t= 3*120000 + (N-3) * 90000;
else else if (N<=10)
{ t= 3*120000 + 3*90000 + (N-6)*85000;
statements else
} t= 3*120000 + 3*90000 + 4*85000 + (N-10)*70000;

Basic Logics 14
Programming Fundamentals using C

Selection Constructs: if … else


⚫ Similarly, describe the
if (condition 1) expression that will Begin
{ statements compute the paid value N,t → int
} when we use electric Accept N
else if (condition2) power. Compute t
{ statements ⚫ Implement it to a program. Print out t
} End
else
{ statements
}

100 150 200 Number of kwhs

950 1250 1350 1550 prices

Basic Logics 15
Programming Fundamentals using C

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

Basic Logics 16
Programming Fundamentals using C

Selection Constructs: Operator ? :

(condition) ? True_Value : False_Value

Basic Logics 17
Programming Fundamentals using C

Selection Constructs: Operator ? :

Basic Logics 18
Programming Fundamentals using C

Selection Constructs:
The switch statement

switch (variable or expression)


{ Integral
char / int expression
case constant :
statement(s); c1 c2 c3 default
break;
case constant : Op1 Op2 Op3 Op4
statement (s);
break;
default:
If the break statement is missed, the next statements
statement (s); 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
Basic Logics 19
Programming Fundamentals using C

Selection Constructs:
The switch statement

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?

Basic Logics 20
Programming Fundamentals using C
Analysis
Nouns: expression num1 op num2
Selection Constructs: ➔ double num1, num2; char op
result → double result
switch… Verbs: Begin
Accept num1, op, num2 → “%lf%c%lf”
switch (op)
Write a program that allows { case ‘+’ : result = num1 + num2;
user inputting a simple print out result;
expression containing one of break;
case ‘-’ : result = num1 - num2;
four operators +, -, *, / then print out result;
the result is printed out to break;
the monitor. Input format: case ‘*’ : result = num1 * num2;
print out result;
num1 operator num2, break;
Example: 4*5 case ‘/’ : if ( num2==0)
print out “Divide by 0 “
else
{ result = num1 / num2;
print out result;
}
break;
default: print out “Op is not supported”
Implement it. }
Basic Logics 21
End
Programming Fundamentals using C

1.4- Iteration (loop) Constructs


• Loop/Iteration: some statements are executed repetitively
• Structure of a loop:
• Initial block.
• Condition.
• Task in each execution.
• Types of iteration: fixed loops, variable loops
• The iteration constructs are:
while
do while
for

Basic Logics 22
Programming Fundamentals using C

Iteration…

Identify a loop:
• Calculate S= 1+2+3+4+5+6+7+ … + 100
➔Some addition are performed ➔ Loop
• Sum of some numbers they are inputted until user
enters 0.
➔Accept and add numbers ➔ Loop

Basic Logics 23
Programming Fundamentals using C

Iteration…
Identify a loop for an expression:
Left side → Initial block
Right side → Condition
An operation and preparations for the next iteration: Tasks in each
iteration.

S=1+2+3+4+… + 100 S=1*2*3*4*… * 100


→ S=0+1+2+3+4+… + 100 →S=1*1*2*3*4*… * 100
S=0 (1) S=S+i; i<=100 S=1 (1) S=S*i; i<=100
i=1 (2) i=i+1; i=1 (2) i=i+1;

S=1
i=2

Basic Logics 24
Programming Fundamentals using C

Iteration…
S= 0 , n<=0 S= 0 , n<=0
1 + 3 + 5 +… + n, n is odd n + (n-2) + (n-4) + … + 0
2 + 4 + 6 + … + n, n is even
Initial value:
Initial value: S = 0;
S=0 i = n;
i = (n%2==1)? 1: 2; Condition i>0
Condition i <=n Tasks: S += i;
Tasks: S += i; i -=2;
i+=2;

S= 1 + 1/10 + 1/ 21 + 1/32 + … + 1 /nn-1


Initial value: #include <math.h>
S = 1.0;
i = 1;
Condition i <=n
Tasks: S += 1.0/ pow ( i, i-1 );
i = i +1;
Basic Logics 25
Programming Fundamentals using C

Iteration: for statement


• for ( InitBlock; Condition; Task2) Task1;
• for ( Init1, Init2; Condition ; Task1, Task2);
• InitBlock;
for ( ; Condition ; Task2) Task1;
InitBlock
• InitBlock;
no
for ( ; Condition ;) Condition?
{ Task1; yes
Task2; Task1
}
Task2
The condition will be tested before tasks are
performed.

Basic Logics 26
Programming Fundamentals using C

Iteration…
• 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

Basic Logics 27
Programming Fundamentals using C

Iteration…
• 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

Basic Logics 28
Programming Fundamentals using C

Iteration: while/do…while statements


InitBlock
InitBlock

no
Condition? Task1

yes
Task2
Task1

Task2
yes no
Condition?

/* Initializations */ /* Initializations */
do
while (condition)
{ statements;
{ statements; }
} while (condition) ;
The condition will be tested before
tasks are performed. The condition will be tested after
tasks are performed.
Basic Logics 29
Programming Fundamentals using C

Iteration: while/do…while statements


• Write a program that will print out the ASCII table.

ASCII code : 0 → 255


Initialize: code =0
Condition: code <256
Task:
Print the code using 4 formats: %c, %d, %o, %X
code = code +1

Basic Logics 30
Programming Fundamentals using C

Iteration…
• 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 Implement it by
{ accept x; yourself.
sum += x;
}
while (x!=0);
Print out sum
End

Basic Logics 31
Programming Fundamentals using C

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 The while statement is
noDigits = noLetters = noOthers = c= 0 intentionally used. So, Implement
printf(“Enter a string:”); c=0 is assigned and the it by
While (c!=ENTER) condition c!=ENTER is yourself.
{ accept c; evaluated to TRUE
if ( c>=‘0’ && c <=‘9’) noDigits++;
else if ( (c>=‘a’ && c <=‘z’) || (c>=‘A’ && c <=‘Z’) ) noLetters++;
else noOthers++;
} Input form:
Print out noDigits, noLetters, noOthers abc1234fGH+-*/?(ENTER)
End Basic Logics 32
Programming Fundamentals using C

Iteration…

• When a loop is needed, what loop statement should be used?


➔ All of them can be used to satisfy your requirement.

Basic Logics 33
Programming Fundamentals using C

Iteration: Break/ Bypass a loop

0 1 2 3 4 5

0 1 2 3 4 5

Basic Logics 34
Programming Fundamentals using C

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.

Basic Logics 35
Programming Fundamentals using C

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.

Basic Logics 36
Programming Fundamentals using C

Iteration Constructs: Flags…


Use if instead of continue

Basic Logics 37
Programming Fundamentals using C

Iteration Constructs: Flags…

Basic Logics 38
Programming Fundamentals using C

Iteration Constructs: Flags…


Loop infinitively

Basic Logics 39
Programming Fundamentals using C

Iteration Constructs: Flags…

No flag is
used.

A flag is used.

Basic Logics 40
Programming Fundamentals using C

2- 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

Basic Logics 41
Programming Fundamentals using C

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

Basic Logics 42
Programming Fundamentals using C

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.

Basic Logics 43
Programming Fundamentals using C

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.

Basic Logics 44
Programming Fundamentals using C

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

Basic Logics 45
Programming Fundamentals using C

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.

Basic Logics 46
Programming Fundamentals using C

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.
Basic Logics 47
Programming Fundamentals using C

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

Basic Logics 48
Programming Fundamentals using C

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

Basic Logics 49
Programming Fundamentals using C

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

Basic Logics 50
Programming Fundamentals using C

Walkthroughs: Demo.
a b a+b c

5 2 7 1

6 4 10 9

7 6 13 17

8 8 18 25

9 10 19 33

10 12 22 41

Output
41

Basic Logics 51
Programming Fundamentals using C

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

Basic Logics 52
Programming Fundamentals using C

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: Modify Input


“%d %d” 12 8
int m,n, i, S=0;
“%d%d” 12 8
scanf(“%da%d”, &n, &m); “%d%d” 12
8
for (i=m; i<=n; i++) S+=i;
“%d-%d” 12-8
printf(“%d”, S);
What is the output if the input are 8a12?
Basic Logics 53
Programming Fundamentals using C

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
Basic Logics 54
Programming Fundamentals using C

Extra Demo: Print star characters

N=6 i

i= 1 * Print out 1*, “\n”


2 ** Print out 2*, “\n” Accept N;
for ( i=1; i<=N; i++)
3 *** Print out 3*, “\n” { for (j=1; j<=i; j++) printf(“*”);
printf (“\n”);
4 **** Print out 4*, “\n” }

5 ***** Print out 5*, “\n”


6 ****** Print out 6*, “\n”

Basic Logics 55
Programming Fundamentals using C

Extra Demo: Multiplication Table


N=5
5x 1= 5
5x 2=10
5x 3=15
5x 4=20 Accept n;
5x 5=25 for ( i=1; i<=10; i++)
Print out “%dx%2d=%2d\n”, n, i, n*i
5x 6=30
5x 7=37
5x 8=40
5x 9=45
5x10=50

Basic Logics 56
Programming Fundamentals using C

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.


Basic Logics 57
Programming Fundamentals using C

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.

Basic Logics 58
Programming Fundamentals using C

Thank You

Basic Logics 59

You might also like