Anda di halaman 1dari 45

C Programming

COP-2220C
Instructor: Brian Williamson

“Hardware: The parts of a computer system that can be kicked.” – Jeff Pesis
About Me
 E-mail: BWilliamson9@valenciacollege.edu

 Master’s Degree in Computer Science from UCF


 Worked for five years at Lockheed Martin
 Software Engineer in Research and Development
 Currently work at a small software company
 Develop embedded flight software for satellite
systems
 Worked part time at UCF on research projects.
 Technical Expertise: C, Objective C, C++, C#, Unity
3D Game Engine, OpenGL, HTML, XML, SVN,
VxWorks
About You
 As we take attendance this time, please introduce
yourself.
 What major are you pursuing?
 What are your goals with learning programming?
 What areas of computer science interest you?
 Anything else you want to add? Hobbies? Interests?
Key Points from the Syllabus
 Each of the following are worth 100 points.
 All homework assignments.
 Can be turned in late for points deducted each day late.
 In-class assignments.
 Self assessment quizzes at the end of the lecture.
 Each Test (there are three)
 The Final Exam
 The Final Project
 The lowest of TEST score will be dropped.
Section 1 – Getting
Started
Getting Started in Programming
 Should be familiar with code by now.
 Focus is on C syntax and concepts to be learned from
them.
 We will use Visual Studio Community 2017.
 Step by step guide is on Blackboard in References.
Studying Terms
 Typically terms are introduced to enforce some concepts.
 Also to be studied for exams.
 Usually near the start of a lecture for easy reference.
 But covers concepts we will be going over.
Terms to Know
 Syntax – Rules for writing a program in a particular
language.
 Operator – Symbol representing a function that calculates
a value.
 Operand – Value to the left or right of an operator.
 Promotion – Changing the data type of a variable so that
it can hold more information.
 Demotion – Changing the data type of a variable so that it
loses information.
 Type Casting – A way to temporarily and explicitly change
the data type of a variable.
Programming Overview
 In C code is sequential.
 You are writing sequential steps for the processor.
 The steps flow from the top to the bottom.
 Each step MUST be written correctly for the compiler to
understand.
 What is a compiler?

Object File Machine Code


Your Code (Processor Specific) (Executable)
C
#include <stdio.h>
void main() Compiler jmp 1,0 Linker 1011011010110001
brne $2,0,1 100100111000110
{
goto label1 110010010000101
}
Note: Actual instructions are made up and do not represent a real relationship
First Code (build together)
#include <stdio.h>
void main()
{
printf("Hello world!\n");
}
Breaking down the first code
#include <stdio.h>

 This is a compiler directive (usually begin with #)


 void
Thismain()
tells the compiler to include the stdio (standard
 IO)
All Clibrary.
code must have a main function that looks like
{
the following.
 This is where the code begins executing.
 The curly brackets represents blocks of code.
 This is stating that everything that follows until the
closed bracket } belongs to the main function
Breaking down the first code
printf("Hello world!\n");

 printf is a print function.


 Everything inside the quotation marks is a string that
} will be printed to the console output.
 Here we close out the last block of code we opened
with {
 In this example this basically says “the code for the
main function ends here”.
Building and Running
 Syntax / Compile errors
 If your code does not match basic C syntax
 The compiler will let you know when it fails to build.
 Visual Studio Intellisense
 Very good at trying to tell you what you need.
 There is no easy answer to debugging code.
 It takes practice and time (so start the homework early!)
 I can assist to a limited degree.
 If you e-mail me asking for code help. Include the code either
copied and pasted into the e-mail or attached.
 Use NetTutor and other resources available to you!
Building and Running
Continued
 Basic Syntax Tips for C
 Statements must end with ;
 This is most single lines of code (such as printf).
 Multiple lines of code are contained within { }
 So for example the multiple lines of the main function.
 C and C++ are case sensitive!
 The “main” function
 Required for all C programs in Windows.
 This is the starting point of your code. All code within the
main function block { } will be executed sequentially.
Concepts Summary
 Syntax – rules for writing a computer program in a
particular language.
 Errors in Syntax are called compile-time errors because
they are reported by the compiler.
 Output – information that originates in the program and
is output to a screen, or a file.
 You must get a simple program to run at this point – all
subsequent segments depend on your ability to
experiment with the concepts that are introduced.
Section 2 – Data Types,
Variables and Arithmetic
Variables and Data Types
 Variable - a place to hold data.
 The compiler actually creates a memory space for you.
 Data type – what 'kind' of data you can hold in a
particular variable.
 All variables in C have a data type
Data Types
 We will look at two data types to get started.
 Integer: a whole number. It has no decimal point. 23, -
1903, 0, 345, 9087 are integers.
 Real numbers: numbers with a decimal point 23.4, -
1903.266, 345.0 are real numbers.
 Every computer language has a syntax for the
programmer to create new variables of a specific type.
 Integers are declared as: int
 Real numbers are declared as: double
 There are more options, but we will start with these.
Variables
 Variables are named locations in memory that can hold a
single piece of data.
 Programmers choose the names for their variables
appropriate for what the variable is being used for.
 Some examples of variable names:
taxRate, total, salary, index, dayOfWeek,
 All variables hold a specific ‘type’ of data.
Variable Naming Rules and
Conventions
 Syntax Rules for variable names:
 cannot contain spaces my variable
 May not start with a digit 7days
 May only contain the characters a-z A-Z 0-9 _
Syntactically correct: days7, DAYS_7, daYs____7
 Naming conventions for variable names:
 Start with lower case letter
 Use mixed case for readability
 Name the variable appropriately for its use using correctly
spelled English words
Variable Naming Rules and
Conventions Continued
 An example: A variable that will hold the tax rate for a
median income family.
 Really long, but descriptive variable name:
taxRateForMedianIncomeFamily
 Really short, but non-descriptive variable name: trmif
 Find a good middle ground: taxRateMedian

 Remember: Visual Studio Intellisense will guess what you


are typing and assist with longer variable names.
Declaring a Variable in C
 All variables in C must be 'declared' giving a data type and
a name.
 The available data types are defined for a language.
 The programmer makes up the name.

int total;
A Program with Variables
#include <stdio.h>
#include <stdlib.h>
void main()
{
double taxRate;
int total = 127;
int countSamples;

taxRate = 0.07;
system("pause");
}
Arithmetic Operators
 In C there are arithmetic operators.
 These are symbols representing functions that calculate a
value.
 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Modulus (%)
Arithmetic Syntax
 operand operator operand;
 Operands can be variables: a + b;
 Constants: 10 + 5;
 Other calculations: (10 * 2) + 5;
 You don’t HAVE to assign the calculation to anything.
 a + b; is valid in the C syntax, but what is the point?
 c = a + b; assigns the calculation somewhere.
Modulus Operator
 Some may be unfamiliar with modulus (%)
 This operator returns the remainder of a division.
 10 / 3 = 3 with a remainder of 1.
 10 % 3 = 1
 4%2=0
 3%2=1
 There are many uses for this operator that you will see.
 Can constrain the range of a variable
 Such as with the rand() function.
 Can determine if a variable is even or odd.
 Variable % 2 will be 0 if even or 1 if odd.
Order of Operations
 Typically Arithmetic in C follows the orders we know:
 P E M D A S (Please Excuse My Dear Aunt Sally)
 Parenthesis, Exponent, Multiplication, Division, Addition,
Subtraction
 c = 10 * 2 + 5
 What happens first? 10 * 2
 Next? + 5
 c = 10 * (2 + 5)
 What happens first? 2 + 5
 Next? * 10
 TIP: Don’t assume order of operations. Use parenthesis
to always make your intention known.
Concepts Summary
 Variables – named locations that hold a piece of data.
 Data type – the type of data that can be put in a variable.
int double
 Naming rules and conventions.
 Assignment operator = pronounce it “gets” not “equals.”
Section 3 – More Data
Types and Mixed Types
More Data Types
 There is far more data types in C than just int and double.
 Eventually we will learn how to make our own data types.
 The issue is choose the type of variable you need.
 Also to be aware of mixing types and the effect.
 Choose a variable based on:
 Size of data (what is its min/max values)
 This is good for efficiency, but not typically a problem in modern
programming.
 Type of data (real number or whole number)
Reference Table
Type Range Bytes Required
unsigned char 0 -> 255 1

char -128 -> 127 1

unsigned short int 0 -> 65,535 2

short int -32,768 -> 32,767 2

unsigned long int and 0 -> 4.3 billion 4


unsigned int
long int and int -2.1 B -> 2.1 B 4

unsigned long long int 0 -> 2^64 8

long long int -2^63 -> 2^63 - 1 8

float 3.4E–38 to 3.4E+38 4


6-7 places
double 2.2E-308 to 1.8E+308 8
15-16 places
Summary of Table
 Remember this:
 Smallest whole number – char (1 byte)
 Second smallest whole number – short (2 byte)
 Second largest whole number – int (4 bytes)
 Largest whole number – long long (8 bytes)
 Smallest decimal number – float (4 bytes)
 Largest decimal number – double (8 bytes)

 The keyword unsigned can only be used with whole


numbers.
 It causes the RANGE of the variable to change.
 Moves from having negative numbers to starting at 0.
char data type
 The char data type is a little special.
 It is the smallest (1 byte).
 It can also represent single characters in C.
 Single characters are represented in single quotes ‘ ‘
char c = ‘a’;

 The char still stores a number.


 The compiler uses the built in ASCII table to translate
numbers to text.
ASCII table
(www.asciitable.com)
sizeof function
 C has a function called sizeof() that determined how many
bytes a variable is.
int x;
int y = sizeof(x);

 Y will contain the value 4 because integers are 4 bytes in


length.
Mixed Data Types
 Recall: Arithmetic operators have a data type.
 / for int is different than / for double
 10 / 3 = 3
 10.0 / 3.0 = 3.333333333

 The int version of / can cause data loss!


Determining Operator Data
Type
 The compiler picks the data type of the operator based on
the data type of the operands
 Operands are the values to the left and right of the
operator.
 (int) / (int) will result in integer division.
 (double) / (double) will result in double division.
 What happens if it is mixed?
 (int) / (double) or (double) / (int)?
 The compiler promotes the int to a double.
 (int) -> (double) / (double)
Mixed Types Continued
 What about for the = assignment operator?
 (int) = (double) / (double)
 Double division is used.
 The double is DEMOTED to an integer when it is assigned.
 Data is lost.
 int a = 10.0 / 3.0; results in a = 3
 (double) = (int) / (int)
 Integer division is used.
 Integer is promoted to double when assigned. No data is lost by
the assignment.
 double a = 10 / 3; results in a = 3.0
Type Casting
 Syntax: (data type to change to) variable
 Type casting is a way to temporarily and explicitly change
the data type of a variable.
 Useful for controlling promotion and demotion.
 May be used to acknowledge you understand demotion
may occur – Downcasting.
 int a = (int) (10.0 / 3.0);
 May be used to prevent data loss – Upcasting.
 double a = (double) 10 / 3;
 This forces the 10 to become a double. The 3 then is promoted
and double division is used. No data is lost.
Type Casting Order
 Be aware of where you place your type cast.
 (double) (10 / 3) is different than (double) 10 / 3
 For one, 10 / 3 is calculated then turned to a double.
 For the other, 10 is turned into a double and 3 is divided.
Mixed Type Tips
 Be aware of what a problem is asking of you.
 Some may be explicit.
 The user inputs an integer and…
 It may be implied.
 Calculate the average….
 This is usually a double.

 In general you do no want to lose data.


 If division is used, consider assigning it to a double and up-
casting variables.
int sum = 100, count = 10;
double average = (double) sum / count;
Summary
 The char data type can be used for small
numbers, or the ASCII code of a character.
 The sizeof operator can be used to
determine the size of a variable, or a data
type.
 The choice of a data type depends on
whether you need character, real or integer
data and how large the values might be that
you are computing with.
 The unsigned modifier allows you to use an
integer data type for positive values only.
 Mixed data type expressions, including cast
First Homework Assignment
 Verify that you can get code up and running.
 Create a program that outputs your name and one of
your favorite hobbies.
 Program must also create the following variables:
 X – short, equal to 10
 Y – int, equal to 3
 Z – double
 Assign X to equal 10 and Y to equal 3. Perform a calculation
where z = x / y and no data is lost (use a type cast).
 You do NOT have to output this value.
QUESTIONS?

Anda mungkin juga menyukai