0% found this document useful (0 votes)
38 views71 pages

Introduction to Computer Programming

CSE115
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)
38 views71 pages

Introduction to Computer Programming

CSE115
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

Overview of Computers

and
Programming
Mirza Mohammad Lutfe Elahi
CSE 115 Programming Language I ECE@NSU
2

Outline
• Overview of Computers
– Hardware

– Software

• Computer Languages

• Software Development Method

• Pseudo Code and Flowcharts

• Professional Ethics

CSE 115 Programming Language I ECE@NSU


3

Computers
• Computers receive input, store, process, and output
information.
• Computer can deal with numbers, text, images,
graphics, and sound.
• Computers are worthless without programming.
• Programming Languages allow us to write programs
that tell the computer what to do and to provide a way
to communicate with computers.
• Programs are then converted to machine instructions
so the computer can understand it.

CSE 115 Programming Language I ECE@NSU


4

Hardware & Software


• Hardware is the equipment used to perform the
necessary computations.
– Central Processing Unit (CPU), memory, disk storage,
monitor, keyboard, mouse, printer, etc.

• Software consists of the programs that enable us to


solve problems with a computer by providing it with a
list of instructions to follow
– Windows OS, MS Word, Mozilla Firefox, etc.

CSE 115 Programming Language I ECE@NSU


5

Computer Hardware
• Main Memory
– RAM - Random Access Memory - Memory that can be read and written in any
order (as opposed to sequential access memory), volatile.
– ROM - Read Only Memory - Memory that cannot be written to, non-volatile.

• Secondary Memory: Magnetic hard disks, Flash (solid state)


disks, Optical disks (CDs and DVDs).
• Central Processing Unit (CPU): Executes all computer
operations and perform arithmetic and logical operations.
• Input/Output Devices: keyboard, mouse, scanner, monitor,
printer, and speakers.
• Computer Networks – Computers that are linked together can
communicate with each other.
CSE 115 Programming Language I ECE@NSU
6

Components of a Computer

CSE 115 Programming Language I ECE@NSU


7

Memory
• Memory: a large collection of memory cells
• Each Memory Cell has an address and a value
0 One bit
• Bit: Binary digit = Either 0 or 1 1

Memory Addresses
2 Byte = 8 bits
• Byte: Made up of 8 bits 3
.
.
. Byte at
• Memory Address: position of a memory cell 16 65 address 16
17 value = 65
• Memory Content: Value stored in memory 18
.
.
.
– Every memory cell has content, whether we know it or not

• Memory capacity
– Kilobyte (KB) = 210 = 1024 Bytes; Megabyte (MB) = 220 Bytes > 106 Bytes
– Gigabyte (GB) = 230 > 109 Bytes; Terabyte (TB) = 240 Bytes > 1012 Bytes

CSE 115 Programming Language I ECE@NSU


8

Computer Software
• Operating System - controls the interaction between
machine and user. Examples: Windows, Linux, etc.
– Communicates with computer user.
– Collects input and Displays output.
– Manages memory and processor time.
– Manages Storage Disk.

• Application Software - developed to assist a computer


user in accomplishing specific tasks. Example: MS
Word, Google Chrome, etc.

CSE 115 Programming Language I ECE@NSU


9

Computer languages
• High-level Language: Combines algebraic expressions and
high-level commands
– High Level : Very far away from the actual machine language

– Examples: Fortran, C, Prolog, C#, Perl, and Java.

• Machine Language: A collection of machine instructions


– Not standardized. There is a different machine language for every
processor family.

• Assembly Language: uses symbols (called mnemonics) that


correspond to machine language instructions.
– Low level: Very close to the actual machine language.

CSE 115 Programming Language I ECE@NSU


10

Compiler
• Compilation is the process of translating the source code (high-
level) into executable code (machine level).
• Source file: contains the original program code
– A Compiler turns the Source File into an Object File

• Object file: contains machine language instructions


– A Linker turns the Object File into an Executable

• Integrated Development Environment (IDE): a program that


combines simple text editor with a compiler, linker, loader, and
debugger tool
– Examples: Code::Blocks, Eclipse, Visual Studio, etc.

CSE 115 Programming Language I ECE@NSU


Editing, Translating, Linking, and 11

Running High-Level Language Programs


-
I

↓ -

T
codeblocks ,

vscode
&

-
3
W

CSE 115 Programming Language I ECE@NSU


Flow of Information During Program 12

Execution

CSE 115 Programming Language I ECE@NSU


13

Software Development Method


1. Specify problem requirements

2. Analyze the problem

3. Design the algorithm to solve the problem

4. Implement the algorithm

5. Test and verify the completed program

6. Maintain and update the program

CSE 115 Programming Language I ECE@NSU


14

Steps Defined
1. Specification: statement that specifies the problem that should
be solved on the computer.
2. Analysis: Understanding the problem and identifying the
inputs, outputs, and required computation.
3. Design - Designing and developing the list of steps called
algorithm to solve the problem.
4. Implementation: writing the algorithm as a program using a
given programming language.
5. Testing - Testing requires checking and verifying that the
program actually works as desired.
6. Maintenance - Maintaining involves finding previously
undetected errors and keep it up-to-date.
CSE 115 Programming Language I ECE@NSU
15

Converting Miles to Kilometers


1. Specification: Your boss wants you to convert a list of miles to
kilometers. Since you like programming, you decide to write
a program to do the job.
2. Analysis
• We need to receive miles as input
• We need to output kilometers
• We know 1 mile = 1.609 kilometers
3. Design
1. Get distance in miles -
2. Convert to kilometers
-

3. Display kilometers
-

CSE 115 Programming Language I ECE@NSU


16

Implementation in C Language

S
/* compiler skips
* Converts distance in miles to kilometers.
*/
za
#include <stdio.h> // printf, scanf definitions > single
-
line comment

-a
#define KMS_PER_MILE 1.609 // conversion constant

dataty
s

a
int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometers

/* Get the distance in miles */


printf("Enter the distance in miles> ");
scanf("%f", &miles);

/* Convert the distance to kilometers */


W
kms = KMS_PER_MILE * miles;
calculation
/* Display the distance in kilometers */
printf("That equals %f kilometers.\n", kms);

}
return 0; Te
Sample Run:
Enter the distance in miles> 10.0
That equals 16.090000 kilometers

CSE 115 Programming Language I ECE@NSU


17

Converting Miles to Kilometers


5. Test: We need to test the previous program to make sure it
works. To test we run our program and enter different values
and make sure the output is correct.

6. Maintenance: Next time, your boss wants to add a new feature,


so he wants you to add support for converting different units.
Input: miles
* 1 609
kms miles
.

kms
Display =

CSE 115 Programming Language I ECE@NSU


18

Pseudo Code and Flowchart


• Algorithm - A list of steps for solving a problem.

• Pseudo code - A combination of English phrases and


language constructs to describe the algorithm steps.

• Flowchart - A diagram that shows the step-by-step


execution of a program

CSE 115 Programming Language I ECE@NSU


19

Why Use Pseudo Code?


• The benefit of pseudo code is that it enables the programmer to
concentrate on the algorithm without worrying about all the
syntactic details of a particular programming language.
• In fact, you can write pseudo code without even knowing what
programming language you will use for the final
implementation.
• Pseudo code cannot be compiled or executed, and does not
follow syntax rules. It is simply an important step in producing
the final code.
• Example:
Input Miles
Kilometers = Miles * 1.609
Output Kilometers

CSE 115 Programming Language I ECE@NSU


20

Another Example of Pseudo Code?


• Problem: Calculate your final grade for CSE 115
• Specification: Get different grades and then compute the final
grade.
• Analysis: We need to input grades for quizzes, assignments,
exams, class performance and the percentage each part counts
for. Then we need to output the final grade.
• Design
1. Get the grades: exams, quizzes, assignments, and labs.
2. Grade = 0.2 * Quizzes + 0.1 * Assignments + 0.25 * Midterm Exam +
0.35 * Final Exam + 0.1 * Class Performance
3. Output the Grade
• Implement and Test: Learn how to program in C, Write the
program, then input some test values, calculate and check the
final grade.
CSE 115 Programming Language I ECE@NSU
21

Flowchart
-
Process Start or Terminal
-

Document
- Decision
-

Display Manual Input

- -

CSE 115 Programming Language I ECE@NSU


22

Example of Flowchart

Start

Get Grades and Calculate Display


percentages Final grade Grade

End

CSE 115 Programming Language I ECE@NSU


23

Professional Ethics
• Privacy and Misuse of Data
– computer theft (computer fraud) - Illegally obtaining
money by falsifying information in a computer database

• Computer Hacking
– Virus - Code attached to another program that spreads
through a computer’s disk memory, disrupting the computer
or erasing information
– Worm - A virus that can disrupt a network by replicating
itself on other network computers

CSE 115 Programming Language I ECE@NSU


24

Professional Ethics
• Plagiarism and Software Piracy
– Software piracy – Violating copyright agreements by
illegally copying software for use in another computer

• Misuse of a Computer Resource

CSE 115 Programming Language I ECE@NSU


Overview of C
Programming

Mirza Mohammad Lutfe Elahi


CSE 115 Programming Language I ECE@NSU
2

Outline
§ History of C

§ C Language Elements

§ Data Types and Variable Declarations

§ Executable Statements

§ Input and Output Functions

§ General form of a C program

§ Arithmetic Expressions

§ Formatting Numbers in Program Output


CSE 115 Programming Language I ECE@NSU
3

History of C
§ C was developed in 1972 by Dennis Ritchie at AT&T
Bell Laboratories.
§ C was designed as a programming language to write
the Unix Operating System.
§ C became the most commonly used language for
writing system software.
§ C is machine independent: C programs can be
compiled to run on a wide variety of processors and
operating systems.

CSE 115 Programming Language I ECE@NSU


C Language Elements in 4

Miles-to-Kilometers Conversion Program


/*
* Converts distance in miles to kilometres.
*/ standard header file
preprocessor #include <stdio.h> /* printf, scanf definitions */
directives #define KMS_PER_MILE 1.609 /* conversion constant */
constant
int main(void) {
float miles, // input – distance in miles
reserved kms; // output – distance in kilometres
words
/* Get the distance in miles */
variables comments
printf("Enter distance in miles: ");
scanf("%f", &miles);
functions // Convert the distance to kilometres
kms = KMS_PER_MILE * miles;
special
// Display the distance in kilometres
symbols
printf("That equals %9.2f km.\n", kms);

return 0;
} punctuations

CSE 115 Programming Language I ECE@NSU


Program in Memory: Before (a) and After 5

Execution of a Program (b)


What happens in the computer memory?

CSE 115 Programming Language I ECE@NSU


6

Preprocessor Directives
§ Preprocessor directives are commands that give
instructions to the C preprocessor.
§ The preprocessor modifies a C program prior to its
compilation.
§ Preprocessor directives begin with #
#include <stdio.h>
– Includes Standard I/O Library header file (.h file)
#include <math.h>
– Includes Standard Math Library header file (.h file)
#define PI 3.141593
– Defines the constant PI

CSE 115 Programming Language I ECE@NSU


7

#include Directives
§ #include directive is used to include other source
files into your source file.
§ The #include directive gives a program access to a
standard library.
§ Standard Libraries contains useful functions and
symbols that are predefined by the C language.
– You must include <stdio.h> if you want to use the
printf and scanf library functions.
– stdio.h is called a header file (.h file). It contains
information about standard input and output functions that
are inserted into your program before compilation.
CSE 115 Programming Language I ECE@NSU
8

#define Directives
§ The #define directive instructs the preprocessor to
replace each occurrence of a text by a particular
constant value before compilation.
§ #define replaces all occurrences of the text you
specify with the constant value you specify
#define NAME value
#define KMS_PER_MILE 1.609
#define PI 3.141593

CSE 115 Programming Language I ECE@NSU


9

The main Function


• int main(void) marks the beginning of the main
function where program execution begins.
• Every C program has a main function.
• Braces { and } mark the beginning and end of the body of
function main.
• A function body has two parts:
– Declarations - tell the compiler what memory cells are
needed in the function
– Executable statements - (derived from the algorithm) are
translated into machine language and later executed by the
computer

CSE 115 Programming Language I ECE@NSU


10

Reserved Words
• A word that has special meaning to C and can not be
used for other purposes.

• These are words that C reserves for its own uses

• Built-in Types: int, float, double, char, etc.

• Control flow: if, else, for, while, return, etc.

• Always lower case

CSE 115 Programming Language I ECE@NSU


11

Standard Identifiers
§ Identifier - A name given to a variable or a function
§ Standard Identifier - An identifier defined in a
standard C library and has special meaning in C.
– Examples: printf, scanf
– Standard identifiers are not reserved words
– You can redefine standard identifiers if you want to, but it is
not recommended.
– For example, if you define your own function printf,
then you cannot use the C library function printf.

CSE 115 Programming Language I ECE@NSU


12

User Defined Identifiers


§ We choose our own identifiers to
– Name memory cells that will hold data and program results
– Name functions that we define
§ Rules for Naming Identifiers:
– An identifier consists only of letters, digits, and underscores
– An identifier cannot begin with a digit
– A C reserved word cannot be used as an identifier
– A standard C identifier should not be redefined
§ Examples of Valid identifiers:
– letter1, inches, KMS_PER_MILE
§ Examples of Invalid identifiers:
– 1letter, Happy$trout, return
CSE 115 Programming Language I ECE@NSU
13

Guidelines for Naming Identifiers


§ Uppercase and lowercase are different
– LETTER , Letter, letter are different identifiers
– Avoid names that only differ by case. They can lead to
problems of finding bugs (errors) in the program.
§ Choose meaningful identifiers (easy to understand)
§ Example: distance = rate * time
– Means a lot more than z = x * y
§ Choose #define constants to be ALL UPPERCASE
– Example: KMS_PER_MILE is a defined constant
– As a variable, we can probably name it:
KmsPerMile or Kms_Per_Mile

CSE 115 Programming Language I ECE@NSU


14

Data Types
§ Data Types: a set of values and a set of operations
that can be performed on those values
– int: Stores signed integer values: whole numbers
• Examples: 65, -12345
– double: Stores real numbers that use a decimal point
• Examples: 3.14159 or 1.23e5 (which equals 123000.0)
– char: Stores character values
• Each char value is enclosed in single quotes: 'A', '*'
• Can be a letter, digit, or special character symbol
– Arithmetic operations (+, -, *, /) and compare can be
performed on int and double variables. Compare
operations can be performed on char variables.
CSE 115 Programming Language I ECE@NSU
15

Integer and Floating-Point Data Types


§ Integer Types in C
Type Size in Memory Range
short 2 bytes = 16 bits -32768 to +32767
unsigned short 2 bytes = 16 bits 0 to 65535
int 4 bytes = 32 bits -2147483648 to +2147483647
unsigned int 4 bytes = 32 bits 0 to 4294967295
long 4 bytes = 32 bits Same as int
long long 8 bytes = 64 bits -9×1018 to +9×1018

§ Floating-Point Types in C
Type Size in Memory Approximate Range Significant Digits
float 4 bytes = 32 bits 10-38 to 10+38 6
double 8 bytes = 64 bits 10-308 to 10+308 15

CSE 115 Programming Language I ECE@NSU


16

Characters and ASCII Code


§ Character Type in C
Type Size in Memory ASCII Codes
char 1 byte = 8 bits 0 to 255

§ ASCII Codes and Special Characters


Character ASCII Code Special Characters Meaning
'0' 48 '' Space Character
'9' 57 '*' Star Character
'A' 65 '\n' Newline
'B' 66 '\t' Horizontal Tab
'Z' 90 '\'' Single Quote
'a' 97 '\"' Double Quote
'b' 98 '\\' Backslash
'z' 122 '\0' NULL Character
CSE 115 Programming Language I ECE@NSU
17

Variable Declaration
§ Variables: The memory cells used for storing a
program’s input data and its computational results
– The Value of a Variable can change at runtime

§ Variable declarations: Statements that communicate


to the compiler the names of variables in the program
and the type of data they can store.
– Examples:
double miles, kms;
int count;
char answer;
– C requires that you declare every variable in the program.
CSE 115 Programming Language I ECE@NSU
18

Executable Statements
§ Executable Statements: C statements used to write
or code the algorithm. C compiler translates the
executable statements to machine code.
§ Examples of executable Statements:
– Assignment Statements
– Function Calls, such as calling printf and scanf
– return statement
– if and switch statements (selection) - later
– for and while statements (iteration) - later

CSE 115 Programming Language I ECE@NSU


19

Assignment Statements
§ Stores a value or a computational result in a variable

variable = expression;

= is the Assignment Operator

§ The assignment statement computes the expression


that appears after the assignment operator and stores
its value in the variable that appears to the left.

CSE 115 Programming Language I ECE@NSU


Effect of 20

kms = KMS_PER_MILE * miles

The value assigned to kms is the result of multiplying


the constant KMS_PER_MILE by the variable miles.

CSE 115 Programming Language I ECE@NSU


Effect of 21

sum = sum + item

Read = as "becomes"
The assignment operator does NOT mean equality

CSE 115 Programming Language I ECE@NSU


22

Input/Output Operations and Functions


§ Input operation: data transfer from the outside world
into computer memory
§ Output operation: program results can be displayed
to the program user
§ Input/Output functions: special program units that
do all input/output operations
– printf : output function
– scanf : input function
§ Function call: used to call or activate a function
– Asking another piece of code to do some work for you
CSE 115 Programming Language I ECE@NSU
23

The printf function

function function arguments


name
printf("That equals %f kilometers.\n", kms);

format place holder print


string list

That equals 16.0900000 kilometers.

CSE 115 Programming Language I ECE@NSU


24

Placeholders
• Placeholders always begin with the symbol %
– % marks the place in a format string where a value will be
printed out or will be read
• Format strings can have multiple placeholders, if you
are printing multiple values

Placeholder Variable Type Function Use


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

CSE 115 Programming Language I ECE@NSU


25

Displaying Prompts
• When input data is needed in an interactive program,
you should use the printf function to display a
prompting message, or prompt, that tells the user what
data to enter.

printf("Enter the distance in miles> ");


printf("Enter the object mass in grams> ");

CSE 115 Programming Language I ECE@NSU


26

The scanf Function


function Number
name function arguments Entered 30.5
miles
scanf("%lf", &miles);
30.5
place holders input variables

§ The & is the address operator. It tells scanf the


address of variable miles in memory.
§ When user inputs a value, it is stored in miles.
§ The placeholder %lf tells scanf the type of data to
store into variable miles.
CSE 115 Programming Language I ECE@NSU
27

Reading Three Letters


char letter1, letter2, letter3;

scanf("%c%c%c",

&letter1, Letters
C a r
Entered
&letter2, letter1
C
&letter3);
letter2
a
letter3

CSE 115 Programming Language I ECE@NSU


28

Return Statement
§ Syntax: return expression ;
§ Example: return (0);
§ Returning from the main function terminates the
program and transfers control back to the operating
system. Value returned is 0.
§ The return statement transfers control from a
function back to the caller.
§ Once you start writing your own functions, you will
use the return statement to return the result of a
function back to the caller.

CSE 115 Programming Language I ECE@NSU


29

General Form of a C program

§ Preprocessor directives modify


the text of a C program before
compilation.
§ Every variable has to be
declared before using it.

§ Executable statements are translated into machine


language and eventually executed.
§ Executable statements perform computations on the
declared variables or input/output operations.
CSE 115 Programming Language I ECE@NSU
30

Comments
§ Comments making it easier for us to understand the program,
but are ignored by the C compiler.
§ Two forms of comments:
– /* C comment */ anything between /* and */ is
considered a comment, even if it spans on multiple lines.
– // C++ comment anything after // is considered a
comment until the end of the line.
§ Comments are used to create Program Documentation
– Help others read and understand the program.
§ The start of the program should consist of a comment that
includes programmer’s name, date, current version, and a brief
description of what the program does.
§ Always Comment your Code!
CSE 115 Programming Language I ECE@NSU
31

Programming Style
§ Why we need to follow conventions?
– A program that looks good is easier to read and understand
than one that is sloppy.
– 80% of the cost of software goes to maintenance.
– Hardly any software is maintained for its whole lifetime by
the original author.
– Programs that follow the typical conventions are more
readable and allow engineers to understand the code more
quickly and thoroughly.
§ Check your text book and expert programmers on how
to improve your programming style.
CSE 115 Programming Language I ECE@NSU
32

White Space
§ The compiler ignores extra blanks between words and
symbols, but you may insert space to improve the
readability and style of a program.

§ You should always leave a blank space after a comma


and before and after operators such as: + − * /
and =

§ You should indent the lines of code in the body of a


function.

CSE 115 Programming Language I ECE@NSU


33

White Space
Bad: Good:

int main(void) int main(void)


{ int foo,blah; {
scanf("%d",&foo); int foo, blah;
blah=foo+1; scanf("%d", &foo);
printf("%d", blah); blah = foo + 1;
return 0;} printf("%d", blah);
return 0;
}

CSE 115 Programming Language I ECE@NSU


34

Bad Programming Practice


§ Missing statement of purpose
§ Inadequate commenting
§ Variables names are not meaningful
§ Use of unnamed constant
§ Indentation does not represent program structure
§ Algorithm is inefficient or difficult to follow
§ Program does not compile
§ Program produces incorrect results
§ Insufficient testing (test case results are different than expected,
program is not fully tested for all cases)

CSE 115 Programming Language I ECE@NSU


35

Arithmetic Expressions
§ To solve most programming problems, you need to
write arithmetic expressions that compute data of type
int and double (and sometimes char)
§ Arithmetic expressions contain variables, constants,
function calls, arithmetic operators, as well as sub-
expressions written within parentheses.
§ Examples:
– sum + 1
– (a + b) * (c – d)
– (-b + sqrt(delta))/(2.0 * a)

CSE 115 Programming Language I ECE@NSU


36

Arithmetic Operators
Operator Meaning Examples
5 + 2 is 7
+ addition 5.0 + 2.0 is 7.0
'B' + 1 is 'C'
5 – 2 is 3
– subtraction 5.0 – 2.0 is 3.0
'B' – 1 is 'A'
5 * 2 is 10
* multiplication
5.0 * 2.0 is 10.0
5 / 2 is 2
/ division
5.0 / 2.0 is 2.5
% remainder 5 % 2 is 1
CSE 115 Programming Language I ECE@NSU
37

Operators / And %
Example Result Explanation
8/5 1 Integer operands à integer result
8.0/5.0 1.6 floating-point operands and result
8 /-5 -1 One operand is negative à negative result
-8 /-5 1 Both operands are negative à positive result
8%5 3 Integer remainder of dividing 8 by 5
8 %-5 3 Positive dividend à positive remainder
-8 % 5 -3 Negative dividend à Negative remainder

§ (m / n) * n + (m % n) is always equal to m
§ / and % are undefined when the divisor is 0.
CSE 115 Programming Language I ECE@NSU
38

Data Type of an Expressions


• What is the type of expression x+y when x and y are
both of type int? (answer: type of x+y is int)
• The data type of an expression depends on the type(s)
of its operands
– If both are of type int, then the expression is of type int.
– If either one or both operands are of type double, then the
expression is of type double.

• An expression that has mixed operands of type int


and double is a mixed-type expression.

CSE 115 Programming Language I ECE@NSU


39

Multi-Type Assignment Statement


§ The expression being evaluated and the variable to
which it is assigned have different data types
§ The expression is first evaluated; then the result is
assigned to the variable to the left side of = operator
– Example: what is the value of y = 5/2 when y is of type
double? (answer: 5/2 is 2; y = 2.0)
§ Warning: assignment of a type double expression to
a type int variable causes the fractional part of the
expression to be lost.
– Example: what is the type of the assignment y = 5.0 / 2.0
when y is of type int? (answer: 5.0/2.0 is 2.5; y = 2)
CSE 115 Programming Language I ECE@NSU
40

Type Conversion Through Casts


• C allows the programmer to convert the type of an
expression by placing the desired type in parentheses
before the expression.
• This operation is called a type cast.
– (double)5 / (double)2 is the double value 2.5

– (int)(9 * 0.5) is the int value 4

• When casting from double to int, the decimal


fraction is truncated (NOT rounded).

CSE 115 Programming Language I ECE@NSU


41

Example of the Use of Type Cast


/* Computes a test average */
#include <stdio.h>

int main(void)
{
int total; /* total score */
int students; /* number of students */
double average; /* average score */

printf("Enter total students score> ");


scanf("%d", &total);
printf("Enter number of students> ");
scanf("%d", &students);
average = (double) total / (double) students;
printf("Average score is %.2f\n", average);
return 0;
}

CSE 115 Programming Language I ECE@NSU


42

Expression with Multiple Operators


§ Operators are of two types: unary and binary
§ Unary operators take only one operand
– Unary minus (-) and Unary plus (+) operators

§ Binary operators take two operands


– Examples: addition (+), subtraction (–), multiplication (*),
division (/) and integer remainder (%) operators

§ A single expression could have multiple operators


– Example: -a + b * c – d / 2

CSE 115 Programming Language I ECE@NSU


43

Step-by-Step Expressions Evaluation

CSE 115 Programming Language I ECE@NSU


44

Evaluate: z - (a + b/2) + w*-y

CSE 115 Programming Language I ECE@NSU


45

Formatting Integers in Program Output


§ You can specify how printf will display integers
§ For integers, use %nd
– % start of placeholder
– n is the optional field width = number of columns to display
– If n is less than integer size, it will be ignored
– If n is greater than integer size, spaces are added to the left

Value Format Output Value Format Output


234 %4d 234 -234 %4d -234
234 %5d 234 -234 %5d -234
234 %6d 234 -234 %6d -234
234 %1d 234 -234 %2d -234
CSE 115 Programming Language I ECE@NSU
46

Formatting Type Double Values


Use %[Link] for double values
– n is the optional field width = number of digits in the whole
number, the unary minus, decimal point, and fraction digits
– If n is less than what the number needs it will be ignored
– .m is the number of decimal places (optional)
Value Format Output Value Format Output
3.14159 %5.2f 3.14 3.14159 %4.2f 3.14
3.14159 %3.2f 3.14 3.14159 %5.1f 3.1
3.14159 %5.3f 3.142 3.14159 %8.5f 3.14159
0.1234 %4.2f 0.12 -0.006 %4.2f -0.01
-0.006 %8.3f -0.006 -0.006 %8.5f -0.00600
-0.006 %.3f -0.006 -3.14159 %.4f -3.1416
CSE 115 Programming Language I ECE@NSU
47

Errors
§ Syntax Errors (Detected by the Compiler)
– Violating one or more grammar rules
– Missing semicolon (end of variable declaration or statement)
– Undeclared variable (using a variable without declaration)
– Comment not closed (missing */ at end of comment)
§ Run-Time Errors (NOT detected by compiler)
– Detected by the computer when running the program
– Illegal operation, such as dividing a number by zero
– Program cannot run to completion
§ Undetected and Logic Errors
– Program runs to completion but computes wrong results
– Input was not read properly
– Wrong algorithm and computation
CSE 115 Programming Language I ECE@NSU

You might also like