First C Program - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

First C Program

Description:

Arithmetic/Logic Unit performs arithmetic operations, and ... Example of Compiling and Running a C Program in Cygwin. Lecture 1 -- 13. Standard Data Types in C ... – PowerPoint PPT presentation

Number of Views:77
Avg rating:3.0/5.0
Slides: 28
Provided by: davidls7
Category:
Tags: cygwin | first | program

less

Transcript and Presenter's Notes

Title: First C Program


1
Lecture 1
  • Introduction
  • First C Program
  • Data Types and expressions
  • Note Read Chapters 1 and 2 for this week

2
Architecture of a Computer
3
I/O Devices
  • Communications with the outside world.
  • Input devices
  • keyboard
  • mouse
  • joystick
  • Output devices
  • screen
  • printer
  • computer speakers

4
Central Processing Unit (CPU)
  • Has 2 components to execute program instructions
  • Arithmetic/Logic Unit performs arithmetic
    operations, and makes logical comparisons.
  • Control Unit controls the order in which your
    program instructions are executed.
  • Uses one or more registers as scratch space for
    storing numbers between instructions.
  • A typical CPU today can execute billions of
    arithmetic operations in a second.

5
Main Memory
  • Sometimes called random access memory (RAM).
  • Stores the numbers (data) that a program uses
    when it runs on the computer.
  • Contains millions of circuits which are either
    off or on (0 or 1) ? Binary
  • Also stores the instructions of the program that
    is running on the computer.
  • Divided into fixed size units of memory called
    words.
  • each word stores one number
  • each word has its own address

Data
Program Instructions
6
Secondary Storage
  • Permanent storage used to save data and programs
    when they are not running on the computer.
  • Data and programs are organized into varying size
    units called files.
  • Files are organized into directories that can
    contain subdirectories.
  • Examples of secondary storage include hard disks,
    floppy disks, and CDs.

7
The Programming Process
  • Use an editor (such as Notepad, Textpad or Visual
    Studio) to create a program file (source file).
  • contains the text of the program written in some
    programming language (like C)
  • Use a compiler/linker (such as gcc) to convert
    the source file into a machine code file (object
    file).
  • converts from English to binary with machine
    operations
  • includes other machine code that the program
    requires
  • Run the executable file.

8
Creating a C Program
  • A C program is a set of functions that
    collectively solve a given problem.
  • each function is a sequence of C statements
    (instructions)
  • execution always begins with a function named
    main
  • one function calls another function to get it to
    execute its statements
  • The C statements in a function are executed one
    after the other in sequential order as written.

9
First C Program Hello World!
  • Anything between / and / is a comment intended
    to improve the readability of the program.
  • include is used to tell the compiler and linker
    what library resources the program uses.
  • the ltstdio.hgt library defines everything you need
    to display messages on the screen, including
    printf
  • This program contains one function named main.
  • The program outputs (prints to the screen) the
    words
  • Hello, World!
  • / Nate Preston
  • Hello World Program
  • prog01.c
  • Jan 18, 2006
  • /
  • include ltstdio.hgt
  • int main ()
  • printf("Hello, World!\n")
  • return 0

10
Using printf to Display Messages On The Screen
  • To display a message on the computer screen use
    the printf statement.
  • The back slash \ indicates an escape sequence.
    This means to take the alternate meaning of
    whatever immediately follows it.
  • \n means to start a new line.
  • \t is a tab
  • \ is a quote
  • Text strings must always be surrounded by double
    quotes.
  • More examples

printf("Hello, World\n")
printf("Hello\nWorld!\n") printf("\tFirst part
of long message. ") printf("Second part of long
message.\n") printf("\"Hello\" World!\n")
11
Defining a C Function
  • A C function has the following form
  • The name of this function is main.
  • The word int, means that this functions returns
    an integer number.
  • usually 0 to indicate that the program ran
    correctly.
  • this is what the return statement does at the end
    of the function
  • The braces define the beginning and the end of
    the function.
  • The first line of the function is called the
    function header.

int main ( ) sequence of statements
separated by semicolons . . . return
0
12
Example of Compiling and Running a C Program in
Cygwin
13
Standard Data Types in C
  • A data type tells what type of data is stored in
    a given memory location. Standard C data types
    are broken into the following types
  • Integral Types
  • represent whole numbers and their negatives
  • declared as int, short, or long
  • Floating Types
  • represent real numbers with a decimal point
  • declared as float, or double, or long double
  • Character Types
  • represent single characters
  • declared as char

14
C Variables
  • Variables in C store data in memory so that the
    data could be accessed throughout the execution
    of a program
  • A variable stores data corresponding to a
    specific type.
  • Each variable that a C program uses must be
    declared at the beginning of the function before
    it can be used.
  • specify the type of the variable
  • numeric types int short long float
    double
  • character type char
  • specify a name for the variable
  • any previously unused C identifier can be used
  • Example int x
  • float sum, product

15
What Does a Variable Declaration Do?
int ageOfDog float tax_rate_Y2K char
middleInitial
A declaration tells the compiler to allocate
enough memory to hold a value of this data type,
and to associate the identifier with this
location.
4 bytes for tax_rate_Y2K
1 byte for middleInitial
16
Variable and function Names In C
  • Variables and function names in C are called
    identifiers.
  • identifiers are used for many other things as
    well
  • Rules for constructing valid identifiers in C
  • can contain letters (upper and lower case),
    digits, and the underscore ( _ ) character
  • cannot start with a digit
  • cannot be a reserved word
  • can be at most 256 characters long, though some
    compilers only look at first 32 characters
  • are case sensitive
  • Some reserved words in C

break case char const continue default do
double else enum float for goto if
int long return short signed static struct switc
h typedef union unsigned void while
17
Identifiers
  • VALID
  • age_of_dog tax_rate_Y2K
  • PrintHeading ageOfHorse_
  • NOT VALID (Why?)
  • age 2000TaxRate
    Age-Of-Cat day of week
  • Using meaningful variable names is a good
    programming practice

18
Giving a Value to a Variable
You can assign (give) a value to a variable by
using the assignment operator VARIABLE
DECLARATIONS char middleInitial char
letter int ageOfDog VALID
ASSIGNMENT STATEMENTS middleInitial X
letter middleInitial ageOfDog 12
19
Assignment Statement
  • An assignment statement is used to put a value
    into a variable.
  • The previous value is replaced
  • Syntax ltvariablegt ltexpressiongt
  • ltvariablegt is any declared variable in the
    program
  • ltexpressiongt is anything that produces a value of
    the appropriate type (more on this later)
  • first, the expression on right is evaluated.
  • then the resulting value is stored in the memory
    location of variable on left.
  • Examples
  • count 10
  • count count 1
  • area 3.14 radius radius
  • NOTE An automatic type coercion occurs after
    evaluation but before the value is stored if the
    types differ for expression and variable

20
Arithmetic Expressions With Integers (int, long)
  • Operators result is always an integer
  • Symbol Name Example Value (x 10, y 3)
  • addition x y 13
  • subtraction x y 7
  • multiplication x y 30
  • / quotient x / y 3
  • remainder x y 1
  • unary minus x -10
  • unary plus x 10
  • You can string the operators together to build
    longer expressions.
  • use parentheses to specify order of operations
  • precedence (after sub-expressions in parentheses)
  • first unary plus and minus from right to left
  • second , / and from left to right
  • third and from left to right

21
Arithmetic Expression Example
int y 2 int z z -y 3 (4 5) 10 -
-3
-2 3 9 10 - -3
-2 3 9 10 3
-6 9 10 3
-54 10 3
-4 3
-1
22
Arithmetic Exprs With Reals (float, double)
  • Arithmetic expressions with real numbers (numbers
    with decimal points) work the same way as with
    integers, with a few exceptions
  • there is no remainder operator ()
  • the / operator means divide, computing the
    answer to many decimal places
  • the result is a real value rather than an integer
    value
  • Important Real values are approximate and may
    contain errors in the last few digits.
  • about 7 digits of accuracy for type float
  • about 14 digits of accuracy for type double

23
Mixed Mode Arithmetic Expressions
  • Arithmetic expressions both integers and floats
    can get tricky.
  • if both operands are integers, integer arithmetic
    is used
  • if either operand is a float, float arithmetic is
    used
  • an integer operand is converted to float for the
    operation
  • Examples
  • int a, x
  • x 3.59 / x gets the value 3 (no rounding) /
  • float y 3 / y gets the value 3.0 /
  • a 12 / a gets the value 12 /
  • float avg (a x) / 2 / avg gets the
  • value 7.0 UH OH!!! /

24
Printing variables and constants to the screen
with printf
  • Use the following conversion specifications
  • d for an integer
  • ld for a long int
  • f float
  • f double
  • c for a character
  • Example Output
  • int sum 5
  • float avg 12.2
  • char ch A
  • printf(The sum is d\n, sum) The sum is 5
  • printf(avg f\n, avg) avg 12.2
  • prinf(ch c\n, ch) ch A
  • printf(d, f, c\n, sum, avg, ch) 5, 12.2, A
  • printf(d\n, 5) 5
  • Note see p. 152 in your textbook for a complete
    list of all datatypes

25
Reading data from the keyboard with scanf
  • Used to assign a value typed on the keyboard to a
    variable.
  • Used similarly to printf. You must use the
    following conversion specifications
  • Data Type printf converstion spec. scanf
    conversion spec.
  • int d d
  • long ld ld
  • float f f
  • double f lf
  • char c c
  • character string s --
  • The user must type a value followed by the Enter
    Key.
  • Ex scanf(d, num)


26
Program to find the average of two numbers
  • Note that you can declare more than one variable
    per line.
  • We divide by 2.0 instead of 2 so that the right
    hand side is a float (i.e. no truncation takes
    place)
  • scanf is used similarly to printf, except that
    you need to put an ampersand () before the
    variable name
  • The first argument of the scanf function is the
    conversion specifier(s) in quotes, then the
    variable name(s)
  • include ltstdio.hgt
  • int main ()
  • int num1, num2
  • float avg
  • / get two inputs /
  • printf( "Enter the first integer )
  • scanf( "d", num1 )
  • printf( "Enter the second integer" )
  • scanf( "d", num2 )
  • / compute and print the avg /
  • avg (num1 num2) / 2.0
  • printf( "The average is f\n", avg )
  • return 0

27
Note
  • HW 1 is posted on the course web site, and is
    due at the beginning of next class. Please note
    the submission instructions.
  • You may work on lab 1 for the rest of the class.
    When you're done, have one of the TAs or myself
    check you off.
Write a Comment
User Comments (0)
About PowerShow.com