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. 

more predictable performance It has all the low-level operations low- .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.

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

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 .

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

obj (linked) ---> executable file .c ---> (compiled) ---> test. The modified program now goes to a compiler. which translates it into machine instructions (object code).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.Compiling and Linking 1. test. Linking. 3. which obeys commands that begin with # (known as directives). #include <stdio. Compiling. Preprocessing.h> before compiling) 2. The program is first given to a preprocessor.

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

Contd .  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 .

1 have special significance to the compiler and therefore can not be used as identifiers.Keywords In Standard C. Table 2. the keywords in Table 2.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 Format of C       Statements are terminated with semicolons Indentation is ignored by the compiler C is case sensitive .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. those forgetting to do so have one or other chosen randomly! .

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

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. this will be investigated later) .absence will make program very ill & not necessary with printf because current value of parameter is used .

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

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

´ is the format strings and describes how the data is formatted. }  The symbols { and } mark the beginning and end of a block of code. return 0.Hello World Program #include <stdio. printf(´Hello World\n´) World\  Sends output to the screen.. Every C-program must have a function Cnamed main somewhere in the code { .  This causes the function main to return an error code of 0 (no error) to the shell that started the program. The portion in quotes ´. ....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.

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

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

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

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.4x1038 1.7x10-308 3.7x10308 3.

.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. double x = 5. double y=x. char answer = ¶n¶. in the same way one assigns a value to an already defined variable. Examples of variable definitions: int a.9.

14159 the preprocessor replaces the identifier PI by the text 3.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.Constants constants can be specified using the preprocessor directive #define example: #define PI 3.14159 CONVENTION: reserve CAPITAL letters for constants and use small caps for variables and functions .

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 */ .

/* casts i into float before division */ .5 */ Type conversions can be forced by a programmer through a type cast float z = (float) i / j. 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 y = i/j. float x = i. Some type conversions occur automatically for example int to float or float to double. /* assigns 17/2 = 8 to y not 8. char c=¶x¶.14. /* assigns 17 to x */ int j = 2. but also char to int int i = 17.Type Conversions C is a hard-typed language.

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

h> #include ´myprog.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´ 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 .

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

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

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

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  .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´.

Input / Output     scanf allows you to read input from standard in (keyboard) scanf uses the same placeholders as printf scanf (³%d´.&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. the reason becomes clear when you learn more about pointers .

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

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

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

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

i<15. i++ ) initialization expression test expression increment expression .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<15. i++ ) initialization expression test expression increment expression initialization expression test expression true body of loop increment expression false exit .For Loop for ( i=0.

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

For Loop for (i=0.i++)  initialization expression : i=0. the test statement is called each time through the loop. 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 . i<10. It gives the loop variable an initial value. the initialization statement is called once when the loop first starts.  Test expression : i<10.

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

i<10. i++) /* indent body but not the brackets */ { printf(´%d\n´.i*i). i++) /* indent body and brackets */ { printf(´%d\n´. } for (i=0. i<10. i++) { /* opening bracket after loop statement */ printf(´%d\n´. } .i*i). i<10.i*i). } for (i=0.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.

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); }

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

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

. scanf(´%c´.Do Loop in the do loop the test expression is evaluated at the end of the loop.&c). } while ( c != ¶y¶). therefore the body is executed at least once char 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 .

&x). if ( x > 100) printf(´%d is greater than 100\n´. .x). else printf(´%d is smaller or equal than 100\n´. Printf(´Enter a number: ´). Scanf(´%d´.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.

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

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.b). %d\ } else { if (a>c) printf(³sorted = %d %d %d\n´.c. %d\ else .c. %d\ else printf(³sorted = %d %d %d\n´.Nested If Else Statement if (a>b) { if (b>c) printf(³sorted = %d %d %d\n´.b).b.c).a.c).a.b. %d\ else if (a>c) printf(³sorted = %d %d %d\n´.a.

/* substitutes if «else */ .Logical Operators logical and : && (x >= 5) && ( x <= 15) /* true if x in [5.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. else min = beta. min = (alpha<beta) ? alpha : beta.

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

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. case <constant2>: « break.else statements switch(<variable>) { case <constant1>: « break. default : « } ..

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

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.

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

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

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 .

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

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 .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". a[]="hello\ char* b=³hello\n´.

µ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] . µ ¶. m[9 ± char m[ ] = ³I like C´. µl¶. ± char m[] = { µI¶. µ ¶. µi¶. µe¶.String Initialization  Initialization ± char m[9] = ³I like C´.¶C¶ }. µk¶.

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

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

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

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

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 (.

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 need to learn to write our own functions. 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. . We have already (without knowing it) seen one function from the C library printf.

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

answer). answer= 1. int count. return 0. } printf ("%d! = %d\n".Factorial program (and thoughts) int main() { int number= 4. count--. count= number. } 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 . number. while (count >= 0) { answer= answer* count. int answer.

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

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

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

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.

float *b. asterisk.POINTERS  Examples of pointer declarations: int *a.  The asterisk. *a. tells the compiler that the variable is to be a pointer. *b. 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. *c.

Pointers    Each variable in a program occupies a part of the computer s memory. 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  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? & -."address operator" which gives or produces the memory address of a data variable * -."dereferencing operator" which provides the contents in the memory location specified by a pointer  .

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

POINTER VARIABLES A pointer variable is a variable that holds address values  Each data type has its own pointer variable. char. pointer to char. %d\  . /* assign the address of i to pointer */ printf(´the value of i can be printed as %d or %d\n´. /* defines a pointer variable for integer variables */ ptr= &i. int. pointer to double. *ptr. double. %d\ printf(´the address of i is %d\n´. int* ptr. i).  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. pointer to int. ptr).

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

// assigns address of w to pointer p *p=12. // 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 . // defines variable w of type int int *p.Pointer Variables int v. // assigns address of v to pointer p v=3. // defines variable v of type int int w. // assigns value 3 to v *p=7. // defines variable p of type pointer to int p=&v. // assigns value 7 to v p=&w.

f(x).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++. /* call function f passing x by value */ printf(´x=%d\n´.Pass by-Value bywhen passing arguments by value. /* x still has the value 4 */ . } int x=4.

 In pass-by-value the function obtains only a local pass-bycopy of the variable. by reference : 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  .Pointers as Function Arguments C offers two different ways to pass arguments to a function by value : void f(int x).

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

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

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

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

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

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

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

i < size. P < a+size. i[a] is equally legal! .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. ² for (i = 0. i++) a[i] = 0. i < size. i++) *(a+i) = 0. p++) *p = 0.   Because a[i] means *(a+i). ² for (p = a.

5. /* array of 5 ints */ for (int i=0. /* using index to access elements */ for (int i=0. 12.array[i]).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. *(array+i)). 34. i++) printf(´%d\ printf(´%d\n´. 17 }. i< 5. /* using pointer to access elements */ /* the variable array is of type pointer to integer */ . i++) printf(´%d\ printf(´%d\n´. i<5.

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

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

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\ }

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

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

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

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

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

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´ allows for a consistent approach to input regardless of the actual physical device Default: stdin FILE C program .File Input In C The C type.

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

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

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

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. start writing at the end Open file for reading and writing Open file for writing and reading .

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

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

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

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

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

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

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

asfprintf (fp_out.    } // Writes out to output file as-is. arr). fp_in).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. . 80. "%s".

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

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

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

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

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