Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

53
Hello World Program Hello World Program The source code #include <stdio.h> int main() { printf("Hello World\n"); return(0); }

Transcript of Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Page 1: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Hello World ProgramHello World ProgramThe source code

#include <stdio.h>

int main()

{

printf("Hello World\n");

return(0);

}

Page 2: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

NameName DescriptionDescription Size*Size* Range*Range*

charchar Character or small Character or small integerinteger

1 byte1 byte signed: -128 to 127signed: -128 to 127unsigned: 0 to 255 unsigned: 0 to 255

short intshort int

(short)(short)

Short integerShort integer 2 bytes2 bytes signed: -32768 to 32767signed: -32768 to 32767unsigned: 0 to 65535 unsigned: 0 to 65535

intint IntegerInteger 4 bytes4 bytes signed: -2147483648 to signed: -2147483648 to 21474836472147483647unsigned: 0 to 4294967295 unsigned: 0 to 4294967295

long intlong int

(long)(long)

Long integerLong integer 4 bytes4 bytes signed: -2147483648 to signed: -2147483648 to 21474836472147483647unsigned: 0 to 4294967295unsigned: 0 to 4294967295

floatfloat Floating point Floating point numbernumber

4 bytes4 bytes 3.4e +/- 38 (7 digits) 3.4e +/- 38 (7 digits)

doubledouble Double precision Double precision floating point numberfloating point number

8 bytes8 bytes 1.7e +/- 308 (15 digits) 1.7e +/- 308 (15 digits)

long long doubledouble

Long double Long double precision floating precision floating point numberpoint number

8 bytes8 bytes 1.7e +/- 308 (15 digits) 1.7e +/- 308 (15 digits)

Data types

Page 3: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Variable Declarationint length = 100; int a;char num = ‘9’; //The actual value is 57float deposit = 240.5;unsigned short ID = 0x5544;

Try the following statements, and see what happens

unsigned char value = -1;printf(“The value is %d \n”, value);

unsigned char value = 300;printf(“The value is %d \n”, value);

Page 4: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

ResultResult

DefinitionDefinition Memory layoutMemory layout DisplayDisplay commentcomment

unsigned char unsigned char value = -1value = -1

1111111111111111 255255

unsigned char unsigned char value = 300value = 300

0010110000101100 4444 overflowoverflow

Page 5: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Variable typesVariable types Local variable

Local variables are declared within the body of a function, and can only be used within that function.

Static variableAnother class of local variable is the static type. It is specified by the keyword static in the variable declaration. The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function.

Global variable A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions.

Page 6: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

An example

int global = 10; //global variable

int func (int x){

static int stat_var; //static local variable

int temp; //(normal) local variableint name[50]; //(normal) local

variable……

}

Page 7: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

printf()printf()

The printf() function can be instructed to print integers, floats and string properly.

The general syntax is printf( “format”, variables);

An exampleint stud_id = 5200;char * name = “Mike”;printf(“%s ‘s ID is %d \n”, name,

stud_id);

Page 8: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Format Identifiers%d decimal integers%x hex integer%c character%f float and double number%s string%p pointer

How to specify display space for a variable?printf(“The student id is %5d \n”, stud_id);

The value of stud_id will occupy 5 characters space in the print-out.

Page 9: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Why “\n”

It introduces a new line on the terminal screen.

\a alert (bell) character \\ backslash

\b backspace \? question mark

\f formfeed \’ single quote

\n newline \” double quote

\r carriage return \000 octal number

\t horizontal tab \xhh hexadecimal number

\v vertical tab

escape sequence

Page 10: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Arithmetic OperationsArithmetic Operations

Page 11: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Arithmetic Assignment Arithmetic Assignment OperatorsOperators

Page 12: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Increment and Decrement Increment and Decrement OperatorsOperators

awkward easy easiest

x = x+1; x += 1 x++

x = x-1; x -= 1 x--

Page 13: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

ExampleExampleArithmetic operatorsint i = 10;int j = 15;int add = i + j; //25int diff = j – i; //5int product = i * j; // 150int quotient = j / i; // 1int residual = j % i; // 5i++; //Increase by 1i--; //Decrease by 1

Page 14: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Comparing themint i = 10;int j = 15;float k = 15.0;

j / i = ?j % i = ?k / i = ?k % i = ?

Page 15: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

The Answerj / i = 1; j % i = 5;k / i = 1.5;k % i It is illegal.

Note: For %, the operands can only be integers.

Page 16: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Logical OperationsLogical Operations What is “true” and “false” in C

In C, there is no specific data type to represent “true” and “false”. C uses value “0” to represent “false”, and uses non-zero value to stand for “true”.

Logical Operators

A && B=> A and B

A || B => A or B

A == B => Is A equal to B?

A != B => Is A not equal to B?

Page 17: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

A > B => Is A greater than B?

A >= B => Is A greater than or equal to B?

A < B => Is A less than B?

A <= B => Is A less than or equal to B?

Don’t be confused

&& and || have different meanings from & and |.

& and | are bitwise operators.

Page 18: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) =>if( i != j || k < j) =>if( j<= k || i > k) =>if( j == k && m) =>if(i) =>if(m || j && i ) =>

Page 19: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => falseif( i != j || k < j) => trueif( j<= k || i > k) => true if( j == k && m) => falseif(i) => trueif(m || j && i ) => true

Did you get the correct answers?

Page 20: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

ConditionalsConditionals if statement

Three basic formats,if (expression){

statement …}if (expression) {

statement … }else{

statement … }

Page 21: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

if (expression) {statement…

} else if (expression) {

statement… } else{

statement… }

Page 22: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

An exampleif(score >= 90){

a_cnt ++;}else if(score >= 80){

b_cnt++;}else if(score >= 70){

c_cnt++;}else if (score>= 60){

d_cnt++}else{

f_cnt++}

Page 23: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

The switch statementswitch (expression) {

case item1: statement; break;

case item2: statement; break;

default: statement; break;

}

Page 24: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

LoopsLoops for statement

for (expression1; expression2; expression3){statement…

} expression1 initializes; expression2 is the terminate test; expression3 is the modifier;

Page 25: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

An exampleint x;for (x=0; x<3; x++) {

printf("x=%d\n",x); }

First time: x = 0;Second time: x = 1;Third time: x = 2;Fourth time: x = 3; (don’t execute the body)

Page 26: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

The while statementwhile (expression) {

statement …}while loop exits only when the expression is false.

An exampleint x = 3; while (x>0) {

printf("x=%d n",x); x--;

}

Page 27: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

for <==> whilefor <==> while

for (expression1; expression2; expression3){

statement…

}

expression1;while (expression2){statement…;expression3;}

equals

Page 28: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Arrays & StringsArrays & StringsArrays

int ids[50];char name[100];int table_of_num[30][40];

Accessing an array

ids[0] = 40;i = ids[1] + j;table_of_num[3][4] = 100;Note: In C Array subscripts start at 0 and end one less than the array size. [0 .. n-1]

Page 29: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

StringsStrings are defined as arrays of characters.The only difference from a character array is, a symbol “\0” is used to indicate the end of a string.

For example, suppose we have a character array, char name[8], and we store into it a string “Dave”.Note: the length of this string 4, but it occupies 5 bytes.DD aa vv ee \0\0

Page 30: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

FunctionsFunctionsFunctions are easy to use; they allow complicated

programs to be broken into small blocks, each of which is easier to write, read, and maintain. This is called modulation.

How does a function look like?

returntype function_name(parameters…)    

{  

local variables declaration;  

function code;

return result;  

}

Page 31: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Sample function int addition(int x, int y)

{int add;add = x + y;return add;

} How to call a function?

int result;int i = 5, j = 6; result = addition(i, j);

Page 32: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

PointersPointersWhat is a pointer?A pointer is a variable which contains the

address in memory of another variable.

In C we have a specific type for pointers.

Page 33: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Declaring a pointer variableint * pointer;

char * name; How to obtain the address of a variable?

int x = 0x2233;pointer = &x; where & is called address of operator.

How to get the value of the variable indicated by the pointer?int y = *pointer;

Page 34: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

3333 2222 0000 0000

0x5200 0x5203

0x5200

pointer

What happens in the memory?

Suppose the address of variable x is 0x5200 in the above example, so the value of the variable pointer is 0x5200.

X

Page 35: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

swap the value of two swap the value of two variablesvariables

Page 36: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Why is the left one not Why is the left one not working?working?

swap

main

x, y

a, b

call swap(a, b) in main

x, y, a, b are all local variables

Page 37: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Why is the right one Why is the right one working?working?

Page 38: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Pointers and ArraysPointers and arrays are very closely linked in C. Array elements arranged in consecutive memory locations

Accessing array elements using pointersint ids[50];int * p = &ids[0];p[i] <=> ids[i]

Pointers and StringsA string can be represented by a char * pointer.

Page 39: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Char name[50];name[0] = ‘D’;name[1] = ‘a’;name[2] = ‘v’;name[3] = ‘e’;name[4] = ‘\0’;char * p = &name[0];printf(“The name is %s \n”, p);Note: The p represents the string “Dave”, but not

the arrayname[50].

Page 40: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Command-Line ArgumentCommand-Line Argument

In C you can pass arguments to main() function.

main() prototypeint main(int argc, char * argv[]);argc indicates the number of argumentsargv is an array of input string pointers.

How to pass your own arguments? ./hello 10

Page 41: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

What value is argc and argv?Let’s add two printf statement to get the value of argc and argv.#include <stdio.h>

int main(int argc, char * argv[]);) {

int i=0;printf("Hello World\n"); printf(“The argc is %d \n”, argc);for(i=0; i < argc; i++){ printf(“The %dth element in argv is %s\n”, i,

argv[i]); }return(0);

}

Page 42: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

The output The argc is 2

The 0th element in argv is ./hello

The 1th element in argv is 10

The trick is the system always passes the name of the executable file as the first argument to the main() function.

How to use your argument? Be careful. Your arguments to main() are always in

string format.

Taking the above program for example, the argv[1] is string “10”, not a number. You must convert it into a number before you can use it.

Page 43: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Data StructureData StructureA data structure is a collection of one or more variables,

possibly of different types.

An example of student record

struct stud_record{

char name[50];

int id;

int age;

int major;

……

};

Page 44: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

A data structure is also a data typestruct stud_record my_record;struct stud_record * pointer;pointer = & my_record;

Accessing a field inside a data structuremy_record.id = 10; “.”

or pointer->id = 10; “->”

Page 45: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Memory AllocationMemory AllocationStack memory allocation

Non-static local variable is an example of stack memory allocation. Such memory allocations are placed in a system memory area called the stack.

Static memory allocationStatic local variable and global variable require static memory allocation. Static memory allocation happens before the program starts, and persists through the entire life time of the program.

Page 46: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Dynamic memory allocationIt allows the program determine how much memory it needs at run time, and allocate exactly the right amount of storage.

The region of memory where dynamic allocation and deallocation of memory can take place is called the heap.

Note: the program has the responsibility to free the dynamic memory it allocated.

Page 47: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Memory arrangementMemory arrangement

Page 48: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Functions for the dynamic memory allocation

void *malloc(size_t number_of_bytes);

allocates dynamic memory

size_t sizeof(type);

returns the number of bytes of type

void free(void * p)

releases dynamic memory allocation

An example of dynamic memory allocation

int * ids; //id arrays

int num_of_ids = 40;

ids = malloc( sizeof(int) * num_of_ids);

…….. Processing …...

free(ids);

Page 49: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Allocating a data structure instancestruct stud_record * pointer;pointer = malloc(sizeof(struct stud_record));pointer->id = 10;

Never calculate the size of data structure yourself. The reason is the size of data types is machine-dependent. Give it to sizeof() function.

size of intsize of int

32-bytes machines32-bytes machines 3232

64-bytes machines64-bytes machines 6464

Page 50: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Programming TipsProgramming Tips Replacing numbers in your code with macros

- don’t use magic numbers directly#define MAX_NAME_LEN 50;char name[MAX_NAME_LEN];

Avoiding global variables - modulation is more important

Giving variables and functions a nice name- a meaning name

Don’t repeat your code - make a subroutine/function

Don’t let the function body to exceed one screen- hard to debug

Page 51: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

Indenting your code (clearance)if(expression){

if(expression){

……}

}Commenting your codeDon’t rush into coding. Plan first. Printing out more debugging information

Page 52: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

C C vvs. C++s. C++C++ is a superset of CC++ has all the characteristics of

C

Page 53: Hello World Program The source code #include int main() { printf("Hello World\n"); return(0); }

ThanksThanks