C/C++ Programming on Hobbes(Unix) Omar Haque Csci 169 Spring 2003.

46
C/C++ Programming on Hobbes(Unix) Omar Haque Csci 169 Spring 2003

Transcript of C/C++ Programming on Hobbes(Unix) Omar Haque Csci 169 Spring 2003.

C/C++ Programming on Hobbes(Unix)

Omar Haque

Csci 169

Spring 2003

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

TA Information

• Name: Omar Haque

• Email: [email protected]

• Office Phone: not ready

• Office Room: not ready

• Office Hours: Tuesday 1pm –3pm

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Open Lab

• Tuesday – Han Young will run the lab– I will be there to help out

• Friday– Semi lecture in lab– Help on class wide problems

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

ANSI

• American National Standards Institute

• 1990 approved standard for C

• 1997 approved standard for C++

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

First C Program

/*Comment*/

#include <stdio.h> /*standard input/output header file*/

main()

{

/*declarations*/

int number1, number2;

number2 = 5;

printf("Enter a number\n");

scanf("%d", &number1);

printf("Number 1 is %d\n", number1);

printf("Number 2 is %d\n", number2);

return 0;

}

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Compiling and Execute C Program

• % gcc filename.c –o outputfile– GNU C compiler– Preprocess, compile, link

• % ./outputfile

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

First C++ Program

//comment

#include <iostream.h>

int main ()

{

//declarations

int number1, number2;

number2 = 5;

cout <<"Enter Number 1 ";

cin >> number1;

cout << "Number 1 is "<< number1 << endl;

cout << "Number 2 is "<< number2 << endl;

return 0;

}

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Compile and Execute C++

• % CC hello.cpp –o outputfile– Sun C++ compiler

• % g++ hello.cpp –o outputfile– GNU C++ compiler

• % ./outputfile

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Comments

• C requires comments to be delimited by /* and */

• C++ allows // for one line comments

• C++ also allows /* */

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Variables, Identifiers

• Variable – piece of memory that is used to hold a value

• Identifiers:– Combination of letters, digits, and underscores– Variable names should start with letter or digit

• C and C++ are case sensitive

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Data Types

• char - 1 byte = 8bits

• int – (system dependent)– short 2 byte– long 4 byte

• float – 4 byte

• double – 8 byte

• bool – 1 byte (only in C++)

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

More on Variables

• Declaration – – int number1;– float number2;

• Initialization –– int number1 = 0;– int number2 = 3.3;

• Assignment-– number1=5;– number2=number1;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Variable Scope

• Global Variables – variables that are declared above main() can be accessed anywhere after the declaration

• Local Variables – variables declared in section of code {}. Only accessible in that region.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Characters and Strings

• ‘a’ is a character• “sfsddsfsf” is a string• In C and C++ a string a char[]

char name[]=“Omar”;printf(“My name is %s\n”, name);

• \n is used for newline• %s shows that a parameter for printf is a

string

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Characters and Strings in C

• Converting a char to an intInt a;

A=atoi(“45”);

• Similar function atof() for floating point.

• Reading input from keyboard with scanf()char string1[20];

printf(“Enter a string:\n”);

scanf(“%s, string1);

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Copying Strings

• Copy entire string using strcpy()char a[] = “Computer”;

char b[25];

strcpy(b,a);

• Copy part of string using strncpy()strncpy(b,a,4);

b[4] =‘\0’;

• ‘\0’ is used as NULL character

• Strcar() and Strncat() to append strings.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Comparing Strings

• See if 2 strings are the same with strcmp()– Strcmp(s1,s2)– Returns 1 if equal

• Compare part of strings using strncmp()

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Formatting Output

• Inside of printf(“ ”); you can use escape characters like \n;– \t move to tab– \r carriage return– \f move cursor to next page

• These are called escape sequences

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Formatting Input

• In scanf(“ “, variablename); we can specify the type of input like %s;– %d or %I for integer– %c char– %s char array or string

• These are called conversion specifiers

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Constants

• #define PI 3.14159265

• The preprocessor reads any line that begins with a #.

• Declaring a constant– Const zero 0;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Arithmetic Operators

• + addition

• - subraction

• * multiplication

• / division

• % modulo or remainder

• As in javaa = --b;

a = b++;

a++;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Relation Operators

• == Equal

• != Different

• > Greater than

• < Less than

• >= Greater or equal than

• <= Less or equal than

• Relation Operators return type bool (true or false) in C++

• In C they return an int; 1 for true and 0 for false;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

C++ I/O

• C++ has a different way of hanlding input and output, using the iostream C++ library

cout << “Omar”;

cout << Omar << lastname << “ is me\n”;

• Input using cinint number;

cin >> number;

cout << number << endl;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Control structures

• if (cond) state1 else if (cond2) state2 else state3• while (expression) statement• do statement while (cond)• for (init; cond; increment) statement;

• Use break, continue and goto to jump around the code.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Switch Statement

switch (x) { \

case 1:

cout << "x is 1";

break;

case 2:

cout << "x is 2";

break;

default:

cout << "value of x unknown";

}

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Functions

• We can use functions to achieve structured programmingInt add(int a, int b){

a = a+b; return (a);

}

• ‘int’ is the return type, ‘a’ and ‘b’ are arguments• When we call the function we must pass it

parameters matching the arguments

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Passing Parameters

• Call By Value– This is what we usually do, we pass a function

the value of a variable

• Call By Reference– Instead of the value we will pass a pointer to

the variable. If we modify the passed variable the change will be seen by the caller

– We use ‘&parm’ to show that we are passing the variable at the memory location of parm

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Arrays

• Intialization– int numbers[5]={0,1,2,3,4,};

• Accessing– num2 =numbers[1];– numbers[0]=99;

• Passing arrays as parameters– Declaration: int add(int numarray[])– Call:

int array[]={1,2,3};add(array);

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Pointers

• We used pointers in call by reference

• Valuable in implementing data structures

• Referencing– by a variable name is called a direct

reference.– Through a pointer is called indirection (*)

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Indirect Referencing

int number=5;

int *numberPtr;

• Number directly referencing a variable whose value is 5;

• numberPtr indirectly referencing the value.• Initialize pointers when they are declared.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Address Operator

• The ‘&’ operator returns the ‘address of’ its operand.

int num=5;

int* numPtr;

numPtr = &y;

• So numPtr set to the address of y;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

More on Pointers

• The two operators & and * are complements• Given:

Int num;Int *numPtr;numPtr =&num

• Then:– &*numPtr is same as &*numPtr;– The value of num can be accessed using ‘num’ or

‘numPtr’– The address of num can be accessed using ‘&num’ or

‘numPtr’– Conversion specifier for pointers is ‘%p’

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Sizeof()

• The Sizeof() function is used to determine how many bytes of a data type during compilation.

• Ex:sizeof(float) equals 4

float array[10];

sizeof(array) equals 4*10 which is40

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Dynamic Memory

• Dynamic Memory allows us to determine and allocate memory to variables and data structures at ‘run time’.

• C++ uses new and delete;– pointer = new type;

• New returns a pointer to the allocated memory

– delete pointer;• Frees up the memory that was allocated

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Dynamic Memory in C

• C does not use new and delete• It uses malloc(), free(), etc… found in

stdlib.h ANSI C library• pointer = (type cast) malloc(nbytes);

Int* numPtrnumPtr =(int*) malloc(sizeof(int));

• free(pointer) releases the allocated memory

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Structs

• Similar to records in Ada.struct person_t{

char fname[20];char lname[20];int age;

}person1, person2;

• Here we are declaring person1 and person2 as type person_t.

• By convention we use the _t

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Accessing the struct members

• We use the ‘.’ to access members of a structcout << person1.fname;

person1.fname=“John”;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

What about Pointers to Structs

• We can point to a struct like other structures.Person_t* person1Ptr;

person1Ptr = &person1;

• We can no longer use the ‘.’ to access the members in the struct we are pointing to.– The ‘->’ is used

Cout << person1Ptr->fname;

– Element fname of structed pointed by person1Ptr

– Same as *(person1Ptr.fname);

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Other Types

• Defining your own types can be done using typdef– Typedef existing_type new_type;

• Unions allow the same portion of memory to be accessed as different data types;

• Enum is like Enumeration Types in Ada– When you grouped the months or days together

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

C++ Classes

• C++, not C, has the ablity to create classes which is similar to Java, using class

• Classes can contain data and functions

• Members of the class can be private, protected or public.– Protected members are only accessible by

friend classes.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Class Example from cplusplus.com

class CRectangle { int width, height; public: CRectangle (int,int); int area (void) {return (width*height);}

};CRectangle::CRectangle (int a, int b) {

width = a; height = b; }

int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; }

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

More on Classes

• Destruct is automatically called if it is definedCRectangle::~CRectangle () { delete width; delete height; }

• You can overload constructers, each with diff parameters. – When you declare a new class instance,

using a constructor with no parameters then don’t use parethesis.• MyClass aclass;

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Little More on C++

• C++ allows for operator overloading• Unlike Java, C++ allows for multiple

inheritance. – A child can have 2 parents

• The keyword this works like it does in Java

• Templates, Namespaces, Friend later in the semister.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

Header Files

• .h files are strictly convention,• Anything in these files can be put in .c

or .cpp files• Usually in the header file we put variable

definition,library includes, function prototype(its sign), constants, typdefs.

• Header files separate implementation for interface like (.ads and .adb in Ada)

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

C Concepts

• Scope is basically top down

• Everything in C is a function

• Relies heavily on programmers’ conventions

• Physical modularity through the file and logical through the functions.

Omar Haque | C/C++ on Hobbes (Unix) | Csci169 | Spring 2003

C++ Concepts

• Proper subset of C

• Classes allow for large scale programming and encapsulation.

• Templates support generic programming

• Class is unit of logical modularity.