C Programming Basics

Introduction to C Data types in C Variables Type conversions Standard input/output Arithmetic, relational, logical operators Header files and libraries Loops and decisions Scope of variables Strings Functions, call by value, call by reference Arrays Structures Unions Pointers Files

History of C-Language C

Developed by Dennis M.Ritchie and Brian Kernighan of AT&T Bell Labs in 1972 In 1983 the American National Standards Institute began the standardisation process In 1989 the International Standards Organisation continued the standardisation process In 1990 a standard was finalised, known simply as Standard C   

Why teach C? 
    

C is small (only 32 keywords). C is common (lots of C code about). C is stable (the language doesn t change much). C is quick running. running. C is the basis for many other languages (Java, C++, awk, Perl). It may not feel like it but C is one of the easiest languages to learn. NOTE: Obviously programmers will find this course easier than everyone else. BUT, this course is for nonnonprogrammers. If you cannot understand what I say, please please ask me either in the lecture or afterwards. 

Why use C? C is not "safe" It assumes you know what you're doing It has a lot of scope for bugs  It's a good systems programming language Not much is hidden Faster than Java. more predictable performance It has all the low-level operations low- .

C-Language Strengths: 1. C programs can be difficult to understand 3. C programs can be difficult to modify . Efficiency 2. Standard library 6. Power 4. Flexibility 5. C programs can be error-prone 2. Portability 3. Integration with UNIX Weaknesses: 1.

The Benefits And Pitfalls Of C  Benefits  It s a powerful language (doesn t restrict you)  Fast  A practical language (real applications)  Pitfalls  It s a powerful language (No programmer failfail-safes)  Compiled code is not portable .

augmented with loops and branches. The idea of breaking a program into functions can be further extended by grouping functions that perform similar tasks into modules. Fortran are procedural programming languages.Structured Programming        C. Pascal. A procedural program is divided into functions. . ideally each has clearly defined purpose and interface to other functions. Dividing a program into functions and modules is the key idea of structured programming. modules. For small programs no other organizational principle (paradigm) is needed. such that functions. programming. A program in a procedural language is a list of instructions. Larger programs are broken down into smaller units.

h> before compiling) 2. #include <stdio. which translates it into machine instructions (object code). Linking.c ---> (compiled) ---> test.Compiling and Linking 1.obj (linked) ---> executable file . Preprocessing. 3. Compiling. The modified program now goes to a compiler. which obeys commands that begin with # (known as directives).h> (include the info in <stdio. A linker combines the object code produced by the compiler with any additional code needed to yield a complete executable program. The program is first given to a preprocessor. test.

.Some programmer jargon Source code: The stuff you type into the computer. The program you are writing. Library: Added functions for C programming which are bolted on to do certain tasks.h which are included at the start of source code. Language: (Special sense) The core part of C central to writing C code. Compile (build): Taking source code and making a program that the computer can understand. Header file: Files ending in . Executable: The compiled program that the computer can run.

 Compiler: Translates program written in "source" language to "target" language  Interpreter: Translate and immediately execute  Assembler: Translate into machine language for particular machine  Macro Processor: Textual substitutions .Contd .

Keywords In Standard C. Table 2.1 have special significance to the compiler and therefore can not be used as identifiers.1 .Keywords auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while . the keywords in Table 2.

The Format of C       Statements are terminated with semicolons Indentation is ignored by the compiler C is case sensitive . those forgetting to do so have one or other chosen randomly! .all keywords and Standard Library functions are lowercase Strings are placed in double quotes Newlines are handled via \n Programs are capable of flagging success or error.

Variables       Variables must be declared before use immediately after { Valid characters are letters. digits and _ First character cannot be a digit 31 characters recognised for local variables (more can be used. but are ignored) Some implementations recognise only 6 characters in global variables (and function names)! Upper and lower case letters are distinct .

this will be investigated later) .absence will make program very ill & not necessary with printf because current value of parameter is used .printf and scanf     printf writes integer values to screen when %i is used scanf reads integer values from the keyboard when %i is used & VERY important with scanf (required to change the parameter.

c /* Program documentation */ #Preprocessor directives Global constants Global variables Function prototypes int main () { Local variables } Function definitions .The Basic Structure Of A C Program example_program.

c o helloworld .c with the command gcc helloworld. }  Compile the source file helloworld.h> // input-output library inputint main() // function main { printf(´Hello World\n´).Hello World Program #include <stdio. // send string to standard output World\ return 0.

Every C-program must have a function Cnamed main somewhere in the code { .h>  includes the standard I/O library which allows you to read from the keyboard (standard in) and write to the screen (standard out) int main()  declares the main function... return 0..Hello World Program #include <stdio.  This causes the function main to return an error code of 0 (no error) to the shell that started the program. printf(´Hello World\n´) World\  Sends output to the screen. .. The portion in quotes ´. }  The symbols { and } mark the beginning and end of a block of code.´ is the format strings and describes how the data is formatted.

Compilation & Linking header file source file helloworld.o linker executable file helloworld .h> compiler object file helloworld.c stdio.h #include <stdio.

unsigned short. unsigned long . char c.Variable Declaration int b. float. double. long. unsigned int a. long double unsigned char.  C is a typed language that means a variable has a name type  C standard types int. double x. short. char. unsigned int.

Primitive Data-Types Datainteger data-types : char. unsigned char. floating point data-types : float. short. double. int. \n . unsigned short. long. long double character data-type : char character constants in single quotes : a .

4x1038 1.7x10-308 3.7x10308 3.Primitive Data-Types DataType char short int long float double long double Low -128 -32768 -2147483648 -2147483648 3.4x10-38 1.4x104932 Digits of Precision 7 15 19 Bytes 1 2 2 4 4 8 10 .4x10-4932 High 127 32767 2147483647 2147483647 3.

Examples of variable definitions: int a. in the same way one assigns a value to an already defined variable.Variable Definitions A declaration introduces a variable s name into a program and specifies its type A definition is a declaration which also sets asides memory for that variable (which is usually the case) In C it is possible to initialize a variable at the same time it is defined. .9. char answer = ¶n¶. double y=x. double x = 5.

14159 CONVENTION: reserve CAPITAL letters for constants and use small caps for variables and functions .14159 throughout the program the major drawback of #define is that the data type of the constant is not specified the preprocessor merely replaces all occurences of the string PI with 3.14159 the preprocessor replaces the identifier PI by the text 3.Constants constants can be specified using the preprocessor directive #define example: #define PI 3.

Comments comments are always a good thing to use because not everyone is as smart as you are and needs more explanation in order to understand your program you may not be as smart next month when you have to change your program comments should clarify your code and explain the rational behind a group of statements comment syntax (C style) /* */ /* this is a comment which can go across multiple lines of code */ .

/* assigns 17/2 = 8 to y not 8.Type Conversions C is a hard-typed language. /* assigns 17 to x */ int j = 2. /* casts i into float before division */ . Some type conversions occur automatically for example int to float or float to double. meaning that each variable has a fixed type that does not change and which determines the possible assignments and applicable operators double pi=3. float x = i. char c=¶x¶.5 */ Type conversions can be forced by a programmer through a type cast float z = (float) i / j. float y = i/j.14. but also char to int int i = 17.

h> /* include header file for math functions */ int main() { double x.Library Functions Many functionalities in C are carried out by library functions. x=sin(y). data conversion and mathematical computations.57. } . These functions perform file access. #include <math. double y. y=1.

Header Files a header file contains the declaration of functions you want to use in your code the preprocessor directive #include takes care of incorporating a header file into your source file example: #include <math.h> #include ´myprog.h´ the brackets <> indicate that the compiler first searches the standard include directory which contains the standard C header files first the quotation marks indicate that the compiler first searches for header files in the local directory if you do not include the appropriate header file you get an error message from the compiler .

Header and Library Files #include <math.c #include ´myprog.h> myprog.o linker executable file myprog library file libm.h´ library header file math.h compiler object file myprog.h user header file myprog.a .

scanf(³%c´.&c). %c\ } . printf(³\ printf(³\nEnter double:´).x.a. scanf(³%lf´.h> int main() { int a. scanf(³%d´. of x is %lf. printf(³Enter integer:´). double x. printf(³\ printf(³\nThe value of a is %d. of c is %c\n´.c).&a).&x). char c.Input / Output /*Program for print the different data types*/ #include <stdio. printf(³\ printf(³\nEnter character:´).

&a).a). standard output device standard input device stdout printf( %d . variable a stdin scanf( %d . variable a .Input / Output A stream is an abstraction that refers to a flow of data.

Input / Output printf allows you to send output to standard out (screen)  The special character \n represents carriage return line feed  The symbol %d is a placeholder for an integer variable in the format string printf(³the value of a is %d\n´.a) %d\ that will be replaced by the value of the variable a when the printf statement is executed  Placeholders: integer %d long %ld float %f double %lf char %c string %s  .

the reason becomes clear when you learn more about pointers .&a) the program reads an integer value from the keyboard and places its value into the integer variable a Notice to put an & in front of the variable.Input / Output     scanf allows you to read input from standard in (keyboard) scanf uses the same placeholders as printf scanf (³%d´.

b=b+a. /* increment operator. same as a=a+1. same as b=b+3 */ a++. /* prefix operator */ . */ a=b++. /* arithmetic assignment operator. b+=3.Arithmetic and Increment Operators int a=4. int b=3. /* postfix operator */ a=3 * ++b.

10 * i++). /* integer division result 0 */ float x = 1. printf(´%d´.0/3.3333 */ int j = 7 % 3. is equivalent to x=x+3. i has value 4 afterwards */ Printf(´%d´. . // modulo operator remainder of 7/3 prefix and postfix-increment operator ++ int i=3.5. subtraction. int j=7.Arithmetic Operators multiplication. /* outputs 80.5. summation. x+=3. division int i = 1/3. /* outputs 30. j has value 8 afterwards */ arithmetic assignment operators float x=6.10 * ++j). /* floating point division result 0.0.

Instead int is used for boolean expression with the convention that 0 is false.Relational Operators   In C there is no special boolean type. Relational operators > greater < less >= greater or equal <= less or equal == equal. everything else is true. not to be confused with assignment = != not equal .

int y=12. int. where 0 is false and any value different from 0 is true C provides the following relational operators <. float typical relationships are equal to. >.Relational Operators a relational operator compares two values of primitive in data types such as char. (x == y) /* false */ (x >= y) /* true */ (x != y) /* true */ . >= example: int x=44. ==. !=. less than and greater than the result of a comparison is either true or false. <=.

i<15.Loops a loop causes a section of the program to be repeated multiple times while the loop condition remains true C knows three kinds of loops for loop while loop do loop the for loop repeats a code segment a fixed number of times the for statement contains three expressions usually refering to the same loop variable separated by semicolons for ( i=0. i++ ) initialization expression test expression increment expression .

i<15.For Loop for ( i=0. i++ ) initialization expression test expression increment expression initialization expression test expression true body of loop increment expression false exit .

i.For Loop #include <stdio. for (i=0. a=1. %d\ a*=2.a). int i. } } .h> int main() { int a.i++) { printf(³2 ^ %d = %d\n´.i<10.

the test statement is called each time through the loop.  Test expression : i<10.For Loop for (i=0. i<10. It gives the loop variable an initial value. the body of the loop is executed as long as the test statement is true  Increment expression : i++ The increment expression is called at the end of the loop and changes the value of the loop variable . the initialization statement is called once when the loop first starts.i++)  initialization expression : i=0.

scanf(³%d´.&number). long fact. fact=1. for (i=number.#include <stdio. i>0. printf(³Enter number:´).number. printf(³Factorial of %d is %ld\n´. i--) i--) fact*=i. int i.fact).h> int main() { int number. %ld\ } For Loop .

i<10. i++) { /* opening bracket after loop statement */ printf(´%d\n´. } for (i=0.i*i). i<10.Indendation and Loop Style ‡ it is good programming practice to indent loops ‡ there is some variation of the style used for loops whatever style you use do it consistently for (i=0. } for (i=0.i*i).i*i). i++) /* indent body and brackets */ { printf(´%d\n´. } . i<10. i++) /* indent body but not the brackets */ { printf(´%d\n´.

While / Do-While Loop Dowhile (a>b) { « }  the body of the loop is executed as long as the test statement is true (possibly zero times) do { « } while (a>b).  the body of the loop is executed and then repeated as long as the test statement is true (at least once) .

While Loop
while ( c != ¶y¶ ) { « } test expression true body of loop test expression

false exit

#include <stdio.h> int main() { int number; int i; long fact fact=1; printf(³Enter number:´); scanf(³%d´,&number); i=number; while (i>0) fact*=i--; fact*=i--; printf(³Factorial of %d is %ld\n´,number,fact); %ld\ }

While Loop

While Loop
the while loop is used when the number of iterations is unknown before the loop is started the while loop is repeated as long as the test expression remains true char c=¶n¶; while ( c != ¶y¶) { printf(´Do you want to continue: (y/n)\n´); scanf(´%c´,&c); }

Do Loop do { «} while ( c != ¶y¶ ). test expression body of loop test expression true false exit .

h> int main() { « i=number.number.While Loop #include <stdio. } while (i>0). /* do not forget the semicolon */ printf(³Factorial of %d is %ld\n´. do { fact*=i--.fact). %ld\ } .Do . fact*=i--.

} while ( c != ¶y¶). scanf(´%c´. therefore the body is executed at least once char c.Do Loop in the do loop the test expression is evaluated at the end of the loop. .&c). do { printf(´Do you want to continue: (y/n)\n´).

If if ( x > 100) { « } else { « } Else Statement test expression test expression true body of if false body of else exit .

Printf(´Enter a number: ´). if ( x > 100) printf(´%d is greater than 100\n´. .x).If Else Statement depending on whether the test condition is true or false either the if or the else branch is executed int x. else printf(´%d is smaller or equal than 100\n´.x). Scanf(´%d´.&x).

b).b. scanf(³%d %d´.If Else Statement #include <stdio. if (a>b) printf(³%d is larger than %d\n´.a. %d\ else if (a==b) printf(³%d is equal to %d\n´.&b). %d\ } .b).h> int main() { int a. %d\ else printf(³%d is smaller than %d\n´.&a.b).a.a.

otherwise the else part is executed. .If Else Statement if (a>b) { « } else { « }  the if part is executed if the test statement is true.

a.a.c.c.b). %d\ else if (a>c) printf(³sorted = %d %d %d\n´. %d\ else printf(³sorted = %d %d %d\n´. %d\ else .b.Nested If Else Statement if (a>b) { if (b>c) printf(³sorted = %d %d %d\n´.c). %d\ } else { if (a>c) printf(³sorted = %d %d %d\n´.b).a.c).a.b.

min = (alpha<beta) ? alpha : beta.Logical Operators logical and : && (x >= 5) && ( x <= 15) /* true if x in [5. /* substitutes if «else */ . else min = beta.15] */ logical or : || (x == 5) || ( x == 10) /* true if x=5 or x=10 */ logical negation : ! ! (x == 5) /* true if x is not equal to 5 */ x != 5 /* is equivalent */ conditional operator : ? : <condition> ? <true expression> : < false expression> if (alpha < beta) min = alpha.

Switch Statement true variable equals const 1 false variable equals const 2 false true second case body first case body default body exit .

. default : « } .Switch Statement the switch statement is used if there are more than two alternatives and the decision depends on the value of the same variable the switch statement can replace a ladder of multiple nested if.else statements switch(<variable>) { case <constant1>: « break. case <constant2>: « break.

&c). case ¶b¶: printf(´You picked a!\n´).b. default: printf(´You picked neither a. break. break. } . Scanf(´%c´. break. switch (c) { case ¶a¶: printf(´You picked a!\n´). printf(´Enter your choice (a/b/c) : ´). case ¶c¶: printf(´You picked a!\n´).c !\n´).Switch Statement char c.

a declaration of a variable in an inner block can hide a declaration in an enclosing block or a global variable .Scope of Variables a block is a section of code delimited by a pair of brackets { } a declaration introduces a variable into a scope ( a specific part of program text) the scope of a variable is the block within which the variable is declared a variable declared outside a function is global.

/* local variable */ int i=7. /* local i hides outer i */ printf(´%d\n´ i). /* outputs 3 */ } /* end of scope of outer i */ . /* global variable */ visibility of outer i lifetime of outer i int main() { int i=3.Scope of Variables int i. /* outputs 7 */ } /* end of scope of j and inner i */ printf(´%d\n´ i). /* local variable */ { int j=5.

'A'.'A'.'1'.'1'.'B'.'\ ' ASCII code maps characters to integers  .'b'.'b'.'\n '0'.'a'.'B'.'a'.Characters    Type char Characters are small integers (0-255) (0Character constants are integers that denote corresponding characters ± '0'.

ASCII Code 0 48 A 65 a 97 1 49 B 66 b 98 2 50 C 67 c 99 3 51 D 68 d 100 4 52 E 69 e 101 5 53 F 70 f 102 6 54 G 71 g 103 7 55 H 72 h 104 8 56 I 73 i 105 9 57 J 74 j 106 NULL (\0) 0 BEL (\g) 7 TAB (\t) 9 NEWLINE (\n) 10 SPACE 32 .

 Character Example char arr[4] = hi .Strings  String is collection of Characters (or ) group of elements. arrays that are NULL terminated. [0] [1] [2] [3] h i NUL L ? .

a[]="hello\ char* b=³hello\n´.Strings  Two interpretations Arrays whose elements are characters Pointers pointing to characters  Strings are always terminated with a NULL character ('\0' or 0) ('\ char a[]="hello\n". b=³hello\ a[0] *b h 104 a[1] a[2] a[3] /* size? */ a[4] a[5] a[6] *(b+1) *(b+2) *(b+3) *(b+4) *(b+5) *(b+6) e l l o \n null 101 108 108 111 10 0 .

µ ¶. ± char m[] = { µI¶.String Initialization  Initialization ± char m[9] = ³I like C´. µI¶ µl¶ µi¶ µk¶ µe¶ µC¶ \0 m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7] m[8] .¶C¶ }. µ ¶. µl¶. µk¶. µi¶. m[9 ± char m[ ] = ³I like C´. µe¶.

s[2]=µ+¶.s[1]=µ+¶.s[1]=µ+¶.¶I'. initialize str[20] I n i t i a l v a l u e \0 ? ? ? ? ? ? Null character .i}. initialize //s[0]=µc¶. // ok. // ok.p. s[3]=0. // ok. preferred s[30] char s[30] = {"c programming "}. s[30] char s[30] = {c.s[2 s[3]=0 char str[20] = ³Initial value´. s[30] // ok. redundant s[30] char s[30] = {c programming }. // ok. inconvenient char string_var[30]. // ok.String Initialization char s[30] = "c programming ".¶T'}. s[30] // illegal // illegal char s[30] = {¶S'. not initialize char* s = ³c++´.¶I'. string_var[30]. //s[0]=µc¶.

x[11] '\ printf("x = %s". x[11] = '\0'. getch(). } .h> #include <stdio.x).Null is the end of it #include <vcl."Snoopy is not a cat").h> #include <string.h> int main() { char x[ ]. strcpy(x.h> #include <conio.

dept). printf("%s %s %s %s\n". name = ³Peter Pan".s.name.d.³Peter Pan")."EE"). printf("%s %s %s\n". strcpy(name.dept).s.³Peter Pan"). s[30] char str1[30]. s[5 enough memory space to char dept[5]. ³Peter Pan" otherwise some chars will strcpy(name."is great!!"). c2[30]=³This is new c1 string´. strcpy(c1 c2 strcpy(c1. %s\ d = strcpy(s. %s\ char c1[30].String Assignment Make sure that you have char s[5]="SIIT". dept[5 char name[20]. c2 30]=³This c1 char s[30] = "c programming ". str = strcat(s. c1 30].d."is great!!"). ."IT"). str1 str1 = strcat(s. *d=dept. str1 30] char *str. be lost. strcpy(dept. c2). name[20] assign the string.

int i. last. getch().last). %s\n". printf("my name is %s. i++) printf("%s \n". last[100].In-Class Example Invoid main() { char first[100]. %s\ for (i=0."Peter"). "Pan"). } . first). i<5. strcpy(first. sprintf(last.

c) .Functions a function groups a number of program statements into a unit and gives it a name the function can be invoked from other parts of the program dividing a program into functions is one way to structure your program (structured programming) a function declaration specifies the name of the function the type of the value returned and the number and type of arguments that must be supplied in a call of the function a function definition contains the body of the function typically function declarations take place in header files (.h) whereas the function definitions are stored in source files (.

Think of a function as extending the C language to a new task. A function is a sub-unit of a program which subperforms a specific task. Functions take arguments (variables) and may return an argument.What is a function?       The function is one of the most basic things to understand in C programming. We have already (without knowing it) seen one function from the C library printf. . We need to learn to write our own functions.

/* exit the function with this result */ } . printf ("%d is the largest from %d and %d \n". Call the function k= maximum (i. 5).h> int maximum (int. /* Call maximum function */ printf ("%d is the largest from %d and %d \n". int b) /* Return the largest integer */ { The function itself if (a > b) return a. char*argv[]) { Prototype the function int i= 4.j). int). } function header int maximum (int a.maximum(3.j). /* Return means "I am the result of the function"*/ return b.k.An example function #include <stdio.5). 3. int k. return 0. /* Prototype ± see later in lecture */ int main(int argc. int j= 5.i.

} number= 4 answer= 1 count= 4 enter while loop answer= 1*4=4 count=3 enter while loop answer=4*3= 12 count=2 enter while loop answer=12*2= 24 count= 1 enter while loop answer= 24*1= 24 count= 0 enter while loop answer= 24*0= 0 . int count. return 0. count--. int answer. count= number. answer= 1. while (count >= 0) { answer= answer* count. } printf ("%d! = %d\n".Factorial program (and thoughts) int main() { int number= 4. number.answer).

for (i=1. /* call function fac()*/ int fac(int n) /* function definition */ { int i.Functions int fac(int n). /* function declaration */ int x=7. printf(´fac(%d)=%d\n´. int result=1. return result. /* exits function and returns value */ } .x. i++) result*=i. i<=n. fac(x)).

for (i=1. Int b=4. return result. int b). i++) result*=a. /* exits function and returns value */ } . /* function declaration */ int a=3.a. printf(´%d ^ %d =%d\n´. /* call function fac()*/ int pow(int a.pow(a. int i. i<=b.b)). int b) /* function definition */ { int result=1.Functions int pow(int a.b.

A variable name directly references a value. value through a pointer is called indirection.    .POINTERS  Pointers are variables that contain memory addresses as their values. A pointer variable must be declared before it can be used. A pointer indirectly references a value. Referencing a indirection.

and must itself be stored The size of a pointer depends on the amount of memory to be addressed A 16-bit pointer can address 64K locations 16A 32-bit pointer can address 4 trillion 32locations    . zero represents the "null" pointer A pointer is a number.POINTERS    A pointer is an address of a storage location By convention.

*b. *a. . and the type of data that the pointer points to. char *c. but NOT the name of the variable pointed to. when used as above in the declaration. asterisk. *c. float *b.  The asterisk. tells the compiler that the variable is to be a pointer.POINTERS  Examples of pointer declarations: int *a.

for example an integer variable occupies 2 bytes of memory The location of the piece of memory used to store a variable is called the address of that variable An address is some kind of number similar to house numbers in a street that is used to locate the information stored in that particular variable .Pointers    Each variable in a program occupies a part of the computer s memory.

Pointers  Pointers are used to: Access array elements Passing arguments to functions when the function needs to modify the original argument Passing arrays and strings to functions Obtaining memory from the system Creating data structures such as linked lists .

Use of & and *    When is & used? When is * used? & -."dereferencing operator" which provides the contents in the memory location specified by a pointer  ."address operator" which gives or produces the memory address of a data variable * -.

pf( After exchange a=%d b=%d . int *bptr) { int temp. } . pf( Enter values of a and b )./*Program to swap the values of two variables in memory #include<stdio. *bptr=temp. pf( Before exchange a=%d b=%d .a. *aptr=*bptr.> void exchange(int*. temp=*aptr. sf( %d%d &a. } void exchange(int *aptr.b.a. exchange(&a.int*) int main() { int a.&b). return 0.b).b).&b).

char.POINTER VARIABLES A pointer variable is a variable that holds address values  Each data type has its own pointer variable. pointer to char. %d\ printf(´the address of i is %d\n´. /* defines a pointer variable for integer variables */ ptr= &i. %d\  . pointer to double. *ptr.  C uses the address-of operator & to get the address of addressan variable  C uses the indirection or contents-of operator * to contentsaccess the value of the variable pointed by int i=17. double. pointer to int. int* ptr. int. ptr). /* assign the address of i to pointer */ printf(´the value of i can be printed as %d or %d\n´. i).

Pointer Variables int i.*ptr). int *ptr. . 0x1054 17 ptr=&i. printf(´value of i = %d\n´.

// defines variable w of type int int *p.Pointer Variables int v. // assigns value 3 to v *p=7. // assigns address of v to pointer p v=3. // assigns address of w to pointer p *p=12. // defines variable v of type int int w. // assigns value 12 to w  Using the indirection operator *p to access the contents of a variable is called indirect addressing or dereferencing the pointer . // assigns value 7 to v p=&w. // defines variable p of type pointer to int p=&v.

/* x still has the value 4 */ . /* call function f passing x by value */ printf(´x=%d\n´. } int x=4.x). the function creates new local variables to hold the values of the variable argument the value of the original variable are not changed void f(int val) /* the parameter val holds a local copy of the variable argument */ { val++. f(x).Pass by-Value bywhen passing arguments by value.

Pointers as Function Arguments C offers two different ways to pass arguments to a function by value : void f(int x). so that changes to the local variable have no impact on the argument with which the function was invoked  In pass-by-reference the function manipulates the pass-byoriginal variable rather than merely its copy  . by reference : void f(int* x).  In pass-by-value the function obtains only a local pass-bycopy of the variable.

double b=5.0. /* call by reference using the addresses of a and b */ printf( a=%lf. b=%lf\ } . b=%lf\n . double* ptr2) { double tmp=*ptr1. &b).0 swap(&a.a. *ptr1=*ptr2.b). /* de-referencing pointer */ de*ptr2=tmp.Pass-byPass-by-Reference void swap( double* ptr1. } int main() { double a=3.

&n). printf( enter a number ).b) int a. } .*b. for(m=1. *b=1. { int m.factorial.*/Factorial of a given number using pointers*/  main() { int n.m<=a.n. } factcompute(a. printf( the factorial of %d .&factorial). factcompute(n.factorial).m++) *b=*b*m. scanf( %d .

.  The elements of an array are accessed by an index number that allows random access.Arrays  The idea of an array is to group similar objects into units.  Arrays are structures that group items of the same data type.

%d\ .i++) printf(³2 ^ %d = %d\n´. for (i=0.Arrays int poweroftwo[10]. for (i=1.i++) poweroftwo[i]=poweroftwo[ipoweroftwo[i]=poweroftwo[i-1]*2. /*array definition */ int poweroftwo[0]=1.i<10.i.i<10.poweroftwo[i]). /* first element has index number 0 */ int i.

2.avg(5. double array[]). i<sz.Arrays double avg(int sz. i++) sum+=array[i].9} /* initialize array */ printf(³average is %lf\n´. 2.x)). %lf\ double avg(int sz. return sum/sz.5. for (i=0. /* function definition*/ double x[5]={1.2. 1.7. } . 3. double sum. 4. double array[]) { int i.

0.i<ROWS. } . double a[COLS].j++) b[i]+=matrix[i][j]*a[j].j. for(i=0.MultiMulti-Dimensional Arrays #define ROWS 5 #define COLS 6 double matrix[ROWS][COLS].i++) { b[i]=0. int i. for(j=0.j<COLS. double b[ROWS].

h> #define MAXSIZE 100 main() { int n.i++) { if(max<elements[i]) max=elements[i].i).&elements).max)./* Write a c-program to find the largest number in can array */  #include<stdio. } printf(the maximum is %d . printf( enter the no of elements ).i<n.max=0.elements[MAXSIZE]. scanf(%d . for(i=0.&n). i<n. scanf( %d . } for(i=0. i++) { printf( enter value for element %d: . } .I.

² for (i = 0. ² for (p = a. P < a+size.Arrays in Pointers Array indexing is syntactic sugar for pointers  a[i] is treated as *(a+i)  To zero out an array: ² for (i = 0. p++) *p = 0. i < size.   Because a[i] means *(a+i). i < size. i++) a[i] = 0. i[a] is equally legal! . i++) *(a+i) = 0.

/* array of 5 ints */ for (int i=0. i++) printf(´%d\ printf(´%d\n´. i< 5. 17 }.Pointers and Arrays There is a close association between pointers and arrays  Arrays can be accessed using pointers  The name of an array is also a constant pointer to the data type of the elements stored in the array  int array[5] = { 23. i<5.array[i]). 5. /* using index to access elements */ for (int i=0. *(array+i)). 34. 12. i++) printf(´%d\ printf(´%d\n´. /* using pointer to access elements */ /* the variable array is of type pointer to integer */ .

fullname). Instead strings are stored in arrays of type character. #include <strings. strcpy(fullname. printf(³full name is %s\n´.firstname). char fullname[512].h> char lastname[256]=³Hansen´. strcat(fullname. char firstname[256]=³Ole´. strcat(fullname.´ ³).lastname).Arrays and Strings  In C there is no particular type for strings. %s\ .

re=2. b. b. /* members of the structure */ double im.b).5. complex mult(struct complex a.re=2. The data items in a structure are called members of the structure.im=-1.8.im=1. }. struct complex a. /* variable declaration of type complex */ a.b.c. . /* accessing members of struct complex */ a.Structures   A structure is a collection of simple variables.0. c=mult(a.im=b. struct complex b). struct complex /* structure declaration */ { double re. that can be of different type.3.

C Structures
Collection of related variables under one name Derived data types Variables declared within the braces of the structure definition are the members of the structure  Members of the same structure type must have unique names  Two different structure types can contain members of the same name without conflict 
 

struct card { int face; char suit[20]; }; struct card aCard, deck[52], *cardPtr;

Structures 
Structures

are collections of variables of different types, as in the following example.
struct abc { int a; long b; char c; } MyStruct; Structure Type Name

Structure Definition

variable declaration

C Structures and Functions
struct point makepoint(struct point pt, int x, int y) { pt.x = x; pt.y = y; return pt; } int main() { struct point pt; pt = makepoint (pt, 5, 6); printf( pt.x = %d pt.y = %d\n , pt.x, pt.y); %d\ }

makepoint (&pt. pt. ptpt->y = y.y = %d\n . %d\ } For very large structures. 5. 6). int y) { pt->x = x. pass the pointer to it! .C Structures and Functions void makepoint(struct point *pt.x = %d pt. pt} int main() { struct point pt.y).x. printf( pt. pt. int x.

date2. int month1. month1month1-date1. int mmdd.mmdd/100. sf( %d .mmdd)./*Program to display the month names of both dates*/  Struct mydate { int yyyy. pf( enter second date(mmdd) ).&date2.//take month alone pf( firstt month is %s . sf( %d . jan . pf( enter first date(mmdd) ).month2=date2. main() { struct mydate date1. feb .mmdd).month2. mar . }.months[month1]. .&date1.months[month2]).mmdd/100. pf( second month is %s . } . char *months[]={ . dec }.

myptr paise). main() { struct currency mycurr={123. showit(&mycurr). } .myptr rupees./*Program to illustrate the use of structure pointer  Struct currency { int rupees.%d .25}. }. int paise. } showit(struct currency *myptr) { pf( rupees %d.

float fval. the -> operator. They have identical declaration syntax and member access. }. for pointers to unions. but they serve a very different purpose.Unions  Unions look similar to structures. z.  Accessing members of a union is via . y. union Utype x. member operator or. char *sval. . union Utype { int ival.

/* Implementation dependent.fval = 56. /* OK. Otherwise. x. one The compiler allocates storage for the biggest member of the union.fval).  union Utype x. */ .  The type retrieved from the union must be the type most recently stored.Unions A union holds the value of one-variable at a time. the result is implementation dependent. x.4. */ printf("%f\ printf("%f\n".ival). x. /* x holds type float. */ printf("%d\ printf("%d\n".

Unions 


Unions are used to store one of a set of different types. Commonly used to implement a variant array. (This is a form of generic programming.) There are other uses also, but they are quite advanced (e.g., concern the alignment properties of unions). 

/* Write a c-program for student marks cusing an array of structures */ 

struct marks { int sub1; int sub2; int sub3; int total; }; main() { int i; static struct marks student[3]={ {56,45,65}, {59,55,75},45,65,75}}; static struct marks total; for(i=0;i<=2;i++) { student[i].total=student[i].sub1+student[i].sub2+student[i].sub3; total.sub1=total.sub1+student[i].sub1; total.sub2=total.sub2+student[i].sub2; total.sub3=total.sub3+student[i].sub3; }

Contd..
printf( STUDENT TOTAL ); for(i=0;i<=2;i++) printf( student[%d] %d ,i+1,student[i].total); printf( SUBJECT TOTAL ); printf( %s%d%s%d%s%d , subject 1 , total.sub1, subject 2 , total.sub2, subject 3 , total.sub3); printf( Grand total=%d ,total.total); }

File Input In C The C type. ³FILE´ allows for a consistent approach to input regardless of the actual physical device Default: stdin FILE C program .

File Output In C Similar to file input. the C type ³FILE´ allows for a consistent approach to output regardless of the actual physical device Default: stdout stream FILE C program .

 Example:  FILE *fp.  Be   sure to include the following preprocessors: #include <stdio. *<name file>.h> #include <stdlib.Declaring a FILE Variable  Format:  FILE *<name of pointer to file>.h> .

r ).  Example:  fp = fopen ( data . .Opening Files Format:  FILE * fopen (const char * filename. r ).  fp = fopen ( /home/profs/tamj/data . const char * mode).  Insufficient permissions to open the file.  Error conditions  File does not exist.

start writing at the end Open file for reading and writing Open file for writing and reading .Opening Files (2)  Filename Must reside in the same directory as C program being run Alternatively you can include the path to the file Some File open modes Mode r w a r+ w+ Effect Open text file for reading Open text file for writing Open text file for writing.

Closing Files Disassociates the file with the physical device  Remaining contents of the stream a flushed  Format:  int fclose (FILE * fp).  .  Example:  fclose(fp).

.   Similar to printf except you can also write to a file other than the screen (standard out). arr).Writing To A File fprintf Format:  fprintf (FILE *fp. Example: char arr[8] = hiya .  fprintf(fp. %s . const char *control_string . arguments).

<control string> . %s . fscanf (fp. chunk).Reading From A File fscanf Format: fscanf (FILE *fp. addresses).  Example:   char arr[8]. Similar to scanf except you can also read from a file other than the keyboard (standard in) .

.Reading From A File fgets  Format: fgets(char *line. int n. FILE *fp). 80. fp).  Example:  fgets(chunk.

 char arr[LENGTH]. main () {  FILE *fp_in. *fp_out .  char fn_out [LENGTH].  scanf("%s".  char fn_in [LENGTH].  printf("Enter name of output file: "). scanf("%s".File I/O: First Example The full example can be found in C: C: #include #include <stdio.h> int const LENGTH = 80. fn_in). fn_out). printf("Enter name of input file: ").   .h> <stdlib.

"r"). } if (!fp_out) { printf("Can't open output file\n"). "w"). fp_out = fopen(fn_out. if (!fp_in) { printf("Can't open input file\n"). file\ return(return(-1).File I/O: First Example (2)             fp_in = fopen(fn_in. } . file\ return(return(-1).

fprintf(fp_out.File I/O: First Example (3)         while (feof(fp_in) == 0) { // Using fscanf it stops scanning at whitespace fscanf(fp_in. arr). "%s} return(0). } . arr). "%s-". "%s".

"%s".File I/O: Second Example This example is identical to the first example except for the loop: while { (feof(fp_in) == 0) // Grabs whole line up 79 characters or the end-of-file end-of(whichever comes first)  fgets (arr. asfprintf (fp_out. arr). 80. . fp_in).    } // Writes out to output file as-is.

File I/O: Third Example #include <stdio.  .  char arr[LENGTH]. printf("Enter name of input file: ").  scanf("%s".h> #include <stdlib. main () {  FILE *fp_in.  char fn_in [LENGTH].h> int const LENGTH = 80. fn_in).

} while (feof(fp_in) == 0) { // Grabs whole line up 79 characters or the end-of-file end-offgets(arr.File I/O: Third Example (2)                fp_in = fopen(fn_in. } . fprintf(stdout. Output file is the screen asfprintf(stdout. arr). fp_in). } return(0). "%s". file\ return(return(-1). if (!fp_in) { printf("Can't open input file\n"). "r"). 80. // Writes out to output file as-is.

/* Write a program to detect error while opening a file that does not exist.*fp2.filename). open_file. r ))==NULL){ printf( Cannot open the file ). number. FILE *fp1. } . w ). if((fp2=fopen(filename.i+=10){ putw(I. printf( Type filenme again ) goto open_file. for(i=10.h> main() { char *filename.*/  #include<stdio. printf( Input File Name ). scanf( %s . fclose(fp1). fp1=fopen( TEST .i<=100.fp1). int i.

. } .i<=20. break.number). if(feof(fp2)) { printf( Ran out of data ). } else printf( %d . } fclose(fp2)./*ERROR HANDLING IN FILE OPERATIONS*/  else for(i=1.i++) { number=getw(fp2).Contd.

f=factorial(num).f).RECURSION It is the process of calling of a function by itself. void main() { int num. EXAMPLE: TO CALCUALTE FACTORIAL OF A NUMBER int factorial(int).&num). printf( enter number whose factorial is to be calculated ). } Contd . scanf( %d .f. The function which calls itself is known as recursive function. printf( %d .

} . else return x*factorial(x-1).int factorial(int x) { if(x==1) return 1.

THANX .

Sign up to vote on this title
UsefulNot useful