Intro to C language - California State University, Los Angeles
Download
Report
Transcript Intro to C language - California State University, Los Angeles
Tarik Booker
CS 290
California State University, Los Angeles
This class is taught in the C language
The book is written in the C++ language
◦ Not (exactly) the same language
◦ Very similar
Look at lecture first before looking at book.
Introduction to C
Variables
Data Types
Intro to C
You should now have:
◦ Code::Blocks working and accessible
(Code:Blocks or Xcode for Mac users)
◦ The basic “Hello World” sample program that came
with the Code::Blocks
Lets look at that main.c program.
Lets look at that main.c program.
File
Headers
Main
Function
C Code
The simplest program in C:
int main()
{
}
Doesn’t do anything!!!
int main()
{
}
What does this mean?
◦ Main = most basic function
◦ Function = piece of written code
“Our” function
Doesn’t do anything
Functions:
◦ Pieces of code that run
◦ Main
Special function that runs first!
All C programs must have a main function
The type that is before specifies a return type (the type
of value the function should result in)
Normally main should return some value (using the return
keyword), but C lets you omit it in main
int main()
{
}
Curly Braces
◦ {}
◦ Signals the beginning and end of functions
◦ Also other code blocks
Note: Nothing in between curly braces here, so nothing
happens (executes)
Back to main.c
◦ “Hello World” is the most basic program
Main function
Now there’s code
File Headers
File
Headers
Main
Function
C Code
Include statements
“Header” files
◦ Compiler copies and pastes everything in the
header file to your code
◦ Access to basic functions
Stdio
Standard input/output functions
Stdlib
Standard library functions
◦ Can even create your own header files!
Using a file header:
◦ Use #include <headername>
Put the header name between the <>
These are really “.h” files
Built in files omit .h
Non-standard files are different:
#include “math.h”
Now we know:
◦ Main Function
◦ File Headers
Printf?
File
Headers
Main
Function
C Code
Print formatted data
◦ To Standard Out (stdio)
◦ Prints a formatted String (characters and text) to
the screen
printf(“This should display in my results.”)
The backslash-n (\n) will print a new line
\ - called an escape character
“Escape” from the current mode
What do these display?
printf(“Hello there!”);
printf(“Hi! \n My\n Name\n Is…”);
Can store values to be used (later) in a
program
◦ Values can be changed
◦ Remember algebra:
x + y = 34
y=5
x =?
◦ Similar Concept in Programming
You must declare a variable in a program
before you use it
◦ Format:
datatype variableName;
A variable can be of any name
Follow identifier rules (later…)
Descriptive names are best
Datatype variableName;
Datatype variableName1, variableName2,
…,variableName3;
Datatype
Specific classification of variables
Different types / different memory sizes
int, double
(main ones)
Discuss later
To name variables or functions
◦ Called identifiers
Should obey rules:
Consists of letters (upper/lower), digits, underscores
Must start with a letter (alphabetic character)
Must NOT start with a digit!!!
Cannot be a reserved word (int, return, main, etc.)
Can be up to 31 characters
Which are legal?
helloworld
aadzxvcna343546390thjke456hftg3sd
HappyHappy
34joy56
$Dollarsand
return
mains
#love
Why / Why not?
After declaring a variable, you must assign it
a value.
◦ Use the assignment operator (=)
int myNumber;
myNumber = 1;
Assigns the value 1 to variable myNumber
Note: You can assign a value to a variable in the
variable declaration statement!!!
Ex:
int myNumber = 1;
double volume = 3.0;
Assigning a value to a variable results in an
assignment statement
◦ double volume = 5.0;
You can also assign the results of an
expression to a variable
◦ double volume = 5.0 * 3.0;
◦ int x = 5 * (3 / 2);
Either method initializes the variable
◦ Should initialize variable after (during) you declare
it!
You can use other variables inside of
expressions!
◦ Can also use the same variable!
◦ int x = 1;
◦ x = x + 1;
Executes Right-Hand Side (RHS) first, then assigns the
result to the Left-Hand Side (LHS)
What is x after the code?
Variable values can change during a program
(Named) Constants are permanent
(throughout the life of the program)
◦ You can define constants
◦ Use the const keyword (either before or after the
datatype)
const datatype constantname = value;
datatype const constantname = value;
Ex:
const double PI = 3.14159;
int const x = 5;
(Numeric) Data Types represent different
ways to store numeric values in a variable
◦ Variables are stored in (primary) memory
◦ Different data types take up different spaces in
memory
Integer Data Types
◦ Used to store integers
…, -10, -9, …, -3, -2, -1, 0, 1, 2, 3, …, 9, 10, …
int
long
◦ Many more (will discuss later…)
Floating-Point Data Types
◦ Written in Scientific Notation
Mantissa
Exponent
double
float
(Will discuss later…)
C includes standard arithmetic operators
Addition
Subtraction
Multiplication
Division
+
*
/
Also has modulus (%)
Also called the remainder operator
Gives the remainder after division
6%2 (Say 6 “mod” 2)
What is 6%2?
3%1
1%3
10%5
Any even number % 2?
Any odd number % 2?
Can use this to check evens or odds
Use the pow(a,b) function
◦ Requires double type
◦ Returns ab
◦ Must include math.h
#include <math.h>
◦ Ex:
double y=1.0;
y = pow(2.0,3.0);
Literal – Constant values that appear in a
program
◦ Ex:
◦ Or:
int numberOfYears = 34;
double weight = 0.305
34 and 0.305 are literals
◦ Different types of literals
Integer
Floating-Point
Integer Literals:
◦ Can be assigned to an integer variable
◦ Works so long as it is within the range of the
variable type
◦ Assumed to be type int (32-bit range)
◦ For type long, append the letter L to it
Ex: 2145063967L
Can also use binary integer literals
Start with 0B or 0b (zero b)
Ex: 0B1111 results in 15
Also can use octal (base 8) and hexadecimal
(base 16) integer literals
Octal: Start with 0
Ex: 07777
results in 4095
Hex: Start with 0x or 0X (zero x)
Ex: 0XFFFF results in 65535
Floating-Point Literals
◦ Written with a decimal point
Ex: 5.0
◦ Default is double
Make literal float by adding an f
Ex: 100.2f
Note: double has more significant digits (15-18)than
float (7-8)
You must use the percent sign (%) when
printing a variable
◦ Use the percent sign and a code for the type
%d
integer
%lf
double
%f
float
◦ Use the code within the String, then after, use a
comma, and the variable name
Ex:
◦ int x = 1;
◦ printf(“The result is: %d”,x);
◦ double y = 3.0;
◦ printf(“The result is: %lf”,y);
You can take any mathematical expression
and translated into code
Make sure you use parentheses whenever
appropriate
◦ Ex:
z=
◦ Result:
3+4𝑥
10
+
10(𝑦−3)
7
4
− 9( )
𝑥
z = (3+4*x)/ 10 + 10 * (y-3) / 7 – 9*(4 / x);
What’s the order of operations?
◦ PEMDAS
◦ Please Excuse my Dear Aunt Sally
◦ Parentheses, Exponent, Multiplication, Division,
Addition, Subtraction
◦ Equal operators (M, D, and A,S) go from left to right
You can combine arithmetic operators and
the assignment operator to perform
augmented operators!!
Ex: x = x + 1;
1 is added to x, and the result is put back into itself
Will happen often (later)
Can shorten this to:
x += 1;
This is translated as x = x + 1;
Works for other operators
Addition
◦ x += 1;
Result: x = x + 1;
Subtraction
◦ x -= 5;
Result: x = x – 5;
Multiplication
◦ y *= 3;
Result:
Division
y = y * 3;
◦ volume /= 7;
Result: volume = volume / 7;
Remainder
◦ i %= 5;
Result: i = i % 5;
Shorthands for incrementing and
decrementing variables;
◦ ++, - ◦ Adds (++) or Subtracts (--) by one
Ex: int i = 3;
i++;
Result?
Ex:
z--;
int z = 4;
◦ Can put before (++i) or after variable (z--)
If used alone (i++, or --z) direction doesn’t
matter.
◦ Ex:
◦ or:
++j;
j++;
// Doesn’t matter
If used within an expression (or statement),
direction does matter
Preincrement / Predecrement
◦ Ex:
++var
--count
◦ If used within an expression, the variable is
incremented (or decremented) first, then used in
the statement
◦ Ex:
int j = ++i;
If i is 2, what is j?
Postincrement / Postdecrement
◦ Ex:
var++
count-◦ If used within an expression, the variable is used in
the statement first, then incremented (or
decremented) afterward
◦ Ex:
int j = i++;
If i is 2, what is j?
What if i is 6?