Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Programming Fundamentals

The document provides an introduction to programming fundamentals, focusing on computer science concepts such as computation, algorithms, and programming languages, particularly C. It outlines objectives for learning problem-solving techniques, program design, and the use of the C programming language. Additionally, it covers topics like computer organization, data types, and the structure of a simple C program.

Uploaded by

hamdaalee0440
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming Fundamentals

The document provides an introduction to programming fundamentals, focusing on computer science concepts such as computation, algorithms, and programming languages, particularly C. It outlines objectives for learning problem-solving techniques, program design, and the use of the C programming language. Additionally, it covers topics like computer organization, data types, and the structure of a simple C program.

Uploaded by

hamdaalee0440
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 169

Programming

Fundamentals
Introduction
What is Computer Science?

✦ Computation
✦ Algorithms
✦ Computer Languages

Explorations in Computing
© 2012 John S. Conery
Objectives

✦ To learn fundamental problem solving techniques

✦ To learn how to design a program

✦ To learn to use the C programming language


Computation
✦ A computation is a sequence of well-defined operations that
lead from an initial starting point to a desired final outcome.
❖ note this definition does not include the word “computer”
❖ a computation is a process that can be carried out by a person or a machine
❖ the same computation might be carried out using any one of a number of different
technologies
What is Computer Science?

✦ Computer science is the study of computation


❖ investigating problems that can
be solved computationally
❖ programming languages used
to describe computations
❖ machines that carry out
computations
❖ theoretical limits of computation
(what is or is not computable)
❖ computational solutions to problems
in math, science, medicine,
business, education, journalism, ...
What Is a Computer?
 Computer
– Performs computations and makes logical decisions
– Millions / billions times faster than human beings
 Computer programs
– Sets of instructions by which a computer processes data
 Hardware
– Physical devices of computer system
 Software
– Programs that run on computers

6
Computer Organization
 Six logical units of computer system
– Input unit
 Mouse, keyboard
– Output unit
 Printer, monitor, audio speakers
– Memory unit
 save input and processed information
– Arithmetic and logic unit (ALU)
 Performs calculations
– Central processing unit (CPU)
 Supervises operation of other devices
– Secondary storage unit
 Hard drives, floppy drives
7
Evolution of Operating Systems
 Batch processing
– One job (task) at a time
– Operating systems developed
 Programs to make computers more convenient to use
 Switch jobs easier

 Multiprogramming
– “Simultaneous” jobs
– Timesharing operating systems

8
Algorithms
✦ The sequence of steps carried out during a computation are
defined by an algorithm
❖ an algorithm can be thought of as a “prescription”
❖ “follow these steps and you will solve your problem”

✦ An algorithm includes a complete description of


❖ the set of inputs, or starting conditions
‣ a full specification of the problem to be solved
❖ the set of outputs
‣ descriptions of valid solutions to the problem
❖ a sequence of operations that will eventually produce the output
‣ steps must be simple and precise
FLOW CHART
• The algorithm can also be written as a FLOW CHART
• The FLOW CHART is a graphic organiser (a picture that
helps organize your thoughts)
• It uses a collection of basic symbols that are used to
organize your algorithm
• These symbols are connected by arrows that show how the
algorithm “flows”
FLOW CHART SYMBOLS

TERMINAL – the beginning or ending of a


program
INPUT/OUTPUT – where the user of the program is
asked for information (INPUT) or where the program
displays a result (OUTPUT)
PROCESSING – shows any
mathematical operation

CALL – shows any other pieces of the


program that are called upon

DECISION – represents any action where the


computer is making a decision
Programming Languages
 Computers can not use human languages, and
programming in the binary language of
computers is a very difficult, tedious process
 Therefore, most programs are written using a
programming language and are converted to the
binary language used by the computer
 Three major categories of prog languages:
 Machine Language
 Assembly Language
 High level Language
Machine Language
• The representation of a computer program which is actually read
and understood by the computer.
– A program in machine code consists of a sequence of machine instructions.
• Instructions:
– Machine instructions are in binary code
– Instructions specify operations and memory cells involved in the operation
Example:

Operation Address

0010 0000 0000 0100

0100 0000 0000 0101

0011 0000 0000 0110


Assembly Language
• A symbolic representation of the machine language of a specific processor.
• Is converted to machine code by an assembler.
• Usually, each line of assembly code produces one machine instruction
(One-to-one correspondence).
• Programming in assembly language is slow and error-prone but is more
efficient in terms of hardware performance.
• Mnemonic representation of the instructions and data
• Example:
Load Price
Add Tax
Store Cost
High Level Languages

 English-like
and easy to learn and program
 Common mathematical notation
– Total Cost = Price + Tax;
– area = 5 * 5 * 3.1415;
 Java, C, C++, FORTRAN, VISUAL BASIC, PASCAL
Binary Number System
 Decimal
– Base 10, ten digits (0-9)
– The position (place) values are integral powers of 10: 10 0(ones),
101(tens), 102(hundreds), 103(thousands)…
– n decimal digits - 10n unique values
 Binary
– Base 2, two digits (0-1)
– The position (place) values are integral powers of 2: 2 0(1), 21(2),
22(4), 23(8), 24(16), 25(32), 26(64)…
– n binary digits - 2n unique values
Big Picture

Processor works with finite-sized data


All data implemented as a sequence of bits
 Bit = 0 or 1
 Represents the level of an electrical charge

Byte = 8 bits

Word = largest data size handled by processor


 32 bits on most older computers
 64 bits on most new computers

17
Numerical Data Types
Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308
C/C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

address
float double long double

pointer reference
C++ Primitive Data Types

Primitive types

integral floating

char short int long bool float double long double

unsigned
Premitive Data Types in C/C++

Integral Types
 represent whole numbers and their negatives
 declared as int, short, or long
Character Types
 represent single characters
 declared as char
 Stored by ASCII values
Boolean Type
• declared as bool
• has only 2 values true/false
• will not print out directly
Floating Types
 represent real numbers with a decimal point
 declared as float, or double
 Scientific notation where e (or E) stand for “times 10 to the ” (.55-e6)
Data types in C
Only really four basic types:
 char
 int (short, long, long long, unsigned)
 float
 double

Size of these types on Type Size (bytes)


CLEAR machines: char 1
int 4
short 2
Sizes of these types long 8
vary from one machine long long 8
to another! float 4
double 8

22
Characters (char)

Roman alphabet, punctuation, digits, and other symbols:


 Encoded within one byte (256 possible symbols)
 ASCII encoding (man ascii for details)

In C:

char a_char = ’a’;


char newline_char = ’\n’;
char tab_char = ’\t’;
char backslash_char = ’\\’;

23
ASCII
Special
control
character From “man ascii”:
s
| 0 NUL| 1 SOH| 2 STX| 3 ETX| 4 EOT| 5 ENQ| 6 ACK| 7 BEL|
| 8 BS | 9 HT | 10 NL | 11 VT | 12 NP | 13 CR | 14 SO | 15 SI |
| 16 DLE| 17 DC1| 18 DC2| 19 DC3| 20 DC4| 21 NAK| 22 SYN| 23 ETB|
| 24 CAN| 25 EM | 26 SUB| 27 ESC| 28 FS | 29 GS | 30 RS | 31 US |
| 32 SP | 33 ! | 34 " | 35 # | 36 $ | 37 % | 38 & | 39 ' |
| 40 ( | 41 ) | 42 * | 43 + | 44 , | 45 - | 46 . | 47 / |
| 48 0 | 49 1 | 50 2 | 51 3 | 52 4 | 53 5 | 54 6 | 55 7 |
| 56 8 | 57 9 | 58 : | 59 ; | 60 < | 61 = | 62 > | 63 ? |
| 64 @ | 65 A | 66 B | 67 C | 68 D | 69 E | 70 F | 71 G |
| 72 H | 73 I | 74 J | 75 K | 76 L | 77 M | 78 N | 79 O |
| 80 P | 81 Q | 82 R | 83 S | 84 T | 85 U | 86 V | 87 W |
| 88 X | 89 Y | 90 Z | 91 [ | 92 \ | 93 ] | 94 ^ | 95 _ |
| 96 ` | 97 a | 98 b | 99 c |100 d |101 e |102 f |103 g |
|104 h |105 i |106 j |107 k |108 l |109 m |110 n |111 o |
|112 p |113 q |114 r |115 s |116 t |117 u |118 v |119 w |
|120 x |121 y |122 z |123 { |124 | |125 } |126 ~ |127 DEL|
Your First Program
#include<stdio.h>
#include<conio.h>

int main()
{
printf(“Hello World : My First C language program”);
getch();
return 0;
}
Preprocessor Directives
 The first two lines that begin the program are preprocessor
directives.
e.g., #include <stdio.h>
#include<conio.h>
• It isn’t a program statement
• It isn’t a part of a function body
• It does not end with a semicolon
Program statement vs preprocessor directive
 Program statements are instructions to the computer to do
something, such as adding two numbers or printing a
sentence.
 A preprocessor directive, on the other hand, is an
instruction to the compiler.
 A part of the compiler called the preprocessor deals with
these directives before it begins the real compilation
process.
Program statement vs preprocessor directive
 The preprocessor directive #include tells the
compiler to insert another file into your source
file.
 The type file usually included by #include is
called a header file.
Header Files
 Thepreprocessor directive #include tells the
compiler to add the file stdio to the source file
before compiling.

Why do this?
Header Files
stdio.h is an example of a header file.
It’s concerned with basic input/output operations,
and contains declarations that are needed by the
printf function.
Without these declarations, the compiler won’t
recognize printf
Always Start with main()
 When you run a C\C++ program, the first
statement executed will be at the beginning of a
function called main().
 The program may consist of many functions, but
on startup, control always goes to main().
 If there is no function called main() in your
program, an error will be reported when you run
the program.
Functions
 The parentheses following the word main are the
distinguishing feature of a function.
 Without parentheses compiler would think that
main refers to some other program element.
 The word int preceding the function name
indicates that this particular function has a return
value of type int.
Braces and the Function Body
 The body of a function is surrounded by braces (sometimes
called curly brackets).
 Every function must use this pair of braces around the
function body.
 In this example there are only three statements in the
function body:
– the line starting with printf, the line starting with getch and the line
starting with return.
 However, a function body can consist of many statements.
Program Statements
 There are three statements in the FIRST program: the line
– printf(“Hello World: My first C++ program”);
– getch();
– and the return statement return 0;
printf
String Constants
 The phrase in quotation marks, “Hello World: My first C
program”, is an example of a string constant.
 Its value is set when the program is written, and it retains
this value throughout the program’s existence.
Program Statements
 The first statement tells the computer to display the quoted
phrase.
 A semicolon signals the end of the statement.
 If you leave out the semicolon, the compiler will signal an
error.
Program Statements
 getch() apart from holding the screen or waiting for a
character to be entered to exit the output screen , it also
print the input given by the user.
 The last statement in the function body is return 0;
 This tells main() to return the value 0 to whoever called it,
in this case the operating system or compiler. The value 0
indicates that the program had terminated successfully.
Whitespace
 Compiler ignores whitespace almost completely.
 Whitespace is defined as spaces, tabs and newlines.
 These characters are invisible to the compiler.
 You can put several statements on one line,
separated by any number of spaces or tabs, or you
can run a statement over two or more lines.
Your First Program
#include<stdio.h>
#include<conio.h>

int main()
{
printf(“Hello World : My First C language program”);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main()
{
printf(“Hello World : \
My First C language program”);
getch();
return 0;
}
Exceptions to the rule
 The first line of the program, starting with #include, is a
preprocessor directive, which must be written on one line.
 Also, string constants, such as “Every age has a language
of its own”, cannot be broken into separate lines.
 If you need a long string constant, you can insert a
backslash(\) at the line break or divide the string into two
separate strings, each surrounded by quotes.
#include<stdio.h>
#include<conio.h>

int main()
Backslash
{
printf(“Hello World : \
My First C language program”);
getch();
return 0;
}
Comments
 They help the person writing a program, and anyone else
who must read the source file, understand what’s going
on.
 The compiler ignores comments
Comment Syntax
Comments start with a double slash symbol (//) and terminate
at the end of the line.

#include<stdio.h>
#include<conio.h>

int main()
{
printf(“Hello World : My First C language program”); //printing a string on the monitor
getch(); //pause the application
return 0; // return 0 to operating system, that signals the program terminated
normally
}
Alternative Comment Syntax

/* this
is a
Potentially
very long
multiline
comment
*/
 Ifyou attempt to use the // style comment in this case, the
closing brace won’t be visible to
the compiler-- since a // style comment runs to the end of
the line—and the code won’t compile correctly.
C/C++ Reserved words
bool const double for
return
break continue else if struct
case default enum int switch
char delete false long typedef
class do float new while

48
What is an Identifier?
• An identifier is the name to denote labels, types, variables,
constants or functions, in a C/C++ program.
• C/C++ is a case-sensitive language.
– Work is not work

• Identifiers should be descriptive


– Using meaningful identifiers is a good programming practice
Identifier
• Identifiers must be unique
• Identifiers cannot be reserved words (keywords)
– double main return
• Identifier must start with a letter or underscore, and be followed by zero or
more letters (A-Z, a-z), digits (0-9), or underscores
• VALID
age_of_dog _taxRateY2K
PrintHeading ageOfHorse
• NOT VALID
age# 2000TaxRate Age-Of-Dog main
Variable Declaration/Definition
• All variables must declared/defined before use.
– At the top of the program
– Just before use.
• Commas are used to separate identifiers of the same type.
int count, age;
• Variables can be initialized to a starting value when they
are declared
int count = 0;
int age, count = 0;
bool Data Type
• Type bool is a built-in type consisting of just 2 values, the
constants true and false
• We can declare variables of type bool
bool hasFever; // true if has high temperature
bool isSenior; // true if age is at least 55
• The value 0 represents false
• ANY non-zero value represents true
Boolean Expression
• Expression that yields bool result
• Include:
6 Relational Operators
< <= > >= == !=
3 Logical Operators
! && ||
Relational Operators
are used in Boolean expressions of form:
ExpressionA Operator ExpressionB
temperature > humidity
B * B - 4.0 * A * C > 0.0
abs (number) == 35
initial != ‘Q’
• Notes:
o == (equivalency) is NOT = (assignment)
o characters are compared alphabetically. However, lowercase letters are higher ASCII value.
o An integer variable can be assigned the result of a logical expression
o You cannot string inequalities together:
Bad Code: 4<x<6 Good Code: (x > 4) &&(x < 6)
Relational Operators
int x, y ;
x = 4;
y = 6;
EXPRESSION VALUE
x<y true
x+2<y false
x != y true
x + 3 >= y true
y == x false
y == x+2 true
y=x+3 7
y=x<3 0
y=x>3 1
Logical Operators
are used in boolean expressions of form:
ExpressionA Operator ExpressionB
A || B (true if either A or B or both are true. It is false otherwise)
A && B (true if both A and B are true. It is false otherwise)
or
Operator Expression
!A (true if A is false. It is false if A is true)

Notes:
Highest precedence for NOT, AND and OR are low precedence.
Associate left to right with low precedence. Use parenthesis to override priority or for clarification
– x && y || z will evaluate “x && y ” first
– x && (y || z) will evaluate “y || z” first
Logical Operators
int age ;
bool isSenior, hasFever ;
float temperature ;
age = 20;
temperature = 102.0 ;
isSenior = (age >= 55) ; // isSenior is false
hasFever = (temperature > 98.6) ; // hasFever is true

EXPRESSION VALUE
isSenior && hasFever false
isSenior || hasFever true
!isSenior true
!hasFever false
Precedence Chart
• ++, --, !, - (unary minus), + (unary plus) Highest

• *, /, %
• + (addition), - (subtraction)
• <<, >>
• <, <=, >, >=
• ==, !=
• &&
• ||
• = Lowest
Boolean Expression (examples)
taxRate is over 25% and income is less than $20000

temperature is less than or equal to 75 or humidity is less than 70%

age is between 21 and 60

age is 21 or 22
Boolean Expression (examples)
(taxRate > .25) && (income < 20000)

(temperature <= 75) || (humidity < .70)

(age >= 21) && (age <= 60)

(age == 21) || (age == 22)


Simple if Statement Syntax
if (Boolean Expression)
Statement

if (Bool-Expr)
{
Statement_1

Statement_n
}
Use of blocks
• Denoted by { .. }
• Recommended in controlled structures (if and loop)
• Also called compound statement.

if (Bool-Expression )
{ “if clause”
}
else
{ “else clause”
}
Multiple Selection
• So far, we have only seen binary selection.

if ( age >= 18 ){
if ( age >= 18 ){ printf(“Vote!\n”) ;
printf(“Vote!\n”) ; }
} else{
printf(“Maybe next time!\n”) ;
}
Multiple Selection (con’t)
• Sometimes it is necessary to branch in more than two
directions.
• We do this via multiple selection.
• The multiple selection mechanism in C is the switch statement.
Multiple Selection with if
if (day == 0 ) { (continued)
printf (“Sunday”) ;
} if (day == 4) {
printf (“Thursday”) ;
if (day == 1 ) {
}
printf (“Monday”) ; if (day == 5) {
} printf (“Friday”) ;
if (day == 2) { }
printf (“Tuesday”) ; if (day == 6) {
} printf (“Saturday”) ;
}
if (day == 3) {
if ((day < 0) || (day > 6)) {
printf (“Wednesday”) ; printf(“Error - invalid day.\n”) ;
} }
Multiple Selection with if-else
if (day == 0 ) {
printf (“Sunday”) ;
} else if (day == 1 ) {
printf (“Monday”) ;
} else if (day == 2) { This if-else structure is more
printf (“Tuesday”) ;
} else if (day == 3) {
efficient than the corresponding if
printf (“Wednesday”) ; structure. Why?
} else if (day == 4) {
printf (“Thursday”) ;
} else if (day == 5) {
printf (“Friday”) ;
} else if (day = 6) {
printf (“Saturday”) ;
} else {
printf (“Error - invalid day.\n”) ;
}
The switch Multiple-Selection Structure
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
switch Statement: Example 1
• If you have a 95, what grade will you get?

switch(int(score)/10){
case 10:
case 9: printf("Grade = A\n“); break;
case 8: printf("Grade = B\n“); break;
case 7: printf("Grade = C\n“); break;
case 6: printf("Grade = D\n“); break;
default: printf("Grade = F\n“);
}
switch Statement: Example 2
is equivalent to:
if (score >= 90)
printf(“%s”,"Grade = A\n“);
else if (score >= 80)
printf (“%s”,”Grade = B\n“);
else if (score >= 70)
printf (“%s”,"Grade = C\n“);
else if (score >= 60)
printf (“%s”,"Grade = D\n“);
else // score < 59
printf (“%s”, "Grade = F\n“);
switch Statement Details
• The last statement of each case in the switch should
almost always be a break.
• The break causes program control to jump to the closing
brace of the switch structure.
• Without the break, the code flows into the next case. This
is almost never what you want.
• A switch statement will compile without a default case,
but always consider using one.
Creating Menus
• When you want to give your user a choice on what to do next,
you can display a set of choices (a menu). The user then enters
his or her choice. You must validate the choice to make sure it
is valid before you continue the program!
Sample Program
int choice;
choice = 0;
do
{
printf( “my menu\n\n” );
printf( “1 – edit\n” );
printf( “2 – delete\n” );
printf( “3 – quit\n” );
printf( “enter your choice: “ );
scanf( “%d”, &choice );
} while ( ( choice >= 1 ) && ( choice <= 3 ) );
Sample Program (cont’d)
switch( choice )
{
case 1: printf( “Do edit\n” );
break;
case 2: printf( “Do delete\n” );
break;
case 3: printf( “Done\n” );
break;
default: printf( “Invalid choice!\n” );
break;
}
#include <stdio.h>
void main ( ) case ‘C’ :
{ case ‘c’ :
char ch ; printf(”O.K”);
printf(“ \n Enter the grade of student: \n“) ; break;
ch = getch(); case ‘D’ :
switch (ch){ case ‘d’ :
case ‘A’ :
case ‘F’ :
case ‘a’ :
case ‘f’ :
printf(”Excellent”);
printf(”poor”);
break;
case ‘B’ : break;
case ‘b’ : default:
cout<<”Good”; printf(”invalid letter grade”);
break; }
}
#include <stdio.h>
void main()
{ int x,y;
printf("Enter 2 integer number: “);
scanf(&x,&y);
switch (x+y) {
case 7: printf("Too small, sorry!“);
break;
case 5: printf("Good job!\n“);
break;
case 4: printf("Nice Pick!\n“);
case 3: printf("Excellent!\n“);
break;
case 2: printf("Masterful!\n“);
break;
case 1: printf("Incredible!\n“);
break;
default: printf("Too large!\n“);
}
printf("\n\n“);
}
Good Programming Practices
• Include a default case to catch invalid data.
• Inform the user of the type of error that has occurred
(e.g., “Error - invalid day.”).
• If appropriate, display the invalid value.
• If appropriate, terminate program execution
switch ( day )
switch Example
{
case 0:
printf (“Sunday\n”) ;
break ;
case 1:
Is this structure
printf (“Monday\n”) ; more efficient
break ; case 5: than the
case 2: printf (“Friday\n”) ;
printf (“Tuesday\n”) ; break ;
equivalent nested
break ; case 6: if-else structure?
case 3: printf (“Saturday\n”) ;
printf (“Wednesday\n”) ; break ;
break ; default:
case 4: printf (“Error -- invalid day.\n”) ;
printf (“Thursday\n”) ; break ;
break ; }
Why Use a switch Statement?
• A nested if-else structure is just as efficient as a switch
statement.
• However, a switch statement may be easier to read.
• Also, it is easier to add new cases to a switch statement than to
a nested if-else structure.
Points to Remember
• The expression followed by each case label must be a
constant expression.
• No two case labels may have the same value.
• Two case labels may be associated with the same
statements.
• The default label is not required.
• There can be only one default label, and it is usually last.
Common Programming Errors
The following if statement is true for all values of x!

if( 0 <= x <= 4)


printf(“Condition is true\n” );

Instead,use
if( 0 <= x && x <= 4)

The following always prints the same thing:

if ( x = 10 )
printf( “ x is 10\n” );
The char Data Type
• The char data type holds a single character.
char ch;
• Example assignments:
char grade, symbol;
grade = ‘B’;
symbol = ‘$’;
• The char is held as a one-byte integer in memory. The ASCII
code is what is actually stored, so we can use them as
characters or integers, depending on our need.
The char Data Type (con’t)
• Use
scanf (“%c”, &ch) ;
to read a single character into the variable ch. (Note
that the variable does not have to be called “ch”.”)
• Use
printf(“%c”, ch) ;
to display the value of a character variable.
char Example
#include <stdio.h>
int main ( )
{
char ch ;

printf (“Enter a character: “) ;


scanf (“%c”, &ch) ;
printf (“The value of %c is %d.\n”, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.
The getchar ( ) Function
• The getchar( ) function is found in the stdio library.
• The getchar( ) function reads one character from stdin
(the standard input buffer) and returns that
character’s ASCII value.
• The value can be stored in either a character variable
or an integer variable.
getchar ( ) Example
#include <stdio.h>
int main ( )
{
char ch ; /* int ch would also work! */

printf (“Enter a character: “) ;


ch = getchar( ) ;
printf (“The value of %c is %d.\n”, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.
Problems with Reading Characters
• When getting characters, whether using scanf( ) or
getchar( ), realize that you are reading only one character.
• What will the user actually type? The character he/she
wants to enter, followed by pressing ENTER.
• So, the user is actually entering two characters, his/her
response and the newline character.
• Unless you handle this, the newline character will remain
in the stdin stream causing problems the next time you
want to read a character. Another call to scanf() or
getchar( ) will remove it.
Improved getchar( ) Example
#include <stdio.h>
int main ( )
{
char ch, newline ;

printf (“Enter a character: “) ;


ch = getchar( ) ;
newline = getchar( ) ; /* could also use scanf(“%c”, &newline) ; */
printf (“The value of %c is %d.\n”, ch, ch) ;
return 0 ;
}

If the user entered an A, the output would be:


The value of A is 65.
Additional Concerns with Garbage in stdin
• When we were reading integers using scanf( ), we didn’t
seem to have problems with the newline character, even
though the user was typing ENTER after the integer.
• That is because scanf( ) was looking for the next integer
and ignored the newline (whitespace).
• If we use scanf (“%d”, &num); to get an integer, the
newline is still stuck in the input stream.
• If the next item we want to get is a character, whether we
use scanf( ) or getchar( ), we will get the newline.
• We have to take this into account and remove it.
EOF Predefined Constant
• getchar( ) is usually used to get characters from a file until the
end of the file is reached.
• The value used to indicate the end of file varies from system to
system. It is system dependent.
• But, regardless of the system you are using, there is a #define
in the stdio library for a symbolic integer constant called EOF.
• EOF holds the value of the end-of-file marker for the system
that you are using.
getchar( ) Example Using EOF
#include <stdio.h>
int main ()
{
int grade, aCount, bCount, cCount, dCount, fCount ;
aCount = bCount = cCount = dCount = fCount = 0 ;
while ( (grade = getchar( ) ) != EOF ) {
switch ( grade ) {
case ‘A’: aCount++; break ;
case ‘B’: bCount++; break ;
case ‘C’ : cCount++; break ;
case ‘D’: dCount++; break ;
case ‘F’: fCount++; break ;
default : break ;
}
}
return 0 ;
}
Loop
• is a repetition control structure.
• causes a single statement or block of statements to be
executed repeatedly until a condition is met.
• There are 3 kinds of loop in C++:
– While loop
– Do-While loop
– For loop
While Loop
SYNTAX
while ( Expression )
{
… // loop body
}
• No semicolon after the boolean expression
• Loop body can be a single statement, a null statement, or a block.
While Loop Example
#include<conio.h>
#include<stdio.h>
Int main()
{
int count ;
count = 0; // initialize LCV
while (count < 5){ // test expression
printf("%d ",count);
count = count + 1; //count++;
}
printf("Done\n");
return 0;
}
Loop Tracing
int count ; count Expression Output
count = 0; // initialize LCV 0 true 0

while (count < 5){ // test 1 true 01


expression 2 true 012

printf("%d ",count); 3 true 0123


4 true 01234
count = count + 1;
5 false 0 1 2 3 4 Done
}
printf("Done\n");
Increment and Decrement Operators
• Denoted as ++ or --
• Mean increase or decrease by 1
• Pre increment/decrement: ++a, --a
– Increase/decrease by 1 before use.
• Post increment/decrement: a++, a--
– Increase/decrease by 1 after use.
• Pre and Post increment/decrement yield different results
when combining with another operation.
Pre and Post Increment and Decrement
int count ; count Expression Output
count = 0; 0 true 0
while (count < 5){ 1 true 01
printf("%d ",count); 2 true 012
count = count + 1; 3 true 0123
} 4 true 01234
printf("Done\n"); 5 false 0 1 2 3 4 Done
int count ; count Expression Output
count = 0; 0 true 1
while (count < 5){ 1 true 12
printf("%d ",++count);
} 2 true 123
printf("Done\n"); 3 true 1234
4 true 12345
5 false 1 2 3 4 5 Done
Do-While Loop
SYNTAX
do
{
… // loop body
} while ( Expression );
• Insured that the loop is executed at least once
• The LCV is initialized/updated before the end of the loop.
• Boolean expression is tested at the end of the loop.
• There is a semicolon after the boolean expression.
Do hile Loop Example
int ans;
do
{
printf(“Choose a number from 1 to 4: “); // repeated action
scanf(“%d”,&ans); // LCV is initialized or updated
} while (ans >= 1 && ans <= 4); // test expression
printf(“Done”);
Output Input ans Expression
Choose a number from 1 to 4: 2 2 true
Choose a number from 1 to 4: 3 3 true
Choose a number from 1 to 4: 1 1 true
Choose a number from 1 to 4: 5 5 false
Done
Loop-Controlled Types
Count-controlled: repeat a specified number of times.
Event-driven: some condition within the loop body changes and this
causes the repeating to stop.
Sentinel-controlled: using a specific value to end.
Sentinel: a value that cannot occur as valid data.
Ask-before-Continuing: ask users if they want to continue.
Flag-Controlled Loops: use a variable whose value is changed when an
event occurs (usually from false to true).
Count-Controlled Loop
• Has a loop control variable (LCV) as a counter.
• LCV must be
– Initialized before start of the loop
– Tested (boolean expression)
– Updated
Event-driven loop
double salary;
printf("Enter you salary: “);
Scanf(“%f”, salary);
int years = 0;
while (salary < 50000) {
salary = salary * 1.02;
years++;
}
printf(“You need %f years to get to 50K“,years);
Sentinel-Controlled
do
{
printf( “Enter salary, type -1 to exit”); // no one earns negative salary
Scanf(“%f”,&salary); // process income
} while (salary > 0);
Ask-before-Continuing
char ans = ‘y’; // LCV is initialized
while (ans == ‘Y’ || ans == ‘y’) // test expression
{
doSomething; // repeated action
printf(“Do you want to continue? ”);
scanf(“%c”, &ans); // LCV is updated
};
BREAK statement
allows to exit from any loop.

do
{
scanf(“%f”,&x);
if (x % 2 ==0)
break;
} while (x > 0); // exits when an even number is entered
CONTINUE Statement
allows you to skip the rest of the loop body and go back to the
beginning of the loop.

do
{
scanf(“%f”,&x);
if (x % 2 == 0)
continue;
printf(“%d\n”,x);
} while (x <100); //prints out all odd numbers entered less than 100
Program Style
• Indenting:
– Separate processes with blank lines
– Blank lines are also ignored and are used to increase readability.
– indent statements within statements (loop body)
• Comments:
– // tells the computer to ignore this line.
– for internal documentation. This is done for program clarity and to facilitate
program maintenance.
General rules for Comments
• Place a comment at the beginning of every file with the file
name, version number, a brief program description,
programmer’s name.
• Place a descriptive comment after each variable declared.
– Use a blank line before and after variable declarations
• Place a descriptive comment and a blank line before each
subtask.
Constants
• Syntax: const type identifier = value;
• Ex: const double TAX_RATE = 0.08;
• Convention: use upper case for constant ID.
Why use constants?
• Clarity: Tells the user the significance of the number. There
may be the number 0.08 elsewhere in the program, but you
know that it doesn’t stand for TAXRATE.
• Maintainability. Allows the program to be modified easily.
– Ex: Program tax compute has const double TAXRATE=0.0725. If
taxes rise to 8%, programmer only has to change the one line to
const double TAXRATE=0.08
• Safety: Cannot be altered during program execution
What is an Expression in C/C++?
• An expression is a valid arrangement of variables, constants,
and operators.
• In C++, each expression can be evaluated to compute a value of
a given type

• In C++, an expression can be:


– A variable or a constant (count, 100)
– An operation (a + b, a * 2)
– Function call (getRectangleArea(2, 4))
Assignment Operator
• An operator to give (assign) a value to a variable.
• Denote as ‘=‘
• Only variable can be on the left side.
• An expression is on the right side.
• Variables keep their assigned values until changed by another
assignment statement or by reading in a new value.
Assignment Operator Syntax
• Variable = Expression
– First, expression on right is evaluated.
– Then the resulting value is stored in the memory location of Variable
on left.

NOTE: An automatic type coercion occurs after evaluation but


before the value is stored if the types differ for Expression and
Variable
Assignment Operator Mechanism
• Example:
0
int count = 0;
int starting; 12345 (garbage)

starting = count + 5;
• Expression evaluation:
– Get value of count: 0
– Add 5 to it.
– Assign to starting 5
//********************************************************
// Program Convert Measurements: This program converts
// measurements in feet and inches into centimeters using
// the formula that 1 inch is equal to 2.54 centimeters.
//********************************************************
#include <condio.h>
#include <stdio.h>
//named constants
const double CENTIMETERS_PER_INCH = 2.54;
const int INCHES_PER_FOOT = 12;
int main ()
{
//declare variables
int feet, inches;
int totalInches;
double centimeter;
//Statements: Step 1 - Step 7
printf("Enter two integers, one for feet and "one for inches: “);
//Step 1
printf("For Feet: ");
scanf("%d",&feet);
printf("For inches: ");
scanf("%d", &inches);
//Step 2
printf("The Numbers you entered are %d ", feet);
printf("for feet, and %d for inches. ", inches);
//Step 3
totalInches = INCHES_PER_FOOT * feet + inches;
//Step 4
printf(“The total number of inches = %f“, totalInches,”\n);
//Step 5
centimeter = CENTIMETERS_PER_INCH * totalInches;
//Step 6
printf("\nThe total number of inches = %d", totalInches);
//Step 7
return 0;
}

Sample Run
Enter two integers, one for feet, one for inches: 15 7

The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98
Operators
Pre- and post-variations of ++ and –– operators
Abbreviated (compound) assignment expressions

• n –= 5; /* is equivalent to n = n – 5; */
• n *=5; /* is equivalent to n = n * 5; */
• n /= 5; /* is equivalent to n = n / 5; */
• n %= 5; /* is equivalent to n = n % 5; */
Logical Operators in C

Note that here, zero and non-zero operands are mentioned,


not zero and 1. In general,
- Any non-zero value can be used to represent the logical true
- Whereas only zero represents the logical false . The following are, therefore, all valid logical expressions
Conditional Operator in C
• The conditional operator has three expressions. It has the general form
expression1 ? expression2 : expression3
Here first, expression1 is evaluated; it is treated as a logical condition. If the result is non-zero,
then expression2 is evaluated and its value is the final result. Otherwise, expression3 is evaluated
and its value is the final result.
For example,
int m = 1, n = 2, min;
min = (m < n ? m : n); // min is assigned a value 1

explanation: as m is less than n , m < n expression evaluates to be true, therefore, min is


assigned the
value m , i.e., 1.
The same code can also be written using the if-else construct,
int m=1, n=2, min;
if(m<n)
min=m;
else
min=n;
Examples Using Arrays

• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
− If not enough initializers, rightmost elements become 0
− If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
− Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
− 5 initializers, therefore n is a 5 element array
Multiple-Subscripted Arrays
• Multiple subscripts - tables with rows, columns
− Like matrices: specify row, then column.
Column 0 Column 1 Column 2 Column 3
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript

Array name
Row subscript

1 2
• Initialize 3 4

int b[ 2 ][ 2 ] = { {1, 2}, {3, 4}};


1 0
− Initializers grouped by row in braces 3 4

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
FIGURE 11-3 Storing Strings

Computer Science: A Structured Programming Approach Using C 127


FIGURE 11-4 Storing Strings and Characters

Computer Science: A Structured Programming Approach Using C 128


FIGURE 11-5 Differences Between Strings and Character Arrays

Computer Science: A Structured Programming Approach Using C 129


FIGURE 11-6 Strings in Arrays

Computer Science: A Structured Programming Approach Using C 130


Note
A string literal is enclosed in double quotes.

Computer Science: A Structured Programming Approach Using C 131


FIGURE 11-7 Character Literals and String Literals

132
FIGURE 11-8 String Literal References

Computer Science: A Structured Programming Approach Using C 133


FIGURE 11-9 Defining Strings

134
Note
Memory for strings must be allocated before the
string can be used.

135
FIGURE 11-10 Initializing Strings

136
Changing String Variables (cont)
• Can change parts of a string variable
char str1[6] = “hello”;
str1[0] = ‘y’;
/* str1 is now “yello” */
str1[4] = ‘\0’;
/* str1 is now “yell” */
• Important to retain delimiter (replacing str1[5] in the original
string with something other than ‘\0’ makes a string that does
not end)
• Have to stay within limits of array
Memory Storage for a String

• The string is always ended with a null character ‘\0’.


• The characters after the null character are ignored.
• e.g., char str[20] = “Initial value”;

[0] [13]

I n i t i a l v a l u e \0 ? ? …

9-138
Input/Output of a String
• The placeholder %s is used to represent string arguments in printf
and scanf.
− printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a positive number in
the placeholder.
− printf(“%8s”, str);
• The string can be left-justified by placing a negative number in the
placeholder.
− Printf(“%-8s”, str);

9-139
Right and Left Justification of Strings
The “%8s” placeholder displays a string which is right-justified and in 8-
columns width.
If the actual string is longer than the width, the displayed field is expanded
with no padding.

9-140
Input/Output of a String
• The placeholder %s is used to represent string arguments in
printf and scanf.
− printf(“Topic: %s\n”, string_var);
• The string can be right-justified by placing a positive number in
the placeholder.
− printf(“%8s”, str);
• The string can be left-justified by placing a negative number in
the placeholder.
− Printf(“%-8s”, str);

9-141
Right and Left Justification of Strings
The “%8s” placeholder displays a string which is right-justified and in 8-
columns width.
If the actual string is longer than the width, the displayed field is expanded
with no padding.

9-142
An Example of Manipulating String with scanf
and printf

The dept is the initial memory address of the


string argument. Thus we don’t apply the &
operator on it.

9-143
Execution of scanf ("%s", dept);
• Whenever encountering a white space, the scanning stops and scanf places the null character
at the end of the string.
• e.g., if the user types “MATH 1234 TR 1800,” the string “MATH” along with ‘0’ is stored into dept.

9-144
String Library Functions

• The string can not be copied by the assignment operator ‘=’.


− e..g, “str = “Test String”” is not valid.
• C provides string manipulating functions in the “string.h”
library.

9-145
Some String Functions from String.h
Function Purpose Example
strcpy Makes a copy of a string strcpy(s1, “Hi”);
strcat Appends a string to the end of strcat(s1, “more”);
another string
strcmp Compare two strings alphabetically strcmp(s1, “Hu”);

strlen Returns the number of characters in strlen(“Hi”) returns 2.


a string
strtok Breaks a string into tokens by strtok(“Hi, Chao”, “ ,”);
delimiters.
9-146
Functions strcpy and strncpy
• Function strcpy copies the string in the second argument into
the first argument.
− e.g., strcpy(dest, “test string”);
− The null character is appended at the end automatically.
− If source string is longer than the destination string, the overflow
characters may occupy the memory space used by other variables.
• Function strncpy copies the string by specifying the number of
characters to copy.
− You have to place the null character manually.
− e.g., strncpy(dest, “test string”, 6); dest[6] = ‘\0’;
− If source string is longer than the destination string, the overflow
characters are discarded automatically.
9-147
Extracting Substring of a String (1/2)
• We can use strncpy to extract substring of one string.
– e.g., strncpy(result, s1, 9);

9-148
Extracting Substring of a String (2/2)
• e.g., strncpy(result, &s1[5], 2);

9-149
Functions strcat and strlen
• Functions strcat and strncat concatenate the fist
string argument with the second string argument.
− strcat(dest, “more..”);
− strncat(dest, “more..”, 3);
• Function strlen is often used to check the length of a
string (i.e., the number of characters before the fist null
character).
− e.g., dest[6] = “Hello”;
strncat(dest, “more”, 5-strlen(dest));
dest[5] = ‘\0’;
9-150
Distinction Between Characters and Strings
• The representation of a char (e.g., ‘Q’) and a string (e.g., “Q”) is
essentially different.
− A string is an array of characters ended with the null character.

Q Q \0

Character ‘Q’ String “Q”

9-151
String Comparison (1/2)
• Suppose there are two strings, str1 and str2.
− The condition str1 < str2 compare the initial memory address
of str1 and of str2.
• The comparison between two strings is done by comparing each
corresponding character in them.
− The characters are comapared against the ASCII table.
− “thrill” < “throw” since ‘i’ < ‘o’;
− “joy” < joyous“;
• The standard string comparison uses the strcmp and strncmp
functions.
9-152
String Comparison (2/2)

Relationship Returned Value Example


str1 < str2 Negative “Hello”< “Hi”
str1 = str2 0 “Hi” = “Hi”
str1 > str2 Positive “Hi” > “Hello”

• e.g., we can check if two strings are the same by


if(strcmp(str1, str2) != 0)
printf(“The two strings are different!”);

9-153
Input/Output of Characters and Strings
• The stdio library provides getchar function which
gets the next character from the standard input.
− “ch = getchar();” is the same as “scanf(“%c”,&ch);”
− Similar functions are putchar, gets, puts.

9-154
Character Analysis and Conversion
• The <ctype.h> library defines facilities for character analysis and
conversion.

Functions Description
isalpha Check if the argument is a letter

isdigit Check if the argument is one of the ten digits

isspace Check if argument is a space, newline or tab.

tolower Converts the lowercase letters in the argument to


upper case letters. 9-155
Conversions Between Strings Numbers
• The <stdlib.h> defines some basic functions for
conversion from strings to numbers:
− atoi(“123”) converts a string to an integer.
− atol(“123”) converts a string to a long integer.
− atof(“12.3”) converts a string to a float.
• However, there is no functions such as itoa, itof, …etc,
− because there is a function called sprintf which can converts
many formats to a string.

9-156
Static Data Allocation
Auto
matic
h er e array
u po n s allo
entry cated
to blo
0xFFFFFFFF ck.
stack
(dynamically allocated)
SP

heap
address space (dynamically allocated)

static data

program code
PC
0x00000000 (text)

Arrays in C
157
Data Storage in Memory
• Variables may be automatic or static

• Automatic variables may only be declared within functions and


compound statements (blocks)
• Storage allocated when function or block is entered
• Storage is released when function returns or block exits

• Parameters and result are (somewhat) like automatic variables


• Storage is allocated and initialized by caller of function
• Storage is released after function returns to caller.

158
Scope
• Identifiers declared within a function or
compound statement are visible only from the
point of declaration to the end of that function or
compound statement.
• Like Java

159
Example
int fcn (float a, int b) { i is visible from this point
int i; to end of fcn
g is visible from this point
double g; to end of fcn

for (i = 0; i < b; i++) { h is only visible from this


double h = i*g; point to end of loop!
loop body – may access a, b, i, g, h
} // for(i…)

fcn body – may access a, b, i, g


} // int fcn( … )
160
Idiosyncrasies

• In traditional C & Visual Studio


• All variables must be declared at beginning of function or compound
statement (i.e., before first statement); visible from that point on
• In gcc
• Variables may be declared anywhere in function or compound
statement; visible from that point on
• In C99 & C++
• Loop variables may be declared in for statement; visible only to end
of loop body, but not beyond

161
Static Data – Very different
• Static variables may be declared within or outside of functions
• Storage allocated when program is initialized
• Storage is released when program exits

• Static variables outside of functions may be visible to linker

• Compiler sets aside storage for all static variables at compiler or link
time
• Values retained across function calls

• Initialization must evaluate to compile-time constant

162
Static Variable Examples
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program

int fcn (float a, int b) {


// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

163
Static Variable Examples (continued)
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
De
cla
f rati
int fcn (float a, int b) { u nct o n o
st ion uts
// nothing inside of {} is visible to linker at :– a ide a
vis
ic lwa ny
int i = b; //automatic
ible s to y s st
r ag atic
double g; //automatic to l e c
ink lass:
static double h; //static, not visible to er –n
ot
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

CS-2303, C-Term 2010


Scope Rules and Storage Types 164
is
Static Variable Examples (continued) d ef au lt
o t
n :– n
tio s :–
c la s
f un tic c
e r
int j; //static, visible to linker &ideallmafuncts a g
r n ke
n s to to
I au
static float f; // not visible to linker, visible tos
c o li
// to all functions in this programt i et
t a ibl
s vis
int fcn (float a, int b) {
// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

CS-2303, C-Term 2010


Scope Rules and Storage Types 165
Static Variable Examples (continued)
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program

int fcn (float a, int b) {


// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
// linker; value retained from call to call
No
Vtael: v
body – may access j, f, a, b, i, g, h fro ueaoluf e
acmr o hoif
osns e s ha i
reccall lsso ret
} // int fcn( … ) ursto retaain
ionnex ineed
s t d
CS-2303, C-Term 2010
Scope Rules and Storage Types 166
Extern Variables
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
extern float p; // static, defined in another program
ex
te
r
int fcn (float a, int b) { stat n sto
r
// nothing inside of {} is visible to linkerano ic var age c
the iabl lass
int i = b; //automatic rC ed :– a
p ro e f
double g; //automatic gra ined i
static double h; //static, not visible to m n
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h , p

} // int fcn( … )
CS-2303, C-Term 2010
Scope Rules and Storage Types 167
Extern Variables (continued)

• Examples:–
• stdin, stdout, stderr are extern variables that point to standard
input, output, and error streams.

• extern variables:–
• Frequently occur in .h files.
• Each must be actually declared outside any function in exactly
one .c file

CS-2303, C-Term 2010


Scope Rules and Storage Types 168
Lifetime
The and
heap and theStorage
stack Management
• The heap and the stack are closely linked.

You might also like