1-1 An Introduction to C Muhammed Al-Mulhem Jan. 2008.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

C Language.
Programming and Data Structure
Programming Languages and Paradigms The C Programming Language.
Structures Spring 2013Programming and Data Structure1.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Review for Final Exam Dilshad M. NYU. In this review Arrays Pointers Structures Java - some basic information.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
C For Java Programmers Tom Roeder CS sp. Why C? The language of low-level systems programming  Commonly used (legacy code)  Trades off safety.
1 CSSE 332 Preprocessor, Array and Strings. 2 External library files libname.a or libname.so Special functionality is provided in the form of external.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Why learn C (after Java)? Both high-level and low-level language Better control of low-level mechanisms Performance better than Java Java hides many details.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Pointers CSE 2451 Rong Shi.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C Tokens Identifiers Keywords Constants Operators Special symbols.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Pointers Programming Applications. Pointer A pointer is a variable whose value is a memory address representing the location of the chunk of memory on.
Representing Strings and String I/O. Introduction A string is a sequence of characters and is treated as a single data item. A string constant, also termed.
Review 1 List Data Structure List operations List Implementation Array Linked List.
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Pointers PART - 2. Pointers Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer.
Structures and Union. Review bitwise operations –you need them for performance in terms of space and time –shifts are equivalent to arithmetics enumeration.
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Structure A collection of values (members) struct date{ int day; char month[10]; int year; }; Declare a structure variable struct date today; struct struct_name.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
Advanced Programming Constants, Declarations, and Definitions Derived Data Types.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
Chapter 7: User-Defined Functions II
Computer Science 210 Computer Organization
C Programming Tutorial – Part I
Functions and Structured Programming
Day 02 Introduction to C.
Pointers.
C programming language
Module 2 Arrays and strings – example programs.
Computer Science 210 Computer Organization
Lecture 18 Arrays and Pointer Arithmetic
Programming Languages and Paradigms
Variables in C Topics Naming Variables Declaring Variables
C Language B. DHIVYA 17PCA140 II MCA.
Presentation transcript:

1-1 An Introduction to C Muhammed Al-Mulhem Jan. 2008

1-2 Goals of this tutorial To introduce the basics of imperative programming using the C programming language To prepare you for basic imperative programming To prepare you for better understanding of the other parts of the course

1-3 Overview Basic types in C Some simple programs Format specifiers More example programs

1-4 C Programs: General Form preprocessor directives int main(){ variable declarations; statements; } Example: #include int main(){ int x = 1; printf(“Salaam Shabab\n”); printf(“This is program %d\n”, x); return 0; }

1-5 Basic Data Types (some) int char double short Basic pointer types (associated with each basic type)

1-6 Format Specifiers (some) Variable typeConversion Specifiers char %c Int%d Float%f Double%lf String%s

1-7 Format Specifiers (some) #include int main(){ char ch = 's'; int i = 3; float f = 3; char *name = "ICS 410"; printf("Your values are:\n"); printf("A char: %c\n", ch); printf("A char: %d\n", ch); printf("An int: %d\n", i); printf("A float: %f\n", f); printf("A string: %s\n", name); printf("Mixed: %f\t%d\t%c\n", i,f,ch); return 0; } Your values are: A char: s A char: 115 An int: 3 A float: A string: ICS 313 Mixed: s

1-8 Operators Arithmetic int i = i+1; i++; i--; i *= 2; +, -, *, /, %, Relational and Logical, =, ==, != &&, ||, &, |, ! Control structure if ( ) { } else { } while ( ) { } do { } while ( ); for(i=1; i <= 100; i++) { } switch ( ) {case 1: … } continue; break;

1-9 Example #include #define DANGERLEVEL 5 /* like Java ‘final’ */ int main() { float level=1; if (level <= DANGERLEVEL) printf(“Low on gas!\n”); else printf(“Good driver !\n”); return 0; }

Part - II

1-11 Overview Introduction to pointers Arrays and pointers Strings in C Pointers as function parameters

1-12 Pointers in C: An Introduction A pointer is an address in memory of some ordinary data There is a pointer type associated with every type Example 1: #include int main(){ int x = 1; int *xp; xp = &x; printf(“x = %d\n”, x); printf(“*xp = %d\n”, *xp); return 0; }

1-13 Pointers: A Pictorial View float f; float *fp; ?? f fp ? any float any address ?4300 f fp fp = &f;

1-14 Pointers: A Pictorial View (cont’d) *fp = 3.2; /* indirection operator */ f fp f fp float g=*fp; /* indirection: g is now 3.2 */ f = 1.3;

1-15 Example 2:Dereferencing Pointers #include int main(){ int i=3, j=7, *ip; ip = &i; *ip = 5; ip = &j; *ip += 11; i += *ip; printf("i = %d\n", i); printf("j = %d\n", j); printf("*ip = %d\n", *ip); return 0; }

1-16 Example 3: Pointer Compatibility #include int main(){ int x = 3, *xp, *xp2; float f = 7, *fp; void *vp; /* generic pointer: no arithmetic no dereferencing */ xp = &x; fp = &f; fp = xp; vp = xp; fp = vp; xp2 = vp; (*xp)++; printf("x = %d\n", *xp); printf("*vp = %d\n", *fp); printf("*vp = %d\n", *xp2); return 0; }

1-17 Arrays and Pointers Arrays in C are not objects: no methods, no ‘length’ field The name of an array is a constant pointer

1-18 Example 4: Arrays and pointers #include int main(){ int i, j, *ip, myArray[5] = {2,3,5,7,11}; ip = &myArray[2]; for(i= 0; i<5; i++) printf("myArray[%d] = %d\n", i, *(myArray+i)); *(ip+1) = 4; *(ip-1) += 11; j = *(ip-2); for(i=0; i<5; i++) printf("myArray[%d] = %d\n", i, *(myArray+i)); printf("j = %d\n", j); return 0; }

1-19 Example 5: Dynamic Arrays #include int main(){ int i, j, size, *ip, *myArray; printf("Enter array size:"); scanf("%d", &size); myArray = (int *)malloc(size*sizeof(int)); printf("Enter the %d elements (separated by space: ",size); for(i=0;i<size; i++){ scanf("%d", myArray+i); } ip = &myArray[2]; *(ip+1) = 4; *(ip-1) += 11; j = *(ip-2); for(i=0; i<5; i++) printf("myArray[%d] = %d\n", i, *(myArray+i)); printf("j = %d\n", j); return 0;

1-20 Example 6: File I/O #include int main(){ int i,n,hours; long id; float rate, wage; char name[50], n2[50]; FILE *inputFile, *outputFile; inputFile = fopen("employeeData.txt","r"); outputFile = fopen("employeeWage.txt","w"); if (inputFile) printf("File succesfully opened for reading!\n"); else { printf(“File not opened\n”); exit(1); }

1-21 Example 6: File I/O printf("How many employees do you have>"); scanf("%d", &n); for(i=0;i<n;i++){ fscanf(inputFile, "%[0-9]%[^0-9]%d%f", &id,name,&hours,&rate); wage = hours*rate; fprintf(outputFile, "%ld\t%d\tSR%5.2f\t\tSR%5.2f\n", id,hours,rate,wage); } fclose(inputFile);fclose(outputFile); return 0; }

1-22 Strings in C Java strings are objects of class java.lang.String or java.lang.StringBuffer, and represent sequences of characters Strings in C are just arrays of, or pointers to, char Functions that handle strings typically assume that strings are terminated with a null character ‘\0 ’, rather than being passed a length parameter Utilities for handling character strings are declared in. For example: strcpy, strncpy, strcmp, strncmp, strcat, strncat, strstr,strchr

1-23 Example 7: Strings in C #include int main(){ char name[] = {'i', 'c', 's', ‘4', '1', ‘0', '\0'}; char *dept = "ICS, KFUPM"; int i = 0; printf("Course name = %s\n", name); for(; i<6; i++) printf("%c", *(name+i)); printf("\n"); for(i=0; i<10; i++) printf("%c", *(dept+i)); printf("\n"); return 0; }

1-24 Example 8: Strings Processing #include int main() { char first[80], second[80]; printf("Enter a string: "); gets(first); strcpy(second, first); printf("first: %s, and second: %s\n", first, second); if (strcmp(first, second)) puts("The two strings are equal"); else puts("The two strings are not equal"); return 0; }

1-25 Pointers and Functions What is the parameter passing method in Java? Passing arguments to functions –By value –By address Returning values from functions –By value –By address

1-26 Example 9:Pass By Value #include int sum(int a, int b); /* function prototype at start of file */ int main(){ int a=4,b=5; int total = sum(a,b); printf("The sum of 4 and 5 is %d\n", total); return 0; } int sum(int a, int b){ /* function definition */ return (a+b); }

1-27 Example 10: Pass By Address #include int sum(int *a, int *b); int main(void){ int a=4, b=5; int *ptr = &b; int total = sum(&a,ptr); printf("The sum of 4 and 5 is %d\n", total); return 0; } int sum(int *pa, int *pb){ return (*pa+*pb); }

1-28 Example 11: Pass By Value #include void swap(int, int); int main() { int num1 = 5, num2 = 10; swap(num1, num2); printf("num1 = %d and num2 = %d\n", num1, num2); return 0; } void swap(int n1, int n2) { /* passed by value */ int temp; temp = n1; n1 = n2; n2 = temp; printf("num1 = %d and num2 = %d\n", n1, n2); }

1-29 Example 12: Pass By Address #include void swap(int *, int *); int main() { int num1 = 5, num2 = 10; swap(&num1, &num2); printf("num1 = %d and num2 = %d\n", num1, num2); return 0; } void swap(int *n1, int *n2) { /* passed and returned by reference */ int temp; temp = *n1; *n1 = *n2; *n2 = temp; printf("num1 = %d and num2 = %d\n", *n1, *n2); }

1-30 One-Dimensional Arrays #include int main(){ int number[12]; int index, sum = 0; /* Always initialize array before use */ for (index = 0; index < 12; index++) { number[index] = index; } for (index = 0; index < 12; index = index + 1) { printf("number[%d] = %d\n", index,number[index]); sum += number[index]; } printf("The sum is: %d\n", sum); printf("The sum is: %d\n", number[12]); return 0; }

Part - III

1-32 Overview Storage classes Structures –Type aliasing via typedef –enum types –struct types –union types

1-33 Storage Classes: An Introduction For any variable declared in a program (e.g., int x = 11;), the compiler is told the following information about the variable: its –type (preceded by an optional qualifier, e.g., long int x;) –name –cell size (with an implicit address) –storage class A storage class indicates the degree of the life span of a variable. A variable can either have an extern, an auto, a register or a static storage class. A register, auto and a local static variable has a temporary, local scope. A global extern and a global static variable has a permanent, global scope.

1-34 Storage Classes: An Introduction In functions other than main(), make a variable static if its value must be retained between calls to the function. If a variable is used by most or all of the program's functions, define it with the extern storage class. auto is the default storage class for local variables. auto can only be used within functions, i.e. local variables. register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary `&' operator applied to it (as it does not have a memory location). register should only be used for variables that require quick access - such as counters.

1-35 Storage Classes: An Introduction static is the default storage class for global variables. static can also be defined within a function. If this is done, the variable is initialized at compilation time and retains its value between calls. Because it is initialized at compilation time, the initialization value must be a constant. extern defines a global variable that is visible to ALL object modules. An extern variable cannot be initialized because all extern does is point the variable name at a storage location that has been previously defined.

1-36 Example 1: Storage Classes #include int x = 71; /* Equivalently, static int x = 71; */ void func1(void) { extern int x; /* Illegal to initialize! */ printf("In func1(), x = %d\n", x); } int main() { auto x = 23; /* Equivalently, auto int x = 23; */ printf("In main(), x = %d\n", x); func1(); return 0; }

1-37 Example 2: Storage Classes #include void func1(void); /* function declaration */ static count=10; /* Global variable - static is the default */ main() { while (count--) func1(); return 0; } void func1(void) { /* 'x' is local to 'func1' - it is * only initialized at run time. Its value * is NOT reset on every invocation of * 'func1' */ static x=5; x++; printf(" x is %d and count is %d\n", x, count); }

1-38 Example 3: Storage Classes #include char *f(void); int main() { char *result; result = f(); printf("%s",result); return 0; } char *f(void) { char name[13]="Amr Ali"; return name; }

1-39 Structures: Motivations Our programs so far used only the basic data types provided by C, i.e., char, int, float, void and pointers. Programmers can define their own data types using structures Structures can be used to conveniently model things that would otherwise be difficult to model using arrays Arrays versus structures: arrays elements and structure components are contiguously laid out in memory arrays are homogeneous, structures can be heterogeneous arrays are passed to functions by reference while structures have to be explicitly passed by reference arrays (of the same type, of course!) cannot be assigned to each other (why?) while structures can array identifiers can be compared while structure identifiers cannot Different structures (in the same program) can have the same component name. A structure component name can also be the same as an ordinary variable name

1-40 Creating Structures: the Tools 1.the typedef specifier 2.the enum specifier 3.the struct specifier 4.the union specifier

1-41 Creating Structures: Examples typedef struct date { int day; int month; int year; } DATE; enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; struct date { int day; int month; int year; }; union mixed { char c; float num; int age; };

1-42 Creating Structures: Examples typedef is a mechanism, which allows a type to be explicitly associated with an identifier. Some examples are typedef char * string; typedef int INCHES, FEET, YARDS; typedef float vector [10]; In each of these type definitions the named identifiers can be used later to declare variables or functions in the same way ordinary types can be used. Thus INCHESlength, width; Strings1 = "abc", s2 = "xyz", vector x;

1-43 Example 4: Structures #include struct date { int day; int month; int year; }; main() { struct date today; today.day = 17; today.month = 11; today.year = 1998; printf("Todays date is %d/%d/%d.\n", today.month, today.day, today.year ); return 0 }

1-44 Example 5: Structures #include struct date {int day, month, year;}; void modify_date(struct date *yaum) { yaum->month = 3; yaum->year = 1999; printf("The date is %d/%d/%d.\n", yaum->day, yaum->month, yaum->year ); } main() { struct date *today; today->day = 16; today->month = 7; today->year = 1998; printf("The date is %d/%d/%d.\n", today->day, today- >month, today->year ); modify_date(today); printf("The date is %d/%d/%d.\n", today->day, today- >month, today->year ); }

1-45 Creating Union A union, like a structure, is a derived type. Unions follow the same syntax as structures but have members that share storage. A union type defines a set of alternative values that may be stored in a shared portion of memory. The programmer is responsible for interpreting the stored values correctly. Consider the declaration union int_or_float { int i; floatf;}; In this declaration union is a keyword, int_or_float is the union tag name, and the variables i and f are members of the union. This declaration creates the derived data type union int_or_float. The declaration can be thought of as a template; it creates the type, but no storage is allocated. The tag name, along with the keyword union, can now be used to declare variables of this type. union int_or_float a, b, c; This declaration allocates storage for the identifiers a, b, and c. For each variable the compiler allocates a piece of storage that can accommodate the largest of the specified members.

1-46 Creating Union Example: tpedef union int_or_float {int i; float f;} number; main ( ) { numbern; n.i = 4444; printf("i: %10df: %16.10e\n", n.i, n.f); n.i = ; printf("i: %10df: %16.10e\n", n.i, n.f); } This little experiment demonstrates how your system overlays an int and a float. The output of this program is system dependent. Here is what is printed on our system: i: 444f: e-41 i: f: e+03