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

Leture 1

The document provides an overview of computer programming, focusing on computer languages, including machine language, assembly language, and high-level languages like C. It explains the components of a C program, including syntax, variables, data types, and input/output operations, along with examples of code. Key concepts such as compilers, preprocessor directives, and the structure of a C program are also discussed, emphasizing the importance of understanding programming fundamentals.

Uploaded by

taifurandalib859
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 views57 pages

Leture 1

The document provides an overview of computer programming, focusing on computer languages, including machine language, assembly language, and high-level languages like C. It explains the components of a C program, including syntax, variables, data types, and input/output operations, along with examples of code. Key concepts such as compilers, preprocessor directives, and the structure of a C program are also discussed, emphasizing the importance of understanding programming fundamentals.

Uploaded by

taifurandalib859
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/ 57

Computer Programming

Dr Khaleda Ali
[email protected]
Computer Languages

Machine Language
binary number codes understood by a specific CPU
Not standard
Different machine language for each type of CPU
Assembly Language
mnemonic codes that correspond to machine language instructions
Computer Languages

A Machine Language Program Fragment and Its


Assembly Language Equivalent
Computer Languages

High-Level Language
machine-independent programming language that combines
algebraic expressions and English symbols

prepared by NI, edited by MAF


Computer Languages

Compiler software
that translates a high-level language program into machine language
Source file
File containing a program written in a high-level language; the input
for a compiler
Syntax
Grammar rules of a programming language
Computer Languages

Object file
file of machine language instructions that is the output of a compiler
Linker
Software that combines object files and resolves cross-references to
create an executable machine language Program
Entering, Translating, and Running a High-Level
Language Program
Flow of Information During Program Execution
What is C?

Dennis Ritchie(1941-2011) – AT&T Bell Laboratories –


1969-1973
16-bit DEC PDP-11 computer (right)
Widely used today
extends to newer system architectures
efficiency/performance
low-level access
Basis for other languages
Edit, Compile and Execute
Source code
produces
Editor welcome.c
eg: welcome.c

Executable code
produces
Compiler Welcome.exe Cannot
compile?

Output
produces Incorrect
Execute Hello, welcome
to CSE 1201!
result?
eg: welcome.exe

Test, test, and test!


Our First Program (1/4)
/*
* Converts distance in miles to kilometres.
*/
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant */

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

/* Get the distance in miles */


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

// Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

// Display the distance in kilometres


printf("That equals %9.2f km.\n", kms);
Sample Run
return 0;
} Enter distance in miles: 10.5
That equals 16.89 km.
Our First Program (2/4)
▪ What happens in the computer memory?

memory memory memory

Executable code of Executable code of Executable code of


Ch2_MileToKm.c Ch2_MileToKm.c Ch2_MileToKm.c

miles miles miles


? 10.5 10.5

kms kms kms


? ? 16.89

At the beginning After user enters: 10.5 After this line is


Do not assume that
uninitialised variables to executed:
contain zero! (Very common
mistake.) scanf("%f", &miles); kms = KMS_PER_MILE * miles;
Our First Program (3/4)
/*
* 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
symbols
// Display the distance in kilometres
printf("That equals %9.2f km.\n", kms);

return 0;
} punctuations
Our First Program (3/4)
General form of a C program:

preprocessor directives
main function heading
{
declarations
executable statements
}
Preprocessor directives
a C program line begins with # provides an instruction to the C
preprocessor
It is executed before the actual compilation is done.
Two most common directives :
#include
#define
In our example (#include<stdio.h>) identifies the header file for
standard input and output needed by the printf().
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.
Function main
Identify the start of the program
Every C program has a main ( )
'main' is a C keyword. We must not use it for any other variable.
4 common ways of main declaration
The line int indicates that the main function returns an integer value ( 0 ) to the
operating system when it finishes normal execution. The symbols ( void ) indicate
that the main function receives no data from the operating system before it begins
execution.
int void main(void) main( )
main(void) main(void) { {
{ {

return 0; } }
} }
Program Structure: Declaration

Declaration Statements
Identifier: name of a variable or function
Reserved words (or keywords)
◻ e.g. int, void, double, return
Standard identifiers
◻ e.g. printf, scanf
User-defined identifiers
◻ Avoid reserved words and standard identifiers
◻ Consist only of letters, digit characters and underscores, and must not begin with
a digit character
◻ Case-sensitive
◻ e.g. invalid: 1Letter, double, int, TWO*FOUR, joe’s
valid: maxEntries, _X1234, this_IS_a_long_name
The curly braces { }

Identify a segment / body of a program


The start and end of a function
The start and end of the selection or repetition block.
Since the opening brace indicates the start of a segment with
the closing brace indicating the end of a segment, there
must be just as many opening braces as closing braces
(this is a common mistake of beginners)
Statement

A specification of an action to be taken by the computer as the


program executes.
Each statement in C needs to be terminated with semicolon (;)
Example:
#include <stdio.h>
int main(void)
{
printf(“I love programming\n”);
printf(“You will love it too once ”); statement
printf(“you know the trick\n”);
statement
return 0;
} statement
statement
Statement cont…

Statement has two parts :


Declaration
The part of the 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
I/O statements (e.g. printf, scanf)
Assignment statements
◻ stores a value or a computational result in a variable
◻ (Note: ‘=’ is not equality, but assignment)
e.g. kms = KMS_PER_MILE * miles;
C program skeleton

In short, the basic skeleton of a C program looks like this:


Preprocessor
#include <stdio.h> directives
int main(void)
Function main
{ Start of segment
statement(s);
return 0;

} End of segment
Identifiers

Words used to represent certain program entities (variables,


function names, etc).
Example:
int my_name;
my_name is an identifier used as a program variable
void CalculateTotal(int value)
CalculateTotal is an identifier used as a function name
Rules for naming identifiers
Rules Example
Can contain a mix of character and numbers. However it H2o
cannot start with a number
First character must be a letter or underscore Number1
_area
Can be of mixed cases including underscore character XsquAre
my_num
Cannot contain any arithmetic operators R*S+T
… or any other punctuation marks #@x%!!
Cannot be a C keyword/reserved word struct; printf;

Cannot contain a space My height


… identifiers are case sensitive Tax != tax
Variables

Variable a name associated with a memory cell whose value can


change;
The memory cells used for storing a program’s input data and its
computational results are called variables because the values stored
in variables can change
(and usually do) as the program executes.
Variable Declaration: specifies the type of a variable
Example: int num;
Variable Definition: assigning a value to the declared variable
Example: num = 5;
Basic Data Types
int
used to declare numeric program variables of integer type
whole numbers, positive and negative
keyword: int
int number;
number = 12;
Type of int format

Binary number
Basic Data Types cont…
float
fractional parts, positive and negative
keyword: float
float height;
height = 1.72;
Basic Data Types

sign exponent mantissa


Basic Data Types cont…

Type Range in Typical Microprocessor


Implementation
short −32,767 .. 32,767
unsigned short 0 .. 65,535
int −2,147,483,647 .. 2,147,483,647
unsigned 0 .. 4,294,967,295
long −2,147,483,647 .. 2,147,483,647
unsigned long 0 .. 4,294,967,295
Why different data types are used?
You may wonder why having more than one numeric type is
necessary. Can the data type double be used for all numbers?

Yes, but on many computers, operations involving integers are


faster than those involving numbers of type double . Less
storage space is needed to store type int values. Also,
operations with integers are always precise, whereas some
loss of accuracy or round-off error may occur when dealing
with type double numbers.

Slide 29
Basic Data Types cont…
char
equivalent to ‘letters’ in English language
Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
single character
keyword: char
char my_letter;
The declared character must be
my_letter = 'U'; enclosed within a single quote!
ASCII Code

American Standard Code for Information Interchange


particular code that specifies the integer representing each char
value.
The digit characters '0' through '9' have code values of 48
through 57 (decimal).
uppercase letters have the decimal code values 65 through 90
Lowercase letters have the decimal code values 97 through 122
the printable characters have codes from 32 (code for a blank
or space) to 126 (code for the symbol ~ ).
ASCII Code Table
Extended ASCII Code Table
Constant example – volume of a cone
#include <stdio.h>
int
main(void)
{
double height, radius, base, volume;
double pi = 3.14;
printf(“Enter the height and radius of the cone:”);
scanf(“%lf %lf”,&height, &radius);

base = pi * radius * radius;


volume = (1.0/3.0) * base * height;

printf(“\nThe volume of a cone is %lf ”, volume);


return 0;
}
#define
You may also associate constant using #define preprocessor directive
#include <stdio.h>
#define PI 3.14

int main(void)
{
double height, radius, base, volume;

printf(“Enter the height and radius of the cone:”);


scanf(“%lf %lf”,&height,&radius);

base = PI * radius * radius;


volume = (1.0/3.0) * base * height;
printf(“\nThe volume of a cone is %lf ”, volume);
return 0;
}
Input/Output Operations

Input operation
an instruction that copies data from an input device into memory
Output operation
an instruction that displays information stored in memory to the
output devices (such as the monitor screen)
Input/Output Functions

A C function that performs an input or output operation


A few functions that are pre-defined in the header file stdio.h
such as :
printf()
scanf()
getchar() & putchar()
The printf function

Used to send data to the standard output (usually the


monitor) to be printed according to specific format.
General format:
printf(“string literal”);
A sequence of any number of characters surrounded by double quotation
marks.
printf(“format string”, variables);
Format string is a combination of text, conversion specifier and escape
sequence.
The printf function cont…

Example:
printf(“Thank you”);
printf (“Total sum is: %d\n”, sum);
%d is a placeholder (conversion specifier)
◻ marks the display position for a type integer variable
\n is an escape sequence
◻ moves the cursor to the new line
Program Structure: Executable
e.g. sum = sum + item;

◻ Note: Left side of an assignment


statement is called lvalue – it must
be assignable

◻ Examples of invalid assignment (result in compilation error “lvalue required as


left operand of assignment”):
■ 32 = a;
■ a + b = c;
◻ Assignment can be cascaded, with associativity from right to left:
■ a = b = c = 3 + 6; // 9 assigned to variables c, b and a
■ The above is equivalent to: a = (b = (c = 3 + 6));
which is also equivalent to:
c = 3 + 6;
b = c;
a = b;
Program Structure: Executable
◻ Side Effect:
■ An assignment statement does not just assigns, it also has the side
effect of returning the value of its right-hand side expression
■ Hence a = 12; has the side effect of returning the value of 12, besides
assigning 12 to a
■ Usually we don’t make use of its side effect, but sometimes we do, eg:
z = a = 12; // or z = (a = 12);
■ The above makes use of the side effect of the assignment statement a
= 12; (which gives 12) and assigns it to z
■ Side effects have their use, but avoid convoluted codes:
a = 5 + (b = 10); // assign 10 to b, and 15 to a
■ Side effects also apply to expressions involving other operators (eg:
logical operators).
Input/Output
Input/output statements:
age Address of variable
printf ( format string, print list ); ‘age’ varies each
printf ( format string );
20 time a program is
run.
scanf( format string, input list );
One version: “age” refers to value in the variable age.
int age; “&age” refers to (address of) the memory cell
double cap; // cumulative average point
where the value of age is stored.
printf("What is your age? ");
scanf("%d", &age);
printf("What is your CAP? ");
scanf("%lf", &cap);
printf("You are %d years old, and your CAP is %lf\n", age, cap);

Another version:
int age;
double cap; // cumulative average point
printf("What are your age and CAP? ");
scanf("%d %lf", &age, &cap);
printf("You are %d years old, and your CAP is %lf\n", age, cap);
Escape Sequence
Escape Sequence Effect
\a Beep sound
\b Backspace
\f Formfeed (for printing)
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash
\” “ sign
\o Octal decimal
\x Hexadecimal
\O NULL
The scanf function

Read data from the standard input device (usually keyboard)


and store it in a variable.
General format:
scanf(“Format string”, &variable);
Notice ampersand (&) operator :
C address of operator
it passes the address of the variable instead of the variable itself
tells the scanf() where to find the variable to store the new value
The scanf function cont…
Example :
int age;
printf(“Enter your age: “);
scanf(“%d”, &age);

Common Conversion Identifier used in printf and scanf


functions.
printf scanf
int %d %d
float %f %f
double %lf %lf
char %c %c
string %s %s
The scanf function cont…
If you want the user to enter more than one value, you
serialise the inputs.
Example:
float height, weight;

printf(“Please enter your height and weight:”);


scanf(“%f%f”, &height, &weight);
Few notes on C program cont…

Reserved Words
Keywords that identify language entities such as statements, data
types, language attributes, etc.
Have special meaning to the compiler, cannot be used as identifiers
(variable, function name) in our program.
Should be typed in lowercase.
Example: const, double, int, main, void,printf, while, for, else (etc..)
Few notes on C program cont…

Punctuators (separators)
Symbols used to separate different parts of the C program.
These punctuators include:
[ ] ( ) { } , ; “: * #
Usage example:
int main void()
{
int num = 10;
printf(“%d”, num);
return 0;
}
Few notes on C program cont…

Operators
Tokens that result in some kind of computation or action when
applied to variables or other elements in an expression.
Example of operators:
*+=-/
Usage example:
result = total1 + total2;
Input/Output
%d and %lf are examples of format specifiers; they are placeholders for values to
be displayed or read
Placeholder Variable Type Function Use
%c char printf / scanf
%d int printf / scanf
%f float or double printf
%f float scanf
%lf double scanf
%e float or double printf (for scientific notation)
■ Examples of format specifiers used in printf():
■ %5d: to display an integer in a width of 5, right justified
■ %8.3f: to display a real number (float or double) in a width of 8, with 3
decimal places, right justified
■ Note: For scanf(), just use the format specifier without indicating width, decimal
places, etc.
Input/Output
\n is an example of escape sequence
Escape sequences are used in printf() function for certain special effects or to
display certain characters properly
These are the more commonly used escape sequences:

Escape Meaning Result


sequence
\n New line Subsequent output will appear on the next line
\t Horizontal tab Move to the next tab position on the current line
\" Double quote Display a double quote "
%% Percent Display a percent character %
Operators
Arithmetic operations
Binary Operators: +, –, *, /, % (modulo or remainder)
Left Associative (from left to right)
◻ 46 / 15 / 2 3/2 1
◻ 19 % 7 % 3 5%3 2
Unary operators: +, –
Right Associative
◻ x = – 23 p = +4 * 10
Execution from left to right, respecting parentheses rule, and then precedence
rule, and then associative rule (next page)
addition, subtraction are lower in precedence than multiplication, division, and
remainder
Truncated result if result can’t be stored (the page after next)
int n; n = 9 * 0.5; results in 4 being stored in n.
Operators
Arithmetic operators: Associativity & Precedence
Operator Name Number of Position Associativity Precedence
operands
( Parentheses Unary Prefix Left to right 1
) Parentheses Unary Postfix Left to right 1
+ Positive sign Unary Prefix Right to left 2
- Negative sign Unary Prefix Right to left 2
++ Post-increment Unary Postfix Left to right 2
-- Post-decrement Unary Postfix Left to right 2
++ Pre-increment Unary Prefix Right to left 2
-- Pre-decrement Unary Prefix Right to left 2
*, /, % Multiplication, division, Binary Infix Left to right 3
remainder
+, - Addition, subtraction Binary Infix Left to right 4
=, +=, -=, *=, Assignment Binary Infix Right to left 5
/=, %=
Operators
Mixed-Type Arithmetic Operations
int m = 10/4; means
float p = 10/4; means
int n = 10/4.0; means
float q = 10/4.0; means
int r = -10/4.0; means
■ Type Casting
◻ Use a cast operator to change the type of an expression
■ syntax: (type) expression
int aa = 6; float ff = 15.8;
float pp = (float) aa / 4; means
int nn = (int) ff / aa; means
float qq = (float) (aa / 4); means
Common Programming Errors

Debugging Process removing errors from a


program
Three (3) kinds of errors :
Syntax Error
a violation of the C grammar rules, detected during
program translation (compilation).
statement cannot be translated and program cannot be
executed
Common Programming Errors cont…

Run-time errors
An attempt to perform an invalid operation, detected
during program execution.
Occurs when the program directs the computer to
perform an illegal operation, such as dividing a number by
zero.
The computer will stop executing the program, and
displays a diagnostic message indicates the line where the
error was detected
Common Programming Errors cont…

Logic Error/Design Error


An error caused by following an incorrect algorithm
Very difficult to detect - it does not cause run-time
error and does not display message errors.
The only sign of logic error – incorrect program output
Can be detected by testing the program thoroughly,
comparing its output to calculated results
To prevent – carefully desk checking the algorithm and
written program before you actually type it

You might also like