c programming getting started getting started hello world hello world data types and variables data...

Post on 31-Mar-2015

229 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

C Programming

Getting Started Hello World Data types and variables main() I/O routines

Program Module Basics of C Programming Advanced C Programming

Hello World#include <stdio.h> Header file for I/O routines

int main() Main entry point for all C programs{ Start of function body printf(“Hello World\n”); Display the message Hello World on screen return 0; Exit code for program (0 means no error)} End of function body

Above is the first program a student will write in any programming language. It illustrates some of the basics that must be mastered to write a program. Note that each line is terminated with a semicolon (;) and that the function body is enclosed is a set of matching braces {}. These are key features of the syntax of the C language.

Data Types

Simple Data Types char single byte used for character

& strings int integer default 4 bytes float single precision floating point double double precision floating point

Complex Data Types struct unions enum

Data Constants integer

123 +123 -123

floating point 1.23 -1.23e+11 -1.23×1011

4.56e-8 4.56×10-8

character ‘a’ lower case a – note use of single quote ‘ char(43) plus sign +

string “this is a string” note strings are enclosed in double

quotes “ “a” this is a string containing the single character a

not a single character constant (see above for a character constant)

Variable Declaration

All variables must be declared prior to their use. Variables must have a type. In C, all tokens are case sensitive id, ID and Id are three different tokens.Examples:

int i, j, k;float x, y;double a, b, c;

Variable Initialization

int n=10; float pi=3.141592654; char oper=‘+’; struct {

char suit, rank;} card = {0,11};

char vowels[5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};

main()

The function main() is the entry point for all C programs. Every program must have exactly one function called main. Typically this is the first function listed in a file. All actions performed by the program must be initiated from main or a function that main invokes. The function declaration for main should be:

int main()

I/O Routines Output

printf(fmt, val_list); fprintf(FILE, fmt, val_list); fwrite(buffer, size, count, FILE);

Input scanf(fmt, var_list); fscanf(FILE, fmt, var_list); gets(); fread(buffer, size, count, FILE);

C Program ModuleHeader Files

External files containing additional data types, variables and functions.

Data Type DefinitionsApplication specific data types

Function PrototypesDeclaration of function type, name, list of argument name and type.

Variable DeclarationsGlobal - available externallyStatic - available internally

Function BodiesCode for each declared function

Header Files

Data Type Declarations Function Prototypes Global Variable Reference

Example:#include <stdio.h>

Data Type DefinitionsDeclare new data types to make your code more readable and flexible. A new data type begins with a typedef keyword then is followed by the definition.Example

typedef struct {byte suit;byte rank;

} cardtype;

In the above we have defined a new data type called cardtype. We can use this to declare new variables of this type.Example

cardtype card, deck[52];

Function Prototypes

Declaration of function type, name, list of argument name and type.type fName(arg_list);

arg_list: type vName, …

Examplevoid deal(cardtype *hand, int numCards);

Variable Declarations

Declare both global and local variables.

Examplestatic int currCard; Local variable available only in file

cardtype deck[52]; Global variable available in any file

Functions Function Declaration Body

Examplevoid deal(cardtype *hand, int NumCards){

int i;for (i=0; i < NumCards; i++) hand[i] = deck[currCard++];

}

Function Declaration

Function Body

Basics of C Programming

C programs consists of a series of statements that perform the necessary calculations to accomplish the intended process. Statements may be grouped together inside a set of matching braces {}. Statements enclosed within these braces are called a statement block and are treated as a single statement.

Statements Assignment

card = hand[topCard]; I/O

printf(“Slope = %f\n”, m); Branching

if (x != 0) y=5.0/x; switch (oper) {

Loops while (*x != 0) printf(“%f\n”, *x++); do {} while(cond);

Assignment Statements

Assignment statements are of the formvar = expr;

Where var is the variable to be assigned the value of expr. The expression expr is a combination of variables, constants and operators.

Operators

Arithmetic + Addition 12+5→17 - Subtraction 12-5→7 * Multiplication 12*5→60 / Division 12/5→2 % Modulo 12%5→2 = Assignment

Increment ++ Suffix ++ Prefix

Decrement -- Suffix -- Prefix

x is 4 y=++x, both x & y will be 5

Operators

x is 4 y=x++, y is 4 & x is 5

x is 4 y=x--, y is 4 & x is 3

x is 4 y=--x, both x & y will be 3

Operators Bitwise

~ Ones Complement ~0110→1001

& And 0110&1010→0010

| Or 0110|1010→1110

^ Exclusive Or 0110^1010→1100

>> Shift Right 0110>>1→0011

<< Shift Left 0110<<1→1100

Operators Compound Assignment

+= a += b a=a+b

-= a -= b a=a-b

*= a *= b a=a*b

/= a /= b a=a/b

%= a %= b a=a%b

&= a &= b a=a&b

|= a |= b a=a|b

^= a ^= b a=a^b

<<=a <<= b a=a<<b

>>=a >>= b a=a>>b

BranchingIf Statement

if (cond) stmt;else stmt; Optional else clause

Exampleif (hand.cards[i].rank == 1) { naces++; val++;} else if (hand.cards[i].rank <= 10) { val += hand.cards[i].rank;} else { val += 10;}

BranchingSwitch Statementswitch (expr) { case const: default: Optional default

}Jumps to case where the value of expr matches const. Jumps to default if no match is found. Will execute code in subsequent case statements unless a break statement is encountered.

Exampleswitch(oper) { case ‘-’: val2 = -val2; falls thru to next

case ‘+’: res = val1 + val2; break; drops out of switch

case ‘*’: res = val1 * val2; break; case ‘/’: res = val1 / val2; break; default: printf(“Unknown operator\n”);}

Operators Relational

== Equals != Not Equals > Greater than >= Greater than or Equal < Less than <= Less than or Equal

Logical ! Not !a returns 1 if a is 0 otherwise returns 1

&& And a&&b returns 1 if both a and b are not 0, otherwise returns 0

|| Or a||b returns 0 if both a and b are 0, otherwise returns 1

PointersA pointer is a variable whose value is a memory address. It specifies where to find a memory location, but does not return the value of the memory location. A pointer may be dereferenced to obtain the value of the memory location.Example:

float x, *xp; declare a floating point variable (x) and a pointer to a floating point variable (xp)x=3.0; assign the value 3 to xxp=&x; assign the address of x to xpprintf(“The value at %x is %f\n”, output the address of x and its value xp, *xp); outputs The value at 12ff00 is 3.000000

PointersThere are four main uses of pointers Passing a value to a function by

reference so that the value of the variable may be changed

Accessing elements of an array Dynamic execution using function

pointers Dynamic allocation of variables

An array is a contiguous region of memory containing equal sized blocks. Each block is called an element. Think of an array as apartment cluster mailbox. EachMailbox in the cluster is an element. The contents of the mailbox is the value of the element. The apartment number on the mailbox is the address. Arrays are 0 based, i.e., the first element is index 0. If the array is named a then a[4] refers to the value of the 5th element of the array (contents of the mailbox). The expression a+4 refers to the address of the 5th element of the array (the apartment number).

Arrays

Array Declarations

Arrays are declared by specifying a type and a number of elements, i.e., type var[num]Examples:

int order[10];double x[100];cardtype deck[52];

Arrays are initialize by following the declaration by a list:

int order[10] = {1,2,3,4,5,6,7,8,9,10};

Arrays may also be initialized by using a for loop:

double x[100];int i;for (i=0; i < 100; i++) x[i] = 0.0;

Array Operators

a[n] returns value of n+1st element in array a[3]4n is called the index

*a returns value of address pointed to by a *a1same as a[0]

a+n returns the address of the n+1st elementsame as &a[n]

*(a+n) returns value of n+1st element in array *(a+2)3

same as a[n]

Array a

Index Value

0 1

1 2

2 3

3 4

4 5

n-1 10

StructuresUser defined data type grouping other data types into a single data type. Members occupy contiguous memory locations. In the example below a struct is defined with 3 members: name, id and exams all grouped together as a single variable student.Example:

struct { char name[80], id[10]; int exams[10];} student;

student

name

id

exams

UnionsUser defined data type grouping other data types into a single data type. All members occupy the same memory location. In the example below a union is defined with 3 members: oper, var and val grouped together as a single variable token. Changing the value of any one member changes the value of all members.Example:

union { char oper; int var; float val;} token;

token

oper var val

Member & Pointer Operators s.b returns the value of member b in struct s

s.b2

sp->c returns the value of member c in pointer sp.

Same as (*sp).c sp->c3

&s returns the address of s

*sp returns the value of the memory address sp

typedef struct { int a, b, c;} stype;stype *sp, s = {1, 2, 3};sp = &s;

top related