0% found this document useful (0 votes)
23 views19 pages

Lecture 01 - Introduction

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)
23 views19 pages

Lecture 01 - Introduction

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/ 19

3/9/2022

“Everybody … should learn to program a computer ... because it teaches you to think.”
- Steve Jobs
Computational Thinking
• Knowledge
CSE102
Computer Programming with C
2021-2022 Spring Semester
Introduction to CSE102
© 2015-2022 Yakup Genç

February 2022 CSE341 Lecture 1.1 2

Computational Thinking Computational Thinking

February 2022 CSE341 Lecture 1.1 3 February 2022 CSE341 Lecture 1.1 4

1
3/9/2022

Computational Thinking Programming Languages


• Computation What's a programming language?
A programming language is an artificial language designed to communicate instructions to
a machine, particularly a computer [Wikipedia].
A language is a “conceptual universe” providing a framework for problem-solving and useful
concepts and programming methods [Perlis].

How many programming languages are there?


Thousands!

Which one to use?


For now, we will claim C…

February 2022 CSE341 Lecture 1.1 5 February 2022 CSE341 Lecture 1.1 6

Programming Language Popularity History of C


• C Programming Language
− Evolved by Ritchie from two previous programming languages, BCPL and B
− Used to develop UNIX
− Used to write modern operating systems
− Hardware independent (portable)
− By late 1970's C had evolved to "Traditional C“
• Standardization
− Many slight variations of C existed, and were incompatible
− Committee formed to create an "unambiguous, machine-independent" definition
− Standard created in 1989, updated in 1999
https://spectrum.ieee.org/static/interactive-the-top-programming-languages-2021

February 2022 CSE341 Lecture 1.1 7 February 2022 CSE341 Lecture 1.1 8

2
3/9/2022

Portability Tips C Standard Library


• Because C is a hardware-independent, widely available language, • C programs consist of pieces/modules called functions
applications written in C can run with little or no modifications on a − A programmer can create his own functions
wide range of different computer systems • Advantage: the programmer knows exactly how it works
• Disadvantage: time consuming
− Programmers will often use the C library functions
• C defines a small number of operations, instead it contains useful libraries
• Use these as building blocks
− Avoid re-inventing the wheel
• If a pre-made function exists, generally best to use it rather than write your own
• Library functions carefully written, efficient, and portable

February 2022 CSE341 Lecture 1.1 9 February 2022 CSE341 Lecture 1.1 10

Performance Tips Portability Tips


• Using Standard C library functions instead of writing your own • Using Standard C library functions instead of writing your own
comparable versions can improve program performance, because comparable versions can improve program portability, because these
these functions are carefully written to perform efficiently. functions are used in virtually all Standard C implementations.

February 2022 CSE341 Lecture 1.1 11 February 2022 CSE341 Lecture 1.1 12

3
3/9/2022

Software Engineering Observation Typical C Program Development


• Read the manuals for the version of C you are using. Reference these
manuals frequently to be sure you are aware of the rich collection of
C features and that you are using these features correctly.

February 2022 CSE341 Lecture 1.1 13 February 2022 CSE341 Lecture 1.1 14

Software Engineering Observation Software Development


• Your computer and compiler are good teachers. If you are not sure • Programming = problem solving
how a feature of C works, write a sample program with that feature, • Methodology
compile and run the program and see what happens. − Specify the problem requirements
− Analyze the problem
− Design an algorithm
− Implement the algorithm
− Test and verify the program
− Maintain and update the program

February 2022 CSE341 Lecture 1.1 15 February 2022 CSE341 Lecture 1.1 16

4
3/9/2022

Problem Requirements Software Development


• Statements of the problem • Programming = problem solving
− Understand the problem • Methodology
− Retrieve the requirements − Specify the problem requirements
− Eliminate unimportant aspects − Analyze the problem
− Design an algorithm
• May need to get information from specialists − Implement the algorithm
− Test and verify the program
− Maintain and update the program
• E.g. Write a program for mile to kilometer conversion

February 2022 CSE341 Lecture 1.1 17 February 2022 CSE341 Lecture 1.1 18

Analysis Software Development


• Identify • Programming = problem solving
• Input data
• Output data • Methodology
• Additional requirements and constraints − Specify the problem requirements
• Decide aspects of data − Analyze the problem
• Representation
• Relationships − Design an algorithm
− Implement the algorithm
• E.g. − Test and verify the program
• Input: distance on miles − Maintain and update the program
• Output: distance on kilometers
• Representation: floating point numbers
• Relationship: 1 mile = 1.609 kilometers

February 2022 CSE341 Lecture 1.1 19 February 2022 CSE341 Lecture 1.1 20

5
3/9/2022

Designing Algorithm Software Development


• Top-down stepwise refinement • Methodology
− List major steps (sub-problems) − Specify the problem requirements
− Break down each step into a more detailed list − Analyze the problem
• Desk-check your algorithm − Design an algorithm
− Perform steps of the algorithm by yourself − Implement the algorithm
• E.g.
1. Get the distance in miles
• Writing the algorithm in C by converting each step into statements of C
2. Convert the distance to kilometers − Test and verify the program
3. Display the distance in kilometers • Run the program for several input cases
− Maintain and update the program
− Step 2 may require further refinement • Keep the program up-to-date
2.1 The distance in kilometers is 1.609 times the distance in miles

February 2022 CSE341 Lecture 1.1 21 February 2022 CSE341 Lecture 1.1 22

Machine Models Today @ CSE102

Fixed Program Stored Program

February 2022 CSE341 Lecture 1.1 23 February 2022 CSE341 Lecture 1.1 24

6
3/9/2022

C Language Elements Preprocessor Directives


• Preprocessor modifies the text of a C program before compilation
• Preprocessor directives
− Start with a #
• #include <stdio.h>
− Each library has a header file. Include it to access the library
− Preprocessor inserts definitions from the header
− stdio.h includes information about standard input/output
• #define KMS_PER_MILE 1.609
− Defines a constant macro
• Value of KMS_PER_MILE can not change
− Preprocessor replaces each occurrence of “KMS_PER_MILE” in the text with “1.609”
− KMS_PER_MILE is easier to remember

February 2022 CSE341 Lecture 1.1 25 February 2022 CSE341 Lecture 1.1 26

C Language Elements Function main


• C programs have exactly one main function
• Marks the beginning of program execution
• (void) indicates that function receives no data
• int means that main "returns" an integer value
• Function bodies enclosed in braces ({ and })
• Function body has two parts
• Declaration
• Executable statements

February 2022 CSE341 Lecture 1.1 27 February 2022 CSE341 Lecture 1.1 28

7
3/9/2022

Identifiers Reserved words


• Reserved words
− E.g.: “int” and “void”
Keywords
− Can not be used for any other purpose
• Standard identifiers auto double int struct
− E.g.: scanf, printf break else long switch
− Has a special meaning but can be redefined case enum register typedef
• User-defined identifiers char extern return union
− E.g.: name of memory cells (miles) and KMS_PER_MILE const float short unsigned
− Free to select the name continue for signed void
− Syntax rules:
default goto sizeof volatile
• Includes only letters, digits and underscore
• Can not begin with digit do if static while
• C is case sensitive!

February 2022 CSE341 Lecture 1.1 29 February 2022 CSE341 Lecture 1.1 30

Program Style C Language Elements


• Pick meaningful identifiers
− Long enough to convey the meaning
• If the identifier consists of two words, place an underscore character
between words
• Do not choose similar identifier names
• Use uppercase letters for names of macros
− Use lowercase letters otherwise

February 2022 CSE341 Lecture 1.1 31 February 2022 CSE341 Lecture 1.1 32

8
3/9/2022

Variables Variables
• Variables: memory cells for storing data • Data types: abstraction of real types
− Values can change − Predefined data types
• Every variable has: − User-defined data types
− Name: identifier
− Each constant or variable has a type
− Type: int, double, char
− Size − int: whole numbers (-123, 15, 27384)
− Value • There is a range because of finite memory cell size

− double: real numbers (12.345, 0.5217e-4)


• Too large and too small numbers can not be represented

− char: character values (‘a’, ‘5’, ‘^’, ‘,’)

February 2022 CSE341 Lecture 1.1 33 February 2022 CSE341 Lecture 1.1 34

Memory (a) Before and (b) After Execution C Language Elements

February 2022 CSE341 Lecture 1.1 35 February 2022 CSE341 Lecture 1.1 36

9
3/9/2022

Executable Statements Effect of kms = KMS_PER_MILE * miles;


• Comes after declaration
• Compiler translates to machine language code
• Assignment statements
• Used to store value to a variable
• Ex: kms = KMS_PER_MILE * miles;
• In general
variable = expression;
• Assignment operator: =
• Should be read as
• becomes
• gets
• takes a value of
• Previous value of variable is lost!..

February 2022 CSE341 Lecture 1.1 37 February 2022 CSE341 Lecture 1.1 38

Effect of sum = sum + item; Executable Statements


• Input/Output Operations
• Input Operation: Reading a value into a variable by scanf
• A different data can be entered by the user
• Output Operation: Displaying a value by printf

• Several I/O functions in C


• All in standard I/O library
#include <stdio.h>

• Function call is an executable statement


• Function performs the action for you
February 2022 CSE341 Lecture 1.1 39 February 2022 CSE341 Lecture 1.1 40

10
3/9/2022

printf Escape Sequences


Displays the output
printf(“That equals %f kilometers.\n”, kms); Escape sequence Description

printf(format string, print list); \n Newline. Position the cursor at the beginning of the next line.
\t Horizontal tab. Move the cursor to the next tab stop.
• Function name: printf
• Function arguments: in paranthesis \a Alert. Sound the system bell.
• Format string: “That equals %f kilometers.\n” \\ Backslash. Insert a backslash character in a string.
• Print list: kms
\" Double quote. Insert a double-quote character in a string.
• Placeholders: %c, %d, %f, %lf
• Escape sequence:
• \n means newline : cursor moves the beginning of the next line
• Can be used anywhere in the format string

February 2022 CSE341 Lecture 1.1 41 February 2022 CSE341 Lecture 1.1 42

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


Reads the data into a variable
scanf(“%lf”, &miles);

scanf(format string, input list);

• Function name: scanf


• Function arguments: in paranthesis
• Format string: “%lf”
• Input list: &miles

• Address-of operator: &


• Used to inform scanf about the location of the variable
• If not used, scanf knows only the value of the variable

February 2022 CSE341 Lecture 1.1 43 February 2022 CSE341 Lecture 1.1 44

11
3/9/2022

Scanning Data Line Bob C Language Elements

February 2022 CSE341 Lecture 1.1 45 February 2022 CSE341 Lecture 1.1 46

Others General Form of a C Program


• The return statement
• Transfers the control to the OS #include <stdio.h>
• Return value indicates whether the operation is successful or not
• Comments void main()
• Ignored by the compiler {
• Provides information for the programmer int a, b;
double x, y;
/* this is a comment */ x = 10.0;
printf(…
}
February 2022 CSE341 Lecture 1.1 47 February 2022 CSE341 Lecture 1.1 48

12
3/9/2022

C Language Elements Program Style


• One statements in each line
• Use extra spaces for readability
• Compiler ignores them
• Leave a space before and after operators
• Indent each block
• Insert blank lines between sections
• Use comments
• Write a descriptive comment for
• the program (header section)
• each identifier
• each program section

February 2022 CSE341 Lecture 1.1 49 February 2022 CSE341 Lecture 1.1 50

Arithmetic Expressions Arithmetic Expressions


• Manipulates type int and double data • Unary Operators: +, -
• Binary operators: +, -, *, /, % • One operand
• Two operand: constant, variable or expression
• Type of the result depend on the types of the operands
• int if both operands are integer
• double otherwise
• Assignment:
• Mixed type expression??? • The value of expression is evaluated and result is assigned
• What if the type of the expression and the type of the variable is different?
• / operator • Assignment of int to double
• Integer division: computes integral part of the division • Fractional part is zero
• Division by zero!.. • Assignment of double to int
• Fractional part is lost
• % operator
• Returns integer remainder • Automatic type conversion
• Zero right operand? Undefined!.. • Type casting
• Negative right operand is non standard (int) 3.7

February 2022 CSE341 Lecture 1.1 51 February 2022 CSE341 Lecture 1.1 52

13
3/9/2022

Expression Evaluation Evaluation Tree for area=PI*radius*radius;


• If there are multiple operators in an expression the order of evaluation makes a
difference
• Ex: x / y * z

• Evaluation Rules:
• Parenthesis rule:
• All expressions in parenthesis are evaluated separately
• Nested parenthesis evaluated inside out
• Precedence rule:
• There is an evaluation order in operators
• Unary +, -
• *, / , %
• Binary +, -
• Associativity rule:
• Operators in the same sub-expression and at the same precedence level
• Unary: right to left
• Binary: left to right

February 2022 CSE341 Lecture 1.1 53 February 2022 CSE341 Lecture 1.1 54

Step-by-Step Expression Evaluation Evaluation for v=(p2-p1)/(t2-t1);

February 2022 CSE341 Lecture 1.1 55 February 2022 CSE341 Lecture 1.1 56

14
3/9/2022

Evaluation for z-(a+b/2)+w*-y Writing Mathematical Formulas


• Use parentheses as needed to specify the order of evaluation
• Place numerator and denominator of a division in parentheses
m = (a - b) / (c + d)
• Use extra parentheses for readability
(a * b * c) + (d / e) – (a + b)
• Do not skip * as in mathematical formulas
• In math: d = b2 – 4ac
• In C: d = b * b - 4 * a * c;
• Two operators can be one after the other
a * -(b + c)

February 2022 CSE341 Lecture 1.1 57 February 2022 CSE341 Lecture 1.1 58

Case Study: Coin Processor Case Study: Coin Processor


• Problem requirements • Design an algorithm
• Convert change to personalized credit slip
• User enters the number of each kind of coin 1. Get and display the customer’s initials
• Analyze the problem 2. Get the count for each kind of coin
• Personalizing the slip: use customers initials 3. Compute the total value in cents
• Count for each type of coin 4. Find the value in dollars and cents
• Total value of the coins in dollars and cents
• Input data 5. Display dollars and cents
• Initials: first, middle, last are characters • Some steps need to refine!...
• Counts: dollars, quarters, dimes, nickels, pennies are integers
• Output data • Implement the algorithm
• Dollars and cents: total_dollars and change are integers
• Intermediate data • In the next slide
• Total value in cents: total_cents is integer
• Relationships • Test and verify the program
• total_cents =
• total_dollars = • Maintain and update the program
• change =

February 2022 CSE341 Lecture 1.1 59 February 2022 CSE341 Lecture 1.1 60

15
3/9/2022

Supermarket Coin Value Program Supermarket Coin Value Program (cont’d)

February 2022 CSE341 Lecture 1.1 61 February 2022 CSE341 Lecture 1.1 62

Case Study: Coin Processor Output Formatting


• Test and verify the program • Default formatting
• User-defined format
• Try the program for several inputs • int: %4d (%nd)
• Make sure that program runs correctly • Field width
• Right justified
• - sign included in the count
• Maintain and update the program • C expands the field width if necessary
• Later!... • double: %6.2f (%n.mf)
• Field width
• Decimal places
• Decimal point, minus sign included in the field width
• Values between -99.99 to 999.99 for %6.2f
• At least one digit before decimal point
• Values are rounded if there are more decimal places
• -9.536 becomes -9.54
• Use %d or %.3f not to have leading blanks

February 2022 CSE341 Lecture 1.1 63 February 2022 CSE341 Lecture 1.1 64

16
3/9/2022

Input and Output Redirection Batch Version of Miles-to-Km Conversion Program

• Interactive mode
• Batch mode
• Input Redirection: standard input is associated with a file instead of keyboard
myprog < inputfile
• No need to display prompting message
• Display the message about input (echo print)
• Output Redirection: standard output is associated with a file instead of screen
myprog > outputfile
• Can print the file to get the hardcopy

February 2022 CSE341 Lecture 1.1 65 February 2022 CSE341 Lecture 1.1 66

Use of Input/Output Files Miles-to-Km Conversion Program with Named Files

• C allows to explicitly name an input or output file


• Declaring file pointer
FILE * inp;
FILE * outp;
• Opening file
inp = fopen(“filename”, “r”);
outp = fopen(“filename”, “w”);
• Reading from a file
fscanf(inp, “%d”, &nickels);
• Writing to a file
fprintf(outp, “Total is %d \n”, value);
• Closing file
fclose(inp);
February 2022 CSE341 Lecture 1.1 67 February 2022 CSE341 Lecture 1.1 68

17
3/9/2022

Case Studies Programming Errors


• Compute change for a given amount of money • Error = bug • Three kind of errors:
• Process of correcting errors: • Syntax errors
debugging • Violation of grammar rule
• Error messages • Detected by the compiler

• Depends on the system used • Run-time errors


• Detected while execution
• Not always easy to understand
• Illegal operation, division by zero etc.
• Logic errors
• Program runs but produces incorrect
result

February 2022 CSE341 Lecture 1.1 69 February 2022 CSE341 Lecture 1.1 70

A Program with Syntax Errors A Program with a Run-Time Error

February 2022 CSE341 Lecture 1.1 71 February 2022 CSE341 Lecture 1.1 72

18
3/9/2022

Revised Coin Value Program A Program That Produces Incorrect Results

February 2022 CSE341 Lecture 1.1 73 February 2022 CSE341 Lecture 1.1 74

Thanks for listening!

19

You might also like