0% found this document useful (0 votes)
34 views43 pages

What Is Computer Science?

The document defines computer science as the systematic study of algorithmic processes that describe and transform information. It discusses that computer science is about how we use tools like computers, not the tools themselves. It then provides definitions and explanations of key concepts in computer science like algorithms, programming, the program development process, representations of algorithms using flowcharts and pseudocode, and basic constructs like sequence, decision, and iteration.
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)
34 views43 pages

What Is Computer Science?

The document defines computer science as the systematic study of algorithmic processes that describe and transform information. It discusses that computer science is about how we use tools like computers, not the tools themselves. It then provides definitions and explanations of key concepts in computer science like algorithms, programming, the program development process, representations of algorithms using flowcharts and pseudocode, and basic constructs like sequence, decision, and iteration.
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/ 43

What is Computer Science?

The systematic study of algorithmic processes that describe and transform


information: their theory, analysis, design, efficiency, implementation, and
application. Computer Science is no more about computers than astronomy is
about telescopes, biology is about microscopes, or chemistry is about test tubes.
Science is not about tools. It is about how we use them, and what we find out
we can do. -Edsger Dijkstra

ELEMENTS OF PROGRAMMING

Programs are developed to instruct computers to do specific tasks, or solve


specific problems.

An algorithm is a finite set of instructions that if followed accomplishes a


particular task. Thus, programming is the activity of communicating algorithms to
computers.

PROGRAM DEVELOPMENT PROCESS

• Problem Solving Phase

Problem definition

The first part requires you to understand and define the problem at hand.
You should be able to identify the necessary inputs and the required
output. This task produces the requirements lists.

Algorithm development

The next step is to identify the logical sequence of steps needed

to solve the problem.


Desktop testing

Then verify the algorithm by following the steps and check to see if the
algorithm solves the problem.

• Implementation phase

Code the program

Encode the algorithm in a particular programming language.

Debug the program

Locate and correct all errors in the program.

Testing and validation

Check that the program produces the correct result.


ALGORITHMS

• An algorithm is a finite set of instructions that if followed accomplishes a


particular task.
• It is the most important step in creating a program.
• Knowing how to code in a specific programming language is secondary.
• An algorithm can be coded in any programming language.

PROPERTIES OF ALGORITHM

1. Finiteness

• The execution of an algorithm must be completed after a finite number


operations have been performed.

2. Absence of ambiguity

• Every step of the algorithm should have a unique interpretation.


• Every time an algorithm is presented for execution with the same input
data, the exact same results should be obtained.

3. Sequence definition

• The order in which the steps are carried out should be clearly specified.

4. Input and output definition

• The algorithm can have zero or more inputs and one or more outputs.

5. Effectiveness

• The algorithm can only give instructions that the computer can carry out.
• Cases wherein there is insufficient information to perform a task should not
exist.
6. Scope definition

• The problem or class of problems where the algorithm can be applied


should be defined.

REPRESENTATION OF ALGORITHMS

Flowchart

Pictorial representation of the logical steps it takes to solve a problem

Pseudocode

An English-like representation of the logical steps it takes to solve a


problem

FLOWCHARTS

• A two-dimensional graphical representation of an algorithm


• Flowcharts don't deal with details making it convenient for algorithm
design and presentation
• Allows the reader to follow the logic of the algorithm more easily than
would a linear description

FLOWCHARTING BASICS

Almost every program involves the steps of input, processing and output as in
the program:

1. Get number

2. Answer = number * 2

3. Print answer

Therefore, most flowcharts need some way to visually separate these three steps
INPUT OPERATIONS

Input operations are represented by the

parallelogram

A statement is written inside the parallelogram

PROCESSING STATEMENTS

• Arithmetic statements are examples of processing statements


• Processing statements are represented by rectangles, and statements are
written inside of them
OUTPUT STATEMENTS

• Output statements use the same symbol as input statements – the


parallelogram

FLOWLINES

• To show the correct sequence of statements, arrows (flowlines) are used


to connect steps.
• Whenever possible, most of a flowchart should read from top to bottom or
from left to right on a page.
TERMINAL

• To be complete, a flowchart should include two more elements: a


terminal or start/stop symbol at each end.
• Usually, a word like START or BEGIN is placed in the first terminal symbol
• A word like END or STOP is placed in the other.
• The standard terminal symbol is shaped like a racetrack or an oval.

FLOWCHART FOR THE PROGRAM THAT DOUBLES A NUMBER


PROGRAM THAT DOUBLES A NUMBER FOR SEVERAL INPUTS

Problem: The program never ends!

Solution:

The best way to end the program is to have predetermined value for NUMBER
that means “Stop the program!”

The programmer and the user could agree that the user will never need to know
the double of 0, so the user could enter a 0 when he or she wanted to stop.

The computer could then test any incoming value for NUMBER and, if it is a 0,
stop the program.
DECISIONS

• Decisions are represented in flowcharts by diamonds.


• The diamond usually contains a question, the answer to which is either a
yes or a no.
• All good computer questions have two mutually exclusive answers like yes
or no.

PROGRAM THAT DOUBLES A NUMBER FOR SEVERAL INPUTS: Final


THE CONNECTOR

A connector will be used when the physical constraints of page size stop the
programmer from completing the flowchart.

VARIABLES

• Programmers commonly refer to the locations in memory called NUMBER


and ANSWER as variables.
• Variables are memory locations, the contents of which can vary.
• Every computer programming language has its own set of rules for
naming variables.

FLOWCHART STRUCTURES

• Sequence
• Selection
• Iteration
SEQUENCE

SELECTION OR DECISION (IF ELSE)


ITERATION OR REPETITION

PSEUDOCODE

• Pseudocode (which means fake code, because its not really


programming code) specifies the steps required to accomplish the task.
• Pseudocode is a type of structured English that is used to specify an
algorithm.

PSEUDOCODE STATEMENTS: ASSIGNMENT

• Assignment is used to store a value


• This might involve either
o Simply storing a value
o Calculating the answer to an arithmetic problem and then storing
the result.
• The equals sign (=) is usually used to indicate assignment.
• Example: total = 0
o This example means: store zero in the variable named total.
PSEUDOCODE STATEMENTS: ARITHMETIC

Arithmetic Calculations

PSEUDOCODE STATEMENTS: INPUT

• Display a message asking the user for a value and store the value typed
by the user in a variable.
o Example: Input custName
• The example means display a message asking the user to input a
customers name and store the value typed by the user in the variable
called custName.

PSEUDOCODE STATEMENTS: DISPLAY

• Displays data on the computer screen (monitor).


• Examples :
o Display "Width = ", width
o Display "Hello World"
o Display grossIncome, taxPayable
• Values in quotation marks are displayed exactly as stated (minus the
quotation marks).
• The values held in variables are displayed rather than the variable name.
• For example, if the variable width held the value 72, the first Display
statement above would display the following:
o Width = 72

BASIC CONSTRUCTS

• SEQUENCE is a linear progression where one task is performed sequentially


after another.
• WHILE is a loop (repetition) with a simple conditional test at its beginning.
• IF-THEN-ELSE is a decision (selection) in which a choice is made between
two alternative courses of action.

SEQUENCE

• Sequential control is indicated by writing one action after another, each


action on a line by itself, and all actions aligned with the same indent.
• The actions are performed in the sequence (top to bottom) that they are
written.
• Example (non-computer):
o Brush teeth
o Wash face
o Comb hair
o Smile in mirror
• Example (computer):
o READ height of rectangle
o READ width of rectangle
o COMPUTE area as height times width
• Common Action Keywords
• Several keywords are often used to indicate common input, output, and
processing operations.
• Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE
Initialize: SET, INIT
Add one: INCREMENT
• For Compute and Initialize, it not necessary to use the action keywords.
IF-THEN-ELSE

Binary choice on a given Boolean condition is indicated by the use of four


keywords:

IF, THEN, ELSE, and ENDIF

The general form is:

IF condition THEN

sequence 1

ELSE

sequence 2

ENDIF

The ELSE keyword and "sequence 2" are optional.

If the condition is true, sequence 1 is performed, otherwise sequence 2 is


performed.

IF-THEN-ELSE EXAMPLES

Example 1:

IF HoursWorked > NormalMax THEN

Display overtime message

ELSE

Display regular time message

ENDIF
Example 2:

IF lineNumber > 50 THEN

Display “More than 50 lines"

ENDIF

Example 3:

IF (monthNumber >= 1) AND (monthNumber <= 12) THEN

Display “Valid month"

ELSE

Display “Invalid month"

Display "Month must be between 1 and 12"

ENDIF

IF-ELSE IF -ELSE

IF condition THEN

statements

ELSE IF condition THEN

statements

ELSE IF condition THEN

statements

ELSE

statements
ENDIF

Note: the ELSE part is optional. Use it where required by the logic.

IF-ELSE IF –ELSE EXAMPLE

IF mark >= 80 THEN

grade = “1"

comment = "Excellent"

ELSE IF mark >= 70 THEN

grade = “2.5"

ELSE IF mark >= 60 THEN

grade = “2.75"

ELSE IF mark >= 55 THEN

grade = “3"

ELSE

grade = “5"

comment = "Poor"

ENDIF
PSEUDOCODE STATEMENTS: BOOLEAN OPERATORS

Boolean Operators

Other Boolean Operators


WHILE

• The WHILE construct is used to specify a loop with a test at the top.
• The beginning and ending of the loop are indicated by two keywords
WHILE and ENDWHILE. The general form is:

WHILE condition

sequence

ENDWHILE

• The loop is entered only if the condition is true.


• The "sequence" is performed for each iteration.
• At the conclusion of each iteration, the condition is evaluated and the
loop continues as long as the condition is true.

WHILE: EXAMPLE

Example 1:

WHILE Population < Limit

Population = Population + Births - Deaths

ENDWHILE
Example 2:

count = 1

WHILE count <= 10

Display count

count = count + 1

ENDWHILE

Example 3:

Input itemPrice

WHILE itemPrice < 0

Display “Invalid Price”

Input itemPrice

ENDWHILE

Example 4:

Input quantitySold

WHILE quantitySold <= 0

Display “Invalid Quantity”

Input quantitySold

ENDWHILE
REPEAT-UNTIL

This loop is similar to the WHILE loop except that the test is performed at the
bottom of the loop instead of at the top.

Two keywords, REPEAT and UNTIL are used. The

general form is:

REPEAT

sequence

UNTIL condition

The "sequence" in this type of loop is always performed at least once, because
the test is performed after the sequence is executed.

At the conclusion of each iteration, the condition is evaluated, and the loop
repeats if the condition is false. The loop terminates when the condition
becomes true.

FOR LOOP

This loop is a specialized construct for iterating a specific number of times, often
called a "counting" loop.

Two keywords, FOR and ENDFOR are used. The

general form is:

FOR iteration bounds

sequence

ENDFOR

In cases where the loop constraints can be obviously inferred it is best to


describe the loop using problem domain vocabulary.
Example:

FOR each month of the year (good)

FOR month = 1 to 12 (ok)

FOR each employee in the list (good)

FOR empno = 1 to listsize (ok)

Example of a FOR loop:

FOR x = 1 to 10

xSquared = x * x

Display x, xSquared

ENDFOR

NESTED CONSTRUCTS

• The constructs can be embedded within each other, and this is made
clear by use of indenting.
• Nested constructs must be clearly indented from their surrounding
constructs.

Example:

SET total to zero

REPEAT

READ Temperature

IF Temperature > zero THEN

total = total + 1

END IF

UNTIL Temperature < zero


Print total

In the above example, the IF construct is nested within the REPEAT construct,
and therefore is indented.

PSEUDOCODE: START AND STOP

Usually there is no Start and Stop when using pseudocode, unlike with
flowcharts.

It is a good programming practice to indicate the start and end of the


pseudocode.

When writing the pseudocode for a program:

Program “Name”– start of the pseudocode

EndProgram “Name” – end of pseudocode

Example: Program ComputeArea, EndProgram Compute Area

When writing the pseudocode for a subprocedure/function:

Procedure/Function “Name”– start of the pseudocode

EndProcedure/EndFunction “Name” – end of pseudocode

Example: Procedure ComputeArea, EndProcedure Compute Area


INTRODUCTION TO C PROGRAMMING

A programming language written by Brian Kernighan and Dennis Ritchie. This


was to be the language that UNIX was written in to become the first "portable"
language.

A BRIEF HISTORY OF C

In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C
Programming Language by Kernighan & Ritchie caused a revolution in the
computing world.

In 1983, the American National Standards Institute (ANSI) established a


committee to provide a modern, comprehensive definition of C. The resulting
definition, the ANSI standard, or "ANSI C", was completed late 1988.

WHY IS C STILL USEFUL?

C provides:

• Efficient, high performance and high quality software


• Flexibility and power
• Stability and small size code
• Provide functionality through rich set of function libraries
• Gateway for other professional languages like C → C++ → Java

C is used:

• System software compilers, editors


• Data compression, graphics and computational geometry, utility
programs
• Databases, operating systems, device drivers, system level routines
• Also used in application programs
Your First C Program

int main(){

int answer;

float answer2;

printf(“Hello world!\n”);

//addition

answer= 5 + 2;

printf(“5 + 2 = %d”, answer);

//subtraction

answer= 5 – 2;

printf(“5 – 2 = %d”, answer);

//multiplication

answer = 5 * 2;

printf(“5 * 2 = %d”, answer);

//Division

answer = 5 / 2;

printf(“5 / 2 = %d”, answer);

//Division with float

answer2 = 5 / 2;

printf(“5 / 2 = %f”, answer2);

return 0;

}
COMMENTS

A comment is any text

between /* */ or after //

/* */ - can span several lines

// - can only span ONE line

Use comments to explain parts of your program and to make it more


understandable.

Comments are not executed by the computer.

Example:

//This line evaluates the product

PREPROCESSOR DIRECTIVES/HEADER FILES

• Preprocessor directives are the first steps the program executes.


Start with #
• Header files are files outside of your program that are also read by your
program
• #include – “read in this file, too”
• stdio.h – a library or file that provide standard input/output functions
MAIN FUNCTION

Functions are blocks of statements.

Enclosed between { }

{ } mark the beginning and end of a function.

The main function is the first function executed.

Can call other functions.

NOTE: ALL PROGRAMS MUST HAVE A MAIN FUNCTION.

The “return 0” statement means that the program completed successfully.

VARIABLES

• Variables represent memory locations in the computer.


• Declaring a variable reserves a memory location
• Variable declaration format:
o datatype variable_name
• Make your variable names as descriptive as possible.
STATEMENTS

• A statement is the basic building block of a program. It usually translates


to one or more machine instructions.
• ALL STATEMENTS END WITH A SEMICOLON ( ; )
• The printf statement is a function from the C library stdio.h used to display
outputs to your screen.
• Usually used to print out strings (sequence of symbols usually enclosed in “
“)
• The “\n” symbol is an escape sequence
Escape Sequences

• Used to format your strings


Some Escape Sequences:

• \n – newline
• \t – tab
• \r – carriage return
• \f – formfeed
• \\ - backslash
• \” – double quote
• \’ – single quote
%d is a placeholder that will be replaced by the value of a variable.

%d – will be replaced by an integer value

%f – will be replaced by a real/floating point value

Arithmetic Operators

• Addition (+)
• Subtraction (-)
• Multiplication (*)
• Division (/)
• Modulo (%)
• Assignment (=)
• Stores a value into a variable
• Unary plus and minus
• +answer
• -answer

Arithmetic Operators

• Increment
o Increase value of a variable by 1
o Prefix
§ ++answer
o Postfix
§ answer++
• Decrement
o Decrease value of a variable by 1
o Prefix
§ --answer
o Postfix
§ answer—

DIFFERENCE BETWEEN PREFIX AND POSTFIX INCREMENT/DECREMENT:

PRECEDENCE
(taken from https://en.cppreference.com/w/c/language/operator_precedence)
DATA TYPES IN C

There are only four basic data types:

THE CHARACTER DATA TYPE

§ Keyword: char
§ A char is a letter, digit or symbol enclosed in single quotes.
§ Here are some examples of characters:
o ‘c’ ‘S’ ‘2’ ‘$’ ‘ ‘
§ Note that the space (‘ ‘) is a character just like a any letter or digit
§ Can also be an escape sequence
o ‘\n’
THE INTEGER DATA TYPE

• Keyword: int
• Represents whole numbers in C
• Its values range from –32768 to 32767 (at least)
o Size of int may vary depending on the compiler
• Here are some example of integers:
o -214
o +2001
o 2002
• An int cannot contain commas.
o For example: 2,001 is not a valid integer value
• Can contain an optional sign (+ or -)
TYPE MODIFIERS

Below is a table of all allowed combinations of these type modifiers:

Note: Type modifiers only apply to the int data type

REAL NUMBER DATA TYPE

• Both float and double data types represent a real number in C.


• A float consists of an optional sign (+ or -), followed by one or more digits,
a decimal point and one or more further numbers.
• A double is a special float, which can store more significant digits.
• The value of a float data type ranges from 3.4x10^-38 to 3.4x10^+38.
• The value of a double data type ranges from 1.7x10^-308 to 1.7x10^+308.
• We often use scientific notation to represent real numbers.
o In Math, 1.23x105 = 123000.0
o In C, 1.23e5 = 123000.0
• Here are some invalid examples of real numbers in C.
o 0.1234e /* missing exponent */
o 5e-0.3 /* invalid exponent */
o 34,500.99 /* comma not allowed */
• Here are some valid examples of real numbers in C
o 0.1234
o 15e-3
o 34500.99
PRINTF PLACEHOLDERS

FORMATTING OUTPUT REAL NUMBERS

Code:

float pi;

pi = 3.1415926535897;

printf(“%f”, pi);

• The code will display: 3.141593


• By default, C displays real numbers up to 6 decimal places
• But what if we want to show only 3 decimal places?
Code:

Float pi;

pi = 3.1415926535897;

printf(“%.3f”, pi);

• The code will display 3.142


• The .3 specifies the precision of the real number to be displayed.
INPUT STATEMENT

• The scanf function (found in the stdio.h header file) reads input from the
keyboard and stores the value into a variable.
• Usage:
o To read in an integer value
§ int answer;
§ printf(“Enter a number: “);
§ scanf(“%d”,&answer);
o To read in a real value using a float data type
§ float answer;
§ printf(“Enter a number: “);
§ scanf(“%f”,&answer);
o To read in to a real value using a double data type
§ double answer;
§ printf(“Enter a number: “);
§ scanf(“%lf”,&answer);
o To read in a character value
§ char answer;
§ printf(“Enter a character: “);
§ scanf(“%c”,&answer);
• It is possible to get more than one value using the scanf function
• Example:
o int answer1;
o float answer2;
o scanf(“%d %f”,&answer1,&answer2);
• As a general rule, it is not good to get more than one input using scanf.
Only get one input at a time using the scanf function.
CONSTANTS

• The scanf function allows a programmer to get input from the user.
• But what if we already know the value that we need?
o Value of pi accurate up to 15 decimal places
§ 3.141592653589793
o It would be a hassle for the user if they have to enter the value of pi
• Three ways of declaring constant values.
INITIALIZE VARIABLES

• We can initialize a variable upon its declaration


• Example:
o float pi = 3.141592653589793;
o This code will declare a variable pi of float data type with an initial
value of 3.141592653589793
• This method has some problems:
o Value of pi can be changed at any point of the program.
o Can be a hassle in larger programs.

CONST KEYWORD

• We can declare a variable to be a constant using the const keyword.


• This will prevent any changes in a variable’s value.
• Example
o float const pi = 3.141592653589793;
• Can still be a hassle in larger programs.
#DEFINE PREPROCESSOR

• Another way to designate a constant is to use the preprocessor


command define
• Syntax: #define <identifier> <value>
• A #define statement allows you to give names to constants.
• Example:
o #define PI_VALUE 3.141592653589793;
o #define EXCHANGE_RATE 41.50;
• The action of #define is just like the search and replace command found
in your text editor.
• Constants declared by using the #define statement cannot have their
values changed at any point in the program.

After using the #define statement to create a constant, you can use it just like a
variable.
Example:

#include<stdio.h>

#define pi_value 3.141592653589793;

int main(){

float circumference, area, radius, pi=pi_value;

printf(“enter radius: “);

scanf(“%f”,&radius);

circumference = 2*radius*pi_value;

area = pi*radius*radius;

printf(“circumference: %f\n area: %f”,circumference,area);

return 0;

TYPE CASTING

RECALL...

• Our first c program made an error when dividing 5 by 2.


o Result was 2 instead of 2.5
o We had to convert everything (variable and values) to real values
§ answer2 = 5.0/2.0;
• We can convert between data types without having to declare new
variables and change values.
• Two types of type casting
o Implicit type casting
o Explicit type casting
• Implicit type casting happens when C automatically converts a type from
one format to another
• Example:
o int answer;
o answer = 2+3.5;
• C will convert or “cast” the sum of 2 and 3.5 as an integer value.
• If the variable answer is changed to float, then C will convert the sum of 2
and 3.5 into a real value.
• We can actually “force” the conversion process to take place
• This is called explicit type casting and is done with a unary operator called
a type cast
• Format: (data type) expression/variable.
• Example:
o float answer;
o answer = (float) 5/2;
RELATIONAL OPERATORS

Symbols used to compare numbers and characters to determine relative order.

RELATIONAL EXPRESSIONS

• Boolean expressions
o Evaluate to either true or false
• Examples:
o 12 > 5 is true
o 7 <= 5 is false
o Given x = 10
§ x == 10 is true,
§ x != 8 is true
§ x == 8 is false

THE IF STATEMENT

• Allows statements to be conditionally executed or skipped over.


• Models the way we mentally evaluate situations:
o “If it is raining, take an umbrella.”
Syntax:

WHAT HAPPENS IN AN IF STATEMENT

• If (expression) is true then statement(s) is executed.


• If (expression) is false then statement(s) is skipped.
FLOW CHART OF AN IF STATEMENT
EXAMPLE:

float examscore,grade;

examscore = 97;

if (examscore > 90) {

grade = 1.75;

printf(“Good work!\n”);

printf(“Your grade is %.2f”,grade);


THE IF/ELSE STATEMENT

Allows choice between statements

Format:

if (expression) {

statements

} else {

statements

FLOW CHART OF AN IF/ELSE STATEMENT


THE IF/ELSE IF STATEMENT

• Chain of if statements that test in order until one is found to be true


• Also models thought processes:
o “if it is raining, take an umbrella, else, if it is windy, take a jacket, else
take sunglasses.”

The last “else” statement is optional

NESTED IF STATEMENTS

• An if statement can be part of an if or else part of another if statement.


• Can be used to evaluate more that one data item.

NOTE: Always indent your nested statements

LOGICAL OPERATORS

• Used to create relational expressions from other relational expressions.


• Operators:
o && - logical AND
o || - logical OR
o ! - logical NOT
NOTES ON USING LOGICAL OPERATORS
• ! has highest precedence, followed by &&, then ||
• If the value of an expression can be determined by evaluating just the
sub-expression on left side of a logical operator, then the sub-expression
on the right side will not be evaluated (short circuit evaluation)

LOGICAL OPERATORS – EXAMPLES

Int x=12, y=5, z=-4;

THE SWITCH STATEMENT

• Used to select among statements from several alternatives


• May be used instead of the if/else if statement
SWITCH STATEMENT FORMAT

SWITCH STATEMENT REQUIREMENTS

• Expression must be an integer variable or an expression that evaluates into


an integer value.
o Characters can also be used.
• Exp(1) through exp(n) must be constant integer expressions or literals (e.g.
integers and characters), and must be unique in the switch statement.
• default is optional.
HOW IT WORKS

• The value of expression is compared against exp1 through exp(n).


• If expression matches a value exp(i), the program branches to the
statement following exp(i) and continues to the end of the switch block.
• If no matching value is found, the program branches to the statement
after default.
BREAK STATEMENT

• Used to stop execution in the current block.


• Used to exit a switch statement.
• Useful when you want to execute a single case statement without
executing the statements following it..

You might also like