KEMBAR78
Lesson-2 - Progr. Process and Running Programs in C | PDF | Computer Program | Programming
0% found this document useful (0 votes)
7 views84 pages

Lesson-2 - Progr. Process and Running Programs in C

This document outlines the fundamentals of programming in C, including the structure of a C program, the programming process from creation to execution, and the importance of comments and data types. It covers various programming concepts such as variable declarations, assignment statements, and input/output operations, along with common programming errors. Additionally, it discusses the problem-solving process and provides examples related to payroll calculations and a miles-to-kilometers conversion program.

Uploaded by

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

Lesson-2 - Progr. Process and Running Programs in C

This document outlines the fundamentals of programming in C, including the structure of a C program, the programming process from creation to execution, and the importance of comments and data types. It covers various programming concepts such as variable declarations, assignment statements, and input/output operations, along with common programming errors. Additionally, it discusses the problem-solving process and provides examples related to payroll calculations and a miles-to-kilometers conversion program.

Uploaded by

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

Lesson-2

Programming Process and


Running Programs in C

Sunday, September 15, 2019 1


Objectives

• To become familiar with the general form of a C program


and the basic elements in a program
• Understand the programming process from creation to
execution
• To appreciate the importance of writing comments in a
program
• To understand the use of data types and the differences
between the data types int, double, and char
• To know how to declare variables
Sunday, September 15, 2019 2
Objectives

• To understand how to write assignment statements


to change the value of variables
• To learn how C evaluates arithmetic expressions and
how to write them in C
• To learn how to read data values into a program and
to display results
• To understand how to write format strings for data
entry and display

Sunday, September 15, 2019 3


Objectives

• To learn how to use redirection to enable the use of


files for input/output
• To understand the differences between syntax errors,
run-time errors, and logic errors, and how to avoid
them and to correct them

Sunday, September 15, 2019 4


C Programming Language

• A high-level programming language


• Developed in 1972 by Dennis Ritchie at AT&T Bell Labs
• Designed as language to write the Unix operating system
• Resembles everyday English
• Very popular

Sunday, September 15, 2019 5


Programming is not Difficult

Is Programming Difficult?
Click Here

Sunday, September 15, 2019 6


Uses of C

Mainly because it produces code that runs nearly as fast as


code written in assembly language. Some examples of the use
of C might be: ⮚ Operating Systems
⮚ Language Compilers
⮚ Assemblers
⮚ Text Editors
⮚ Print Spoolers
⮚ Network Drivers
⮚ Modern Programs
⮚ Data Bases
⮚ Language Interpreters
⮚ Utilities
Sunday, September 15, 2019 7
Why use C?

The largest measure of C's success seems to be based


on purely practical considerations:
▪the portability of the compiler;
▪the standard library concept;
▪a powerful and varied repertoire of operators;
▪an elegant syntax;
▪ready access to the hardware when needed;
▪and the ease with which applications can be
optimised by hand-coding isolated procedures
Sunday, September 15, 2019 8
Programming and Problem-Solving

Sunday, September 15, 2019 9


Steps in
Problem Solving Process

• Analysis and specification of the task


(problem definition)
• Design of the software
(object and algorithm design)
• Coding(Development)
• Testing and Implementation
• Deployment and Maintenance and
• Evolution of the system
Note: There should be proper documentation of the
process.
Understanding and Analyzing
the Problem (Example 1)

• Example 1:
The personnel office of Babcock University is assigned
the task of computing the monthly emolument of all
category of employees of the institution
The employee taxation is based on the following
constraints;
Understanding and Analyzing the
Problem

⚫ If basic salary is less than or equal to N5000, 5% of basic


salary is deducted as tax otherwise 8% deducted.
⚫ Also 10% of the employee gross pay should be deducted
as part of pension scheme.
⚫ It is required that each employee pay slip should contain
employee number, name, total allowance, tax, basic
salary, gross pay and Net pay
Understanding and Analyzing the Problem

• Analyse the above problem and identify the


output, input and processing requirements
• Draw the flowchart for the payroll system
Understanding and Analyzing the Probl

• Input data/requirement:
–Employee Number
–Employee Name
–Basic salary
–Housing allowance
–Transport allowance
–Meal subsidy
Understanding and Analyzing the Problem

• Processing requirements:
–If Basic salary is <=5000, Tax = 5% of Basic salary
Else Tax = 8% of basic salary.
–Total allowances = Housing + Transport + meal subsidy
–Gross Pay = Basic salary + Total allowances
–Contributory pension= 10% of Gross Pay
–Net pay = Gross pay – (Tax + contributory pension)
Understanding and Analyzing
the Problem

• Solution:
• Output requirements:
– Employee Number
– Employee Name
– Total allowance
– Tax
– Contributory Pension
– Basic salary
– Gross pay
– Net pay
Algorithms

• Algorithm
– A sequence of precise instructions that
leads to a solution

• Program
– An algorithm expressed in a language the
computer can understand
Display ALG.
Program Design

❑ Programming is a creative process


– No complete set of rules for creating a program

❑ Program Design Process


▪ Problem Solving Phase
• Result is an algorithm that solves the problem
▪ Implementation Phase
• Result is the algorithm translated into a programming
language
Problem Solving Phase

❑ Be certain the task is completely specified


– What is the input?
– What information is in the output?
– How is the output organized?

❑ Develop the algorithm before implementation


– Experience shows this saves time in getting your
program to run.
– Test the algorithm for correctness
Implementation Phase

• Translate the algorithm into a programming


language
– Easier as you gain experience with the language

• Compile the source code


– Locates errors in using the programming language

• Run the program on sample data


– Verify correctness of results

• Results may require modification of Display IMPL.


the algorithm and program
Creating and Executing a Program

• input data
– the data values that are scanned by a
program

• program output
– the lines displayed by a program

Sunday, September 15, 2019 21


Flow of Information During
Program Execution

Sunday, September 15, 2019 22


Testing and Debugging

• Bug
– A(n) mistake(error) in a program
• Debugging
– Eliminating mistakes(errors) in programs
– Term used when a moth caused a failed relay
on the Harvard Mark 1 computer. Grace Hopper
and other programmers taped the moth in logbook
stating:
“First actual case of a bug being found.”
Common
Programming Errors

• Syntax errors
– Violation of the grammar rules of the language
– Discovered by the compiler
• Error messages may not always show correct location of
errors
• Run-time errors
– Error conditions detected by the computer at run-time
– an attempt to perform an invalid operation
• Logic errors
– Errors in the program’s algorithm
– Most difficult to diagnose
– Computer does not recognize an error
Quick Review

• Can you…
– Describe the first step to take when creating a program?

– List the two main phases of the program design process?

– Explain the importance of the problem-solving phase?

– List the steps in the software life cycle?


Quick Review

• Can you…
– Describe the three kinds of program errors?

– Tell what kind of errors the compiler catches?

– What kind of error is produced if you forget a


punctuation symbol such as a semi-colon?

– Tell what type of error is produced when a program


runs but produces incorrect results?
C-Language Elements

• preprocessor
– a system program that modifies a C program priori
to its compilation
• library
– a collection of useful functions and symbols that
may be accessed by a program
– each library has a standard header file whose
name ends with the symbols “.h”
stdio.h

Sunday, September 15, 2019 27


C-Language Elements

• preprocessor directive
– a C program line beginning with # that provides an
instruction to the preprocessor

#include <stdio.h>
#define KMS_PER_MILE 1.609

Sunday, September 15, 2019 28


C-Language Elements

• constant macro
– a name that is replaced by a particular constant
value before the program is sent to the compiler

#define KMS_PER_MILE 1.609


constant macro
constant

kms = KMS_PER_MILE * miles;

Sunday, September 15, 2019 29


C-Language Elements

• comment
– text beginning with /* and ending with */ that
provides supplementary information but is
ignored by the preprocessor and compiler

Multiple lines-/* Get the distance in miles */

Single line-//

Sunday, September 15, 2019 30


C Language Elements in
Miles-to-Kilometers Conversion
Program

Sunday, September 15, 2019 31


Function main

• Every C program has a main function.


int
main (void)

• These lines mark the beginning of the main function where


program execution begins.

Sunday, September 15, 2019 32


Function main

• declarations
– the part of a program that tells the compiler the
names of memory cells in a program
• executable statements
– program lines that are converted to machine
language instructions and executed by the
computer

Sunday, September 15, 2019 33


C-Language Elements

• reserved word
– a word that has a special meaning in C
– identifiers from standard library and names for
memory cells
– appear in lowercase
– cannot be used for other purposes
return 0;

Sunday, September 15, 2019 34


C-Language Elements

• standard identifier
– a word having special meaning but one that a
programmer may redefine
– redefinition is not recommended

printf(“Enter the distance in miles “);

Sunday, September 15, 2019 35


User-defined identifiers
(Variables)

• These name memory cells that hold data and program


results and to name operations that we define.
• Naming rules:
1. An identifier must consist only of letters, digits and underscores.
2. An identifier cannot begin with a digit.
3. A C reserved word cannot be used an an identifier.
4. An identifier defined in a C standard library should not be
redefined.
5.An identifier is case sensitive.

Sunday, September 15, 2019 36


Implementing
Miles-to-Kilometers Conversion Program

Run Code
See Code

Sunday, September 15, 2019 37


Variable Declarations AND Definition

• variable
– a name associated with a memory cell whose
value can change
• variable declarations
– statements that communicate to the compiler the
names of variables in the program and the kind of
information stored in each variable(data type)

Sunday, September 15, 2019 38


Variable Declarations

• C requires you to declare every variable used in a


program.
• A variable declaration begins with an identifier that
tells the C compiler the type of data store in a
particular variable.

int hours;
double miles;

Sunday, September 15, 2019 39


Data Types

• int
– a whole number
– 435
• Double(double has 2x more precision than float)
– a real number with an integral part and a fractional part
separated by a decimal point
– 3.14159
• char
– an individual character value
– enclosed in single quotes
– ‘A’, ‘z’, ‘2’, ‘9’, ‘*’, ‘!’
Sunday, September 15, 2019 40
C-Data Types

Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc

The size of float


(single precision
float data type) is
4 bytes. And the
size of double
(double precision
float data type) is
8 bytes.

Sunday, September 15, 2019 41


Internal Format of
Type int and Type double

Sunday, September 15, 2019 42


Executable Statements

• Follow the declarations in a function.


• Used to write or code the algorithm and its
refinements.
• Are translated into machine language by the
compiler.
• The computer executes the machine language
version.

Sunday, September 15, 2019 43


Memory
(a) Before and
(b) After Execution of a Program

Sunday, September 15, 2019 44


Executable Statements

• assignment statement
– an instruction that stores a value of a
computational result in a variable

kms = KMS_PER_MILE * miles;

Sunday, September 15, 2019 45


Effect of kms = KMS_PER_MILE * miles;

Sunday, September 15, 2019 46


Executable Statements

• Assignment is not the same as an algebraic equation.


• The expression to the right of the assignment operator is
first evaluated.
• Then the variable on the left side of the assignment
operator is assigned the value of that expression.

sum = sum + item;

Sunday, September 15, 2019 47


Effect of sum = sum + item;

Sunday, September 15, 2019 48


Input /Output Operations and
Functions

• input operation
– an instruction that copies data from an input device
into memory
• output operation
– an instruction that displays information stored in
memory
• input/output function
– a C function that performs an input or output
operation
• function call
– calling or activating function
Sunday, September 15, 2019 49
The printf Function

• Displays a line of program output.


• Useful for seeing the results of a program execution.

printf(“That equals %f kilometers. \n”, kms);

Sunday, September 15, 2019 50


The printf Function

• function argument
– enclosed in parentheses following the function
name
– provides information needed by the function

printf(“That equals %f kilometers. \n”, kms);

function name

Sunday, September 15, 2019 51


The printf Function

• format string
– in a call to printf, a string of characters enclosed in
quotes, which specifies the form of the output line

printf(“That equals %f kilometers. \n”, kms);

Sunday, September 15, 2019 52


The printf Function

• print list
– in a call to printf, the variables or expressions
whose values are displayed
• placeholder
– a symbol beginning with % in a format string that
indicates where to display the output value

printf(“That equals %f kilometers. \n”, kms);

Sunday, September 15, 2019 53


Placeholders in format string

Placeholder Variable Type Function Use


%c char printf/scanf
%d int printf/scanf
%f double printf
% lf double scanf

Sunday, September 15, 2019 54


The scanf Function

• Copies data from the standard input device (usually


the keyboard) into a variable.

scanf(“%lf”, &miles);

scanf(“%c%c%c”, &letter_1, &letter_2, &letter_3);

Sunday, September 15, 2019 55


Effect of scanf("%lf", &miles);

Sunday, September 15, 2019 56


Scanning Data Line Bob

Sunday, September 15, 2019 57


The return Statement

• Last line in the main function.


• Transfers control from your program to the operating
system.
• The value 0 is optional; indicates that your program
executed without an error.

return (0);

Sunday, September 15, 2019 58


General Form of a C Program

Sunday, September 15, 2019 59


Escape Sequence

Notice that the characters \n were not printed on the screen. The
backslash (\) is called an escape character. It indicates that printf is
supposed to do something out of the ordinary. The escape
sequence \n means newline. Some Common escape
sequences are as follows:

Sunday, September 15, 2019 60


Class Work
1.Write the following in C
i).Babcock University
ii).Babcock
University
2.Write out numbers from 1 to 10 on the same line and also on separate line
3. Create a program that prints your name, address and Phone number
4. Given a = 5, b = 1, x = 10, and y = 5, create a program that outputs the result of the
formula
f = (a- b)(x-y) using a single printf() function
5. Create a program that uses escape sequence \" to print your favorite quote.
6. Create a new program that prompts a user for numbers and determines total
revenue using the following formula: Total Revenue = Price * Quantity.
7. Build a new program that prompts a user for data and determines a commission
using the following formula: Commission = Rate * (Sales Price – Cost).

Sunday, September 15, 2019 61


Program Style

• Use spaces consistently and carefully.


– One is required between consecutive words in a
program.
– Improves readability.
• Use comments to document your program.
– Also enhances readability.

Sunday, September 15, 2019 62


Arithmetic Operators

Arithmetic Operator Meaning Example


+ addition 5 + 2 is 7
5.0 + 2.0 is 7.0
– subtraction 5 – 2 is 3
5.0 – 2.0 is 3.0
* multiplication 5 * 2 is 10
5.0 * 2.0 is 10.0
/ division 5.0 / 2.0 is 2.5
5 / 2 is 2
% remainder 5 % 2 is 1

Sunday, September 15, 2019 63


Data Type of an Expression

• mixed-type expression
– an expression with operands of different types
• mixed-type assignment
– the expression being evaluated and the variable to
which it is assigned have different data types
• type cast
– converting an expression to a different type by
writing the desired type in parentheses in front of
the expression
Sunday, September 15, 2019 64
Expressions with Multiple
Operators

• unary operator
– an operator with one operand
– unary plus (+), unary negation (-)
– ex. x = -y;
• binary operator
– an operator with two operands
– ex. x = y + z;

Sunday, September 15, 2019 65


Rules for Evaluating Expressions

• Parentheses rule
– all expression must be evaluated separately
– nested parentheses evaluated from the inside out
– innermost expression evaluated first
• Operator precedence rule
– unary +, - first
– *, /, % next
– binary +, - last

Sunday, September 15, 2019 66


Rules for Evaluating
Expressions

• Right Associativity
– Unary operators in the same subexpression and at the
same precedence level are evaluate right to left.
• Left Associativity
– Binary operators in the same subexpression and at the
same precedence lever are evaluated left to right.

Sunday, September 15, 2019 67


Evaluation Tree for
area = PI * radius * radius;

Sunday, September 15, 2019 68


Step-by-Step Expression Evaluation

Sunday, September 15, 2019 69


Evaluation Tree and Evaluation for
v = (p2 - p1) / (t2 - t1);

Sunday, September 15, 2019 70


Evaluation Tree and Evaluation for
z - (a + b / 2) + w * -y

Sunday, September 15, 2019 71


Numerical Inaccuracies

• representational error
– an error due to coding a real number as a finite
number of binary digits
• cancellation error
– an error resulting from applying an arithmetic
operation to operands of vastly different
magnitudes
– effect of smaller operand is lost

Sunday, September 15, 2019 72


Numerical Inaccuracies

• arithmetic underflow
– an error in which a very small computational result
is represented as zero
• arithmetic overflow
– an error that is an attempt to represent a
computational result that is too large

Sunday, September 15, 2019 73


Mathematical Expressions

Write in C-Language
1. P(x) = x4 + 7x3 - 5x + 9

Sunday, September 15, 2019 74


Profit Wizard Program

Case Study(CS)

Sunday, September 15, 2019 75


Figure 2.13 Profit Wizard Program
Example-1

The Profit Wizard program uses concepts, such as variables,


input and output with printf() and scanf() functions, and
beginning arithmetic operators.

SEE CODE🡪

RUN CODE🡪

Sunday, September 15, 2019 76


Formatting Numbers
in Program Output

• field width
– the number of columns used to display a value

• When formatting doubles, you must indicate the total field


width needed and the number of decimal places desired.

Sunday, September 15, 2019 77


Interactive Mode, Batch Mode,
and Data Files

• interactive mode
– a mode of program execution in which the user
responds to prompts by entering (typing in) data
• batch mode
– a mode of program execution in which the
program scans its data from a previously prepared
data file

Sunday, September 15, 2019 78


Wrap Up

• Every C program has preprocessor directives and a


main function.
• The main function contains variable declarations and
executable statements.
• C’s data types enable the compiler to determine how
to store a value in memory and what operations can
be performed on that value.

Sunday, September 15, 2019 79


Lesson-2 -- End
Back
Display ALG. Next
Prog
ram
exec
Ente Proces ution
ring s:
,
and compi
Ru n ling,
Prog ning a
ram

Sunday, September 15, 2019 82


Miles-Km-Conversion Code

/* /*Convert the distance to kilometers*/


Converts distances from miles to kilometers kms = KMS_PER_MILE * miles;
*/
#include <stdio.h> /* printf, scanf definitions*/ /*Display the distance in kilometers.*/
#define KMS_PER_MILE 2.5 /*Conversion
constants*/ printf("That equals %1f kilometers.\n", kms);

int return(0);
main(void)
{ }
float miles, /*distance in miles*/
kms; 🡨BACK
/*Get the distance in miles*/
printf("Enter the distance in miles:");
scanf("%1f", &miles);

Sunday, September 15, 2019 83


Profit Wizard
/* /*-------------------------------------------*/
*Determines the profit made printf(“\nThe total Cost Price is $%.2f\
*/ n”, totcostprice);
#include <stdio.h>
main() /*Compute total selling Price of items*/
{ printf(“\nEnter selling price per unit:”);
int qty, float sellingprice,float totcostprice, scanf(“%2f”, &fsellingprice);
float totsellingprice; totsellingprice = qty*sellingprice;
float fRevenue, fCostprice;
fRevenue = 0; /*Compute Revenue*/
fCost = 0; fRevenue = totsellingprice-totcostprice;
/*Display the Revenue*/
/* Computing total cost price of items */ printf(“\nThe Revenue is determined as
printf(“Enter cost price per unit:”) $%.2f\n”, fRevenue);
scanf(“%2f”, &fCostprice);
printf(“Enter quantity of items:”); }
scanf(“%d”, &int qty);
Sunday, September 15, 2019
totcostprice = qty*fCostprice; 🡨BACK 84

You might also like