0% found this document useful (0 votes)
9 views60 pages

Top-Down Design and Programming Basics

Chapter 2 discusses top-down design, the program development cycle, and modular programming using functions and pointers. It outlines the steps involved in program development, including problem analysis, algorithm design, coding, and the use of programming tools like flowcharts and pseudocode. Additionally, it covers input/output functions in C, preprocessor commands, and the importance of functions for code modularity and reusability.

Uploaded by

kvreddy1526
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)
9 views60 pages

Top-Down Design and Programming Basics

Chapter 2 discusses top-down design, the program development cycle, and modular programming using functions and pointers. It outlines the steps involved in program development, including problem analysis, algorithm design, coding, and the use of programming tools like flowcharts and pseudocode. Additionally, it covers input/output functions in C, preprocessor commands, and the importance of functions for code modularity and reusability.

Uploaded by

kvreddy1526
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

Chapter-2

Top-Down Design with Functions


&
Pointers and Modular Programming:
CR RAOAIMSCS

Course: Programming for Problem Solving (PPS)

Course Instructor
Venu Nalla
Program Development Cycle
Many programmers follow a sequence of Steps to create their programs.

1. Analyze – Define the Problem


 Make sure that you understand what the program should do. What should the user be
able to enter? How? How does the program come up with an
answer? What does the program output? How?
 User – a person who uses a computer program.
 End User – the user that the program was made for.

2. Design – Plan a Solution for the Problem


 Develop a PRECISE sequence of steps to solve the problem
 An algorithm is a precise sequence of steps to solve aproblem.
Develop an Algorithm
Imagine you want a program that tells a user how many stamps they need in order to mail
a certain number of pages.

Youneed one stamp for every 5 pages


6 pages = 2stamps
12 pages = 3stamps
…

Write an algorithm (the steps needed) to solve this problem


Program Development Cycle – Design
(Continued)

Typically a program follows three general steps


1. Input
2. Processing (Formulas)
3. Output
Develop an Algorithm, 3rd Attempt
OK, now with THAT information, try developing the algorithm

One good algorithm developed could look like this:


1. Request the number of sheets of paper from the user; call it
Sheets (Input/Read)
2. Make sure Sheets is a positive whole number (Input/Validation)
3. Divide Sheets by 5 (Processing)
4. Round the result from step 3 up to the highest whole number; call it Stamps
(Processing)
5. Reply with the number Stamps (Output)
Programming Tools
Flowcharts – Achart that consists of symbols connected by arrows. Within each
symbol is a phrase presenting the activity at that step. The shape of the symbol
indicates the type of operation that is to occur.

Hierarchy Charts – Achart that shows the overall program structure. These charts
describe what each part, or module, does and how they are related. These modules
intentionally omit details of how they work.

Pseudocode – an abbreviated plain English version of actual computer code.


Kind of a mix between English and code.
THERE IS NO OFFICIAL SYNTAXTO PSEUDOCODE.
Flow Charts
Flow Line - indicates the flow of logic

Terminal – indicates the start or end of a task

Input/Output – used for input or output operations. What is to be input or output


should be in the figure.
Flow Charts
Processing - used to show a processing step. The instructions are displayed in
the figure.

Decision – used to show when a decision needs to be made.


Lines for yes and no come out of it. The question is displayed in the figure.

Connector – Used to join flow lines.


Stamps Flowchart
Start

Read
Sheets

Display Error No Is sheets a


positive

Message whole
number?

Yes
Set Stamps =
Sheets/5

Round Stamps to
nearest whole number

Display
Stamps

End
Hierarchy Chart
Postage Stamp
Program

Calculate
Input Display Stamps
Stamps

Set Stamps = Round Stamps to the


Read Sheets Validate Sheets
Sheets/5 next whole number
pseudo code
 Pseudocode is an artificial and informal language that helps programmers
develop algorithms.

 Pseudocode is a "text-based" detail (algorithmic) design [Link] rules of Pseudocode are


reasonably straightforward.

 All statements showing "dependency" are to be [Link] include while, do, for, if,
switch.
How toWrite Pseudocode
Always capitalize the initial word (often one of the main six constructs).
Make only one statement per line.
Indent to show hierarchy, improve readability, and show nested constructs.
Always end multi-line sections using any of the END keywords (ENDIF, ENDWHILE, etc.).
pseudo code -example
Program: sum of two numbers
Pseudocode:
Start
Declare variables x, y, and z
Set value of x to 5
Set value of y to 10
Calculate the sum of x and y
Print the sum z
Stop
Program Development Cycle
3. Write the Code – Implement a solution
 The instructions in a programming language collectively called code.

 Your code should be a translation of your algorithm developed into the


programming language.

 In this class we use C, but there are many other programming languages: C++, Java,
C#, Ruby, Python,Visual Basic, etc.

 This is the major focus of this course, but note that you need to be able to think
algorithmically in order to do this.
 Meaning, you need to be able to logically solve the problem in order to write a program for it.
I/O :Input andOutput
Printf()
 Showing Output with Printf() Function

 It is one of the most used functions in C. The printf() function is basically defined in the
header file stdio.h, and we use it for showing the standard output (the output available
on the console).

 The programmers use the printf() function for printing the value of the variable or any
simple sentence (text). These variables can be of float, char, int, or other data types.
#include <stdio.h>
#include <stdio.h>
int main() {
int main() int year =1997;
{ int month = 08;
int q = 50; int day = 18;
printf(“Today’s date is: %d-%d-%d”, year, month, day);
printf(“The given value of q is: %d”, q); return 0;
}
return 0;
} The Output generated here would be:
Today’s date is 1997-08-18
Scanf()
 Taking Input with Scanf() Function

 We make use of the scanf() function whenever we want the program to receive inputs from us.
Thus, when the program receives input from the user, it stores those input values into any variable.

 In short, we use the scanf() function to receive inputs of all datatypes from a user. The only thing
that we must take care of is that those variables in which we store the input values have a similar
data type.

Taking Input of Integer Value


#include <stdio.h>
int main() {
int input_from_user;
printf(“Hello, please enter a digit here: “); scanf(“%d”, &input_from_user);
printf(“The digit that you entered is: %d”, input_from_user);
return 0;
}

The Output generated here would be:


Hello, please enter a digit here: 25
The digit that you entered is: 25
stdin stdout and stderr in c
stdin − It stands for standard input, and is used for taking text as an input.
stdout − It stands for standard output, and is used to text output of any command
you type in the terminal, and then that output is stored in the stdout stream.
stderr − It stands for standard error.

Preopened File Streams - stdin, stdout, and stderr


• FILE *stdin
• stdin is associated with a user's standard input stream.
• FILE *stdout
• stdout is associated with an output stream used for normal program output.
• FILE *stderr
• stderr is associated with an output stream used for error messages.
Preprocessor Commands
• The C Preprocessor is not a part of the compiler but is a
separate step in the compilation process.

• In simple terms, a C Preprocessor is just a text substitution tool


and it instructs the compiler to do required pre-processing
before the actual compilation.

• All preprocessor commands begin with a hash symbol (#).


Types of Preprocessor Commands
There are three types of preprocessor commands.
• 1 : macro substitution
– Eg: #define
• 2 : file inclusion.
– Eg: #include
• 3 : conditional compilation directives.
– Eg: #if, #else, #ifndef
#include
• The #include preprocessor directive is used to paste code of
given file into current file.

• It is used to include system-defined and user-defined header


files.

• If included file is not found, compiler renders error.

• By the use of #include directive, we provide information to


the preprocessor where to look for the header files.
#include (cntd…)
• There are two variants to use #include directive.
– #include <filename>
• The #include <filename> tells the compiler to look for the directory where
system header files are held.
• In UNIX, it is \usr\include directory.
• Eg: #include <stdio.h>
– #include "filename"
• The #include "filename" tells the compiler to look in the current directory
from where program is running.
• Eg: #include “sum.c”
#include (cntd…)
• In #include directive, comments are not recognized. So in case of
#include <a//b>, a//b is treated as filename.

• In #include directive, backslash is considered as normal text not


escape sequence. So in case of #include <a\nb>, a\nb is treated as
filename.

• You can use only comment after filename otherwise it will give
error.
#define
• It can use any basic data type
• The #define preprocessor directive is used to define constant
or macro substitution.
• A macro is a segment of code which is replaced by the value of
macro.
• There are two types of macros:
– Object-like Macros
– Function-like Macros
#define (cntd…)
• Object-like Macros
– The object-like macro is an identifier that is replaced by value.
– It is widely used to representnumeric constants.
– For Eg: #define PI 3.14
• Here, PI is the macro name which will be replaced by the value 3.14.
• Function-like Macros
– The function-like macro looks like function call.
– For Eg: #define MIN(a,b) ((a)<(b)?(a):(b))
• Here, MIN is the macro name.
#define (cntd…)
• Predefined Macros
• There are some predefined macros which are
readily for use in C programming.
Macro Description
_DATE_ represents current date in "MMM DD YYYY" format
_TIME_ represents current time in "HH:MM:SS" format.
_FILE_ represents current file name.
_LINE_ represents current line number.
_STDC_ It is defined as 1 when compiler complies with the ANSI standard.
#define (cntd…)
#include <stdio.h>
main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
}

Output
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
#undef
• The #undef preprocessor directive is used to undefine
the constant or macro defined by #define.
• The #undef directive is used to define the preprocessor
constant to a limited scope so that you can declare
constant again.
#include <stdio.h>
#define number 15
int square=number*number;
#undef number
main() {
printf("%d",square);
}
Output:
225
#ifdef example
#include <stdio.h>
• The #ifdef preprocessor directive #include <conio.h>
checks if macro is defined by #define NOINPUT
void main()
#define. {
int a=0;
#ifdef NOINPUT
a=2;
• If yes, it executes the code #else
otherwise #else code is executed, printf("Enter a:");
scanf("%d", &a);
if present. #endif
printf("Value of a: %d\n", a);
}
#ifndef Example
#include <stdio.h>
• The #ifndef preprocessor #include <conio.h>
directive checks if macro is void main()
{
not defined by #define. int a=0;
#ifndef INPUT
a=2;
#else
• If yes, it executes the code printf("Enter a:");
scanf("%d", &a);
otherwise #else code is #endif
printf("Value of a: %d\n", a);
executed, if present. }

Output:
Value of a: 2
#if , #elif Example
• The #if preprocessor #include <stdio.h>
directive evaluates the #include <conio.h>
#define NUMBER 1
expression or condition. void main()
{
• If condition is true, it #if (NUMBER==0)
printf("1 Value of Number is: %d",NUMBER);
executes the code #elif (NUMBER==1)
printf("2 Value of Number is: %d",NUMBER);
otherwise #elif or #else #else
printf(“error value with Number");
or #endif code is #endif
executed. getch();
}
Output:
2 Value of Number is: 1
#error Example
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
• The #error preprocessor directive #else
indicates error. void main()
{
• The compiler gives fatal error if float a;
a=sqrt(7);
#error directive is found and skips
printf("%f",a);
further compilation process. }
#endif

Output:
Compile Time Error: First include then compile
Functions in C Programming

• Definition: A function is a block of code designed to perform a specific task.

• Importance: Functions allow for code modularity, reusability, and organization in


programs.

• Role of Functions: Divides the program into smaller, manageable parts


Designing Structured Programs

• What is Structured Programming?


– A programming paradigm aimed at improving clarity, quality, and development
time.

• Key benefits:
– Modularity: Breaks down tasks into functions.
– Reusability: Use the same function in multiple parts of a program.
– Maintainability: Easier to debug and modify code.
Signature of a Function

• Definition: A function’s signature includes its name, parameters, and order/type of


parameters.

• Importance: Uniquely identifies the function and its usage in a program.

• Example: int multiply(int, int);

• Distinguishes functions that may share the same name but differ in parameters
(function overloading in some languages, though C does not support it).
Declaring a Function

• Syntax:
return_type function_name(parameter_list);

• Example:
int add(int a, int b);

• Explanation:
• int: Return type, function returns an integer.
• add: Name of the function.
• (int a, int b): Parameters the function accepts
Parameters and Return Type of a Function

• Parameters: Values passed to a function for processing.


– Example: (int a, int b)

• Return Type: Data type of value function returns to the caller.


– For example, int means the function returns an integer.

• Function with No Return Type:


– Use void to indicate no value is returned.
Passing Parameters to Functions

• Parameter-passing techniques:
– Call by Value: Copies the actual value; changes in the function do not affect the
original variable.
– Call by Reference: Directly refers to the original variable, allowing modifications.

• Example in C
– void example_fn (int value);
Call by Value

• Definition: A copy of the actual parameter’s value is passed to the function.

Example:
void increment(int x)
{
x = x + 1;
}

• Changes to x only affect the function’s copy, not the original variable.
Passing Arrays to Functions

• Syntax:
void displayArray(int arr[], int size);

• Arrays are passed by reference.

• Changing array elements within the function affects the original array.

• Example Usage
displayArray(myArray, 5);
Idea of Call by Reference
• Overview: Passes a reference (address) rather than a copy of the variable.

• Example:
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

• Explanation: Useful for functions needing to modify multiple variables.


Passing Pointers to Functions

• Definition: Passing a pointer allows the function to modify the actual variable value.

• Example:
void modifyValue(int *ptr)
{
*ptr = 10;
}

• Explanation: Modifies the actual variable by using its address.


Structural Charts
• A Structure Chart is a diagram that shows the hierarchical
arrangement of modules, how they interact, and how data
flows between them.

• Structure Chart Elements


– Main module at the top (starting point of the program)
– Sub-modules connected below, representing tasks broken down
– Arrows showing relationships and data/control flow
– Parameters passed between modules are indicated by annotations
Structural Charts – Eg1
• Main Problem: Build a system that manages books in a library.
• Sub-modules:
– Main(): Controls program flow
• AddBook(): Adds a new book record
• RemoveBook(): Deletes a book record
• SearchBook(): Finds a book
• DisplayBooks(): Shows all books
• Structural Chart:
Main
├── AddBook(title, author, id)
├── RemoveBook(id)
├── SearchBook(keyword)
└── DisplayBooks()
Structural Charts – Eg2
• Let’s say
void helperFunction() {
printf("Inside helper function\n");
}
void process() {
helperFunction(); // Called from process()
}
int main() {
process();
return 0;
}

• Structural Chart
Main()
└── process()
└── helperFunction()
Command Line Arguments
• Command line arguments may be passed by specifying them under
main( ).
int main(int argc, char *argv[ ]);

• argc tells us the number of command line arguments

• argv[0] is the first, argv[1] is the second, argv[2] is the third etc.
Example code to print arguments
#include <stdio.h> $ ./[Link] Anirban 21 8.3
0: ./[Link]
int main(int argc, char *argv[])
1: Onish
{
int i; 2: 21
3: 8.3
for(i=0; i<argc; i++)
{
printf("%d: %s\n",i,argv[i]); ./[Link] Onish 21 8.3
}
return 0; argc=4
}
“./[Link]”
argv “Onish”
“21”
“8.3”
Pointers
memory address
• When a variable is created in C, a memory address is assigned to the variable.

• The memory address is the location of where the variable is stored on the computer.

• When we assign a value to the variable, it is stored in this memory address.

• To access it, use the reference operator (&), and the result represents where the variable is
stored:

• For eg:
i n t myAge = 43;
p r in t f (" % p" , &myAge); / / Outputs 0x7ffe5367e044

• The memory address is in hexadecimal form (0x..). You will probably not get the same
result in your program, as this depends on where the variable is stored on your
computer.

• You should also note that &myAge is often called a "pointer". A pointer basically stores
the memory address of a variable as its value. To print pointer values, we use the %p
format specifier.
Pointers
• Pointers are one of the core components of the C programming language. A pointer can be used
to store the memory address of other variables, functions, or even other pointers.

• The use of pointers allows low-level memory access, dynamic memory allocation, and many
other functionality in C

• A pointer is defined as a derived data type that can store the address of other C variables
or a memory location. We can access and manipulate the data stored in that memory
location using pointers.

# include<stdio.h>
int main( )
{
int i = 3 ;
printf ( "Address of i = %u\n", &i ) ;
printf ( "Value of i = %d\n", i ) ;
printf ( "Value of i = %d\n", *( &i ) ) ;
return 0 ;
}
Pointer Types and their Sizes
int *alpha ;
char *ch ;
float *s ;

• Here, alpha, ch and s are declared as pointer variables, i.e., variables that hold addresses.

• The declaration float *s means that s is going to contain the address of a floating-point value.
Similarly, char *ch means that ch is going to contain the address of a char value.

• Even though alpha, ch and s are different types of pointers, they all hold addresses. So, their sizes
would be same. These sizes can be obtained using the sizeof operator as shown below:

printf ( "%d %d %d", sizeof ( alpha ), sizeof ( ch ), sizeof ( s ) ) ;


Example

i n t myAge = 43;
i n t * ptr = &myAge;

the name p t r, t h a t stores the address o f myAge

/ / Output the value o f myAge (43)


p r in t f ( " % d \ n " , myAge);

/ / Output the memory address o f myAge (0x7ffe5367e044)


p r in t f ( " % p \ n " , &myAge);

/ / Output the memory address o f myAge with the pointer (0x7ffe5367e044)


p r in t f ( " % p \ n " , p t r ) ;
Dereference
Dereference
In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).

You can also get the value of the variable the pointer points to, by using the * operator (the
dereference operator):

i n t myAge = 43;
i n t * p t r = &myAge;

/ / Reference: Output the memory address o f myAge with the pointer (0x7ffe5367e044)
p r in t f ( " % p \ n " , p t r ) ;

/ / Dereference: Output the value of myAge with the pointer (43)


p r in t f ( " % d \ n " , * p t r ) ;
Multiple Calls to a Function with Input/Output Parameters
(Call by Reference)
A function can be called multiple times, and each time the same pointer arguments
can be updated.
#include <stdio.h>

void increment(int *val) {


*val = *val + 1;
}

int main() {
int count = 0;
increment(&count);
increment(&count);
increment(&count);
printf("Final count: %d\n", count);
return 0;
} This program increments count three times.
Uses of Pointers
• To return multiple values from a function in an indirect manner, call by reference is
used.

• To access or manipulate elements of an array or string.

• If a large object (like an array or structure) is passed to a function by value, a copy of it


would be created when the function collects it. This leads to wastage of precious
memory space. This can be avoided by passing the address of the large object and
collecting it in a pointer.

• At times, we are required to allocate memory for an object (like an array or structure)
dynamically when the program is executing. This dynamically allocated memory is later
accessed using pointers.

• There are different ways in which data can be organized in memory with a view to
storing and accessing it easily. To do this, various data structures, such as stacks, queues,
trees, hash tables, and graphs, are used. To implement these data structures, pointers
are used.
Storage Classes
• Storage classes in C define the scope, lifetime, and visibility of variables
and functions.

• Four Types:
– Auto
– Register
– Static
– extern
Auto Storage Class
• The auto storage class is the default for local variables.

• The variable is stored in memory (RAM) and is only accessible within the function/block
where it is declared.

• Scope: Local to the block in which it is declared.

• Lifetime: Exists until the block/function exits.

• Visibility: Not visible outside the block.

• Example:
void func() {
auto int num = 10; // Automatically local
printf("%d", num);
}
Register Storage Class
• The register storage class requests the compiler to store the variable in a CPU register instead of
RAM for faster access.

• Used for variables that are accessed frequently.

• Scope: Local to the block in which it is declared.

• Lifetime: Exists until the block/function exits.

• Visibility: Not visible outside the block.

• Note: The compiler may ignore the register request if the CPU registers are full.

• Example:
void func() {
register int counter = 0;
for (counter = 0; counter < 10; counter++) {
printf("%d", counter);
}
}
Static Storage Class
• The static storage class retains the variable's value even after the function exits. The variable is
initialized only once.

• In a global scope, a static variable is only visible within the file in which it is declared.

• Scope: Local to the block or file but retains value between function calls.

• Lifetime: The entire program execution.

• Visibility: Depends on where it is declared:


– Local Static: Within the function/block.
– Global Static: Within the file.

• Example:
void func() {
static int count = 0;
count++;
printf("%d", count);
}
Extern Storage Class
• The extern storage class is used to declare a global variable or function in another file.

• It extends the visibility of the C variables and functions across multiple files.

• Scope: Global, accessible throughout the program.

• Lifetime: The entire program execution.

• Visibility: Across multiple files.

• Example:
(Declaration in file1.c)
int count = 0;

(Access in file2.c)
extern int count;
void increment()
{
count++;
}
Storage Class Comparison

Storage Class Scope Lifetime Visibility


Until block/function
auto Local to block Within block
exits
Until block/function
register Local to block Within block
exits
Entire program
static Local/Global Within block/file
execution
Entire program
extern Global Across multiple files
execution

Storage classes control the visibility, scope, and lifetime of variables in C. Understanding
them is essential for effective memory management and program structure.

You might also like