Sie sind auf Seite 1von 38

Week 2 - Introduction to C Programming

Introduction
C programming language
Structured and disciplined approach to program design

A Simple C Program: Printing a Line of Text


1 2 3 4 5 6 7 8 9 10 /* Fig. 2.1: fig02_01.c A first program in C */ #include <stdio.h> int main() { printf( "Welcome to C!\n" ); return 0; }

Welcome to C!

Comments
Text surrounded by /* and */ is ignored by computer Used to describe program

#include <stdio.h>
Preprocessor directive
Tells computer to load contents of a certain file

<stdio.h> allows standard input/output operations

A Simple C Program: Printing a Line of Text int main()


C++ programs contain one or more functions, exactly one of which must be main Parenthesis used to indicate a function int means that main "returns" an integer value Braces ({ and }) indicate a block
The bodies of all functions must be contained in braces

A Simple C Program: Printing a Line of Text printf( "Welcome to C!\n" );


Instructs computer to perform an action
Specifically, prints the string of characters within quotes ( )

Entire line called a statement


All statements must end with a semicolon (;)

Escape character (\)


Indicates that printf should do something out of the ordinary \n is the newline character
5

A Simple C Program: Printing a Line of Text return 0;


A way to exit a function return 0, in this case, means that the program terminated normally

Right brace }
Indicates end of main has been reached

Another Simple C Program


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 } Enter first integer 45 Enter second integer 72 Sum is 117 return 0; /* indicate that program ended successfully */ printf( "Enter first integer\n" ); scanf( "%d", &integer1 ); /* prompt */ /* read an integer */ int main() { int integer1, integer2, sum; /* declaration */ /* Fig. 2.5: fig02_05.c Addition program */ #include <stdio.h>

Initialize variables Input

printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); sum = integer1 + integer2; printf( "Sum is %d\n", sum ); /* read an integer */ /* assignment of sum */ /* print sum */

Calculate Sum Print Sum

Program Output
7

Another Simple C Program: Sum two integers


As before
Comments, #include <stdio.h> and main

int integer1, integer2, sum;


Declaration of variables
Variables: locations in memory where a value can be stored

int means the variables can hold integers (-1, 3, 0, 47) Variable names (identifiers)
integer1, integer2, sum Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ )
Case sensitive

Declarations appear before executable statements


If an executable statement references and undeclared variable it will produce a syntax (compiler) error
8

Another Simple C Program: Sum two integers


scanf( "%d", &integer1 );
Obtains a value from the user
scanf uses standard input (usually keyboard)

This scanf statement has two arguments


%d - indicates data should be a decimal integer &integer1 - location in memory to store variable & is confusing in beginning for now, just remember to include it with the variable name in scanf statements

When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key
9

Another Simple C Program: Sum two integers


= (assignment operator)
Assigns a value to a variable Is a binary operator (has two operands)
sum = variable1 + variable2; sum gets variable1 + variable2;

Variable receiving value on left

printf( "Sum is %d\n", sum );


Similar to scanf
%d means decimal integer will be printed sum specifies what integer will be printed

Calculations statements

can

be

performed

inside

printf
10

printf( "Sum is %d\n", integer1 + integer2 );

Comments in C
Single line comment
// (double slash) Termination of comment is by pressing enter key

Multi line comment


/*. .*/ This can span over to multiple lines

11

Memory Concepts
Variables
Variable names correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous value Reading variables from memory does not change them

A visual representation
integer1 45

12

All variables must be declared at top of program, before the first statement. Declaration includes type and list of variables.
Example:
int main (void) { int var, tmp; }

Variables

13

Primitive types:
int (16-bits) char (8-bits) short (16-bits) long (32-bits) float (4 bytes) Double (8 bytes)

Data Types

Aggregate data types


Arrays come under this category Arrays can contain collection of int or float or char or double data

User defined data types


Structures and enum fall under this category.
14

Variables
Variables are data that will keep on changing Declaration
<<Data type>> <<variable name>>; int a;

Definition
<<varname>>=<<value>>; a=10;

Usage
<<varname>> a=a+1; //increments the value of a variable by 1

15

Variables
The following variable types can be signed:
signed char (8 bits) 128 to +127 signed short (16 bits) 32768 to +32767 signed int (16 bits) 32768 to +32767 signed long (32 bits) 2147483648 to +2147483648

or unsigned:
unsigned char (8 bits) 0 to + 255 unsigned short (16 bits) 0 to + 65535 unsigned int (16 bits) 0 to + 65535 unsigned long (32 bits) 0 to + 4294967295

NOTE: Default is signed it is best to specify.


16

Reserved Words
Keywords that identify language entities such as statements, data types, language attributes, etc. Have special meaning to the compiler, cannot be used as identifiers in our program. Should be typed in lowercase. Example: const, double, int, main, void, while, for, else (etc..)
17

Identifiers
Words used to represent certain program entities (program variables, function names, etc). Example:
int my_name;
my_name is an identifier used as a program variable

void CalculateTotal(int value)


CalculateTotal is an identifier used as a function name

Input and Output


Input
scanf(%d,&a); Gets an integer value from the user and stores it under the name a

Output
printf(%d,a) Prints the value present in variable a on the screen

Format specifiers for input and output


%d is a format specifier. This informs to the compiler that the incoming value is an integer value. Other data types can be specified as follows:
%c character %f float %lf double %s character array (string)

printf and scanf are defined under the header file stdio.h
19

Rules for constructing identifiers


Identifiers can consist of capital letters A to Z, the lowercase a to z, the digit 0 to 9 and underscore character _ The first character must be a letter or an underscore. There is virtually no length limitation. However,, in many implementations of the C language, the compilers recognize only the first 32 characters as significant. There can be no embedded blanks Reserved words cannot be used as identifiers. Identifiers are case sensitive. Therefore, Tax and tax both different.

20

Rules for constructing identifiers


Examples of legal identifier:
Student_age, Item10, counter, number_of_character

Examples of illegal identifier


Student age (embedded blank) continue (continue is a reserved word) 10thItem (the first character is a digit) Principal+interest (contain operator character +)
21

Recommendations for constructing identifiers


Avoid excessively short and cryptic names such as x or wt.
Instead, use a more readable and descriptive name such as student_id and net_value.

Use underscores or capital letters to separate words in identifiers that consist of two or more words.
Example, student_id or studentID are much easier to read than studentid.
22

Constants
Entities that appear in the program code as fixed values. 4 types of constants: Integer constants Floating-point constants Character constants String Literal

Integer Constant
Positive or negative whole numbers with no fractional part Optional + or sign before the digit. It can be decimal (base 10), octal (base 8) or hexadecimal (base 16) Hexadecimal is very useful when dealing with binary numbers Example: const int MAX_NUM = 10; const int MIN_NUM = -90; const int Hexadecimal_Number = 0xf87;

Integer Constant
Rules for Decimal Integer Constants
1. Decimal integer constants must begin with a nonzero decimal digit, the only exception being 0, and can contain decimal digital values of 0 through 9. 2. If the sign is missing in an integer constant, the computer assumes a positive value. 3. Commas are not allowed in integer constants. Therefore, 1,500 is illegal; it should be 1500.

Example of legal integer constants are 15, 0, +250 and 7550


0179 is illegal since the first digit is zero 1F8 is illegal since it contains letter F 1,700 is illegal since it contains comma

Floating Point Constant


Positive or negative decimal numbers with an integer part(optional), a decimal point, and a fractional part (optional) Example 2.0, 2., 0.2, .2, 0., 0.0, .0 It can be written in conventional or scientific way
20.35 is equivalent to 0.2035E+2 (0.2035 x 102 ) 0.0023 is equivalent to 0.23e-2 (0.23 x 10-2) E or e stand for exponent

In scientific notation, the decimal point may be omitted.


Example: -8.0 can rewritten as -8e0

Floating Point Constant


C supports 3 type of Floating-point: float (4 bytes), double (8 bytes), long double (16 bytes)
By default, a constant is assumed of type double Suffix f(F) or l(L) is used to specify float and long double respectively

Example:
const float balance = 0.125f; const float interest = 6.8e-2F; const long double PI = 3.1412L; const long double planet_distance = 2.1632E+30l

Character constants
A character enclosed in a single quotation mark Example:
const char letter = n; const char number = 1; printf(%c, S);
Output would be: S

How to write a single quotation mark?


is ambiguous, so escape character back slash \ i.e. \
28

Character constants
A character enclosed in a single quotation mark Example:
const char letter = n; const char number = 1; printf(%c, S); Output would be: S

How to write a single quotation mark? is ambiguous, so escape character back slash \ \

String Literals
A sequence of any number of characters surrounded by double quotation marks. Example:
Human Revolution

How to write special double quotation mark? is ambiguous, so use escape character
Example: printf(He shouted, /Run!/); output: He shouted, Run! - The escape character along with any character that follow it is called Escape Sequence

String Literals
Escape Sequence \a \b \f \n \r \t \v \\ \ \ \? Alert Backspace Formfeed New line Carriage return Horizontal tab Vertical tab Back slash Single quotation Double quotation Question mark Name Meaning Sounds a beep Backs up 1 character Starts a new screen of page Moves to beginning of next line Moves to beginning of current line Moves to next tab position Moves down a fixed amount Prints a back slash Prints a single quotation Prints a double quotation Prints a question mark

Statements
Assignment statement:
variable = constant or expression or variable examples: upper = 60; I = I + 5; J = I;

32

Arithmetic
Arithmetic calculations
Use * for multiplication and / for division Integer division truncates remainder
7 / 5 evaluates to 1

Modulus operator(%) returns the remainder


7 % 5 evaluates to 2

Increment (++) and decrement (--) operator


E.g. count++

Operator precedence
Some arithmetic operators act before others (i.e., multiplication before addition)
Use parenthesis when needed

Example: Find the average of three variables a, b and c


Do not use: a + b + c / 3 Use: (a + b + c ) / 3

33

Arithmetic
Arithmetic operators:
C o p era tio n Addition Subtraction Multiplication Division Modulus
Operator(s) ()

Arithm etic op era tor + * / %

Alg eb ra ic exp ression f+7 pc bm x/y r mod s

C exp ressio n f p b x r + * / % 7 c m y s

Order of evaluation (precedence) Rules Operation(s) of operator precedence: Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right. Multiplication,Divi Evaluated second. If there are several, they are sion, Modulus evaluated left to right. Addition Evaluated last. If there are several, they are Subtraction evaluated left to right.
34

*, /, or % + or -

Decision Making: Equality and Relational Operators


Executable statements
Perform actions (calculations, input/output of data) Perform decisions
May want to print "pass" or "fail" given the value of a test grade

if control structure
Simple version in this section, more detail later If a condition is true, then the body of the if statement executed
0 is false, non-zero is true

Control always resumes after the if structure

Keywords
Special words reserved for C Cannot be used as identifiers or variable names
35

Decision Making: Equality and Relational Operators


Standard algebraic equality operator or relational operator
Equality Operators

C equality or relational operator == != > < >= <=

Example of C Meaning of C condition condition

= not =
Relational Operators

x == y x != y x > y x < y x >= y x <= y

x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

> < >= <=

36

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

/* Using if statements, relational operators, and equality operators */ #include <stdio.h> int main() { int num1, num2; printf( "Enter two integers, and I will tell you\n" ); printf( "the relationships they satisfy: " ); scanf( "%d%d", &num1, &num2 if ( num1 == num2 ) printf( "%d is equal to %d\n", num1, num2 ); if ( num1 != num2 ) printf( "%d is not equal to %d\n", num1, num2 ); if ( num1 < num2 ) printf( "%d is less than %d\n", num1, num2 ); if ( num1 > num2 ) printf( "%d is greater than %d\n", num1, num2 ); if ( num1 <= num2 ) printf( "%d is less than or equal to %d\n", num1, num2 ); 37 ); /* read two integers */

Declare variables Input

if statements and Print

29 30 31 32 33 34 35 } return 0; /* indicate program ended successfully */ if ( num1 >= num2 ) printf( "%d is greater than or equal to %d\n", num1, num2 );

Exit main

Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7

Program Output

Enter two integers, and I will tell you the relationships they satisfy: 22 12 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12

38

Das könnte Ihnen auch gefallen