Compiling and Running a C program Preprocessor Compiler Assembler Linker Loader Layout of the Program Memory Static memory Global Variables Static Variables Heap memory Dynamically allocated memory Stack Memory Auto variables Function parameter Program/ Text Program statements First Simple Code in C #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; } Preprocessor command Main function entry point Comment in C ignored while compilation Built in Function with arguments Main function return value Tokens in C A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. printf("Hello, World! \n"); printf ( "Hello, World! \n" ) ; 5 tokens C Data Types Basic Data Types Integer and Float with different sizes Enumerated Data Types Arithmetic type with discrete integer values only Void Data Indicates no Value Derived Data Types Pointer Type, Array Type, Structure Type and Union Type Basic Data Type Data Type Size in Bytes char 1 short 2 int 2 or 4 long 4 float 4 double 8 long double 10 To find the size use the sizeof(type) operator The void type The void type is used in three kinds of situation
Function Returns as void Function arguments as void Pointers to void generic pointers Enumerated Data Type Enumeration type allows programmer to define their own data type . Keyword enum is used to defined enumerated data type #include <stdio.h> enum color{ green, yellow, pink, blue, red}; int main() { enum color select; select=green; return 0; } By default the values starting from 0 will be assigned to green, yellow, pink, blue, red Variables in C A variable is a name given to a storage area that our programs can manipulate The name of the variable is decided by the user along with the type of data it can hold Variables declaration and definition can be done together int d = 3, f = 5; /* initializing d and f. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */ The scope or the time duration, a variable can exist is defined by the storage class Programming Storage Class Automatic Storage class Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are local to the function and doesn't have meaning outside that function. auto External storage class Global variables declared in one file can be accessed in another file. Have a greater scope than global variables. extern Register Storage class They are similar to the auto declared variables, however they can be accessed faster as they are stored in the register. register Static storage class Static variables exist for the entire duration of the program however they cannot be accessed outside the file. static Small Quiz What will be the output? #include <stdio.h> void Check(); int main() { Check(); Check(); Check(); } void Check() { int c=0; printf("%d\t",c); c+=5; } Output 1: 0 0 0 Constants and Literals Constants and Literals are the same. They are the fixed values that the program may not alter during its execution.
Constants in C can be defined in two ways #define pre processor const keyword #include <stdio.h> #define LENGTH 10 int main() { const int WIDTH = 5; area = LENGTH * WIDTH; printf("value of area : %d", area); return 0; } C Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations
The following operators are present in C:
Arithmetic Operators [+,-,*,/,%,++,--] Relational Operators [ ==,!=,>,<,>=,<=] Logical Operators [&&, ||, !] Bitwise Operators [&,|,^,~,<<,>>] Assignment Operators [=,+=,- =,*=,/=,%=,<<=,>>=,|=,^=] Misc Operators [sizeof(),& (address), *, ? :] Bitwise operators #include <stdio.h> main() { int c = 0; unsigned int a = 60; /* 60 = 00111100 */ unsigned int b = 13; /* 13 = 00001101 */
c = a & b; /* 12 = 00001100 */ c = a | b; /* 00111101 */ c = a ^ b; /* 00110001 */ c = ~a; /*11000011 */ c = a << 2; /* 11110000 */ c = a >> 2; /* 00001111 */
} Binary AND Operator Binary OR Operator Binary XOR Operator Binary Is complement Operator Binary Left Shift Operator Binary Right Shift Operator Miscellaneous Operators sizeof() This operator returns the size of the variable & This operator returns the address of the variable * This operator returns the pointer of the variable ? : This operator returns the pointer of the variable
If Condition is true ? Then value X : Otherwise value Y
What is a pointer? int x = 10; int *p;
p = &x;
p gets the address of x in memory. p x 10 What is a pointer? int x = 10; int *p = NULL;
p = &x;
*p = 20;
Declares a pointer to an integer & is address operator gets address of x * dereference operator gets value at p Null pointer What is a pointer? Generic Pointers Pointer variable is declared as type void The pointer does not point to any data Can be used when you dont know what type of variable the pointer is going to point Once the type is known the void pointer need to be casted to that type
void *ptr; *(int*) ptr; Generic pointer declaration Casting it to refer to an integer type Pointer to a pointer A pointer to a pointer is a form of multiple indirection, or a chain of pointers. int **var; Example code #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 3000;
ptr = &var; pptr = &ptr;
printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr); return 0; } What will be the output?? Swapping two numbers (using temp) #include<stdio.h> int main() { int x,y,temp; printf(Enter x and y\n"); scanf("%d%d", &x, &y);
temp = x; x = y; y=temp;
printf("After\nx=%d\ny=%d\n",x,y); return 0; } Swapping without a temp variable #include<stdio.h> int main() { int x,y; printf(Enter x and y\n"); scanf("%d%d", &x, &y);
x =x+y; y =x-y; X =x-y;
printf(After swapping\nx=%d\ny=%d\n",x,y); return 0; } Swapping using pointers #include<stdio.h> int main() { int x,y,*a,*b,temp; printf(Enter x and y\n"); scanf("%d%d", &x, &y); a= &x; b=&y; temp = *b; *b = *a; *a = temp; printf(After swapping\nx=%d\ny=%d\n",x,y); return 0; } Swapping using bitwise XOR #include<stdio.h> int main() { int x,y; printf(Enter x and y\n"); scanf("%d%d", &x, &y);
x =x^y; y =x^y; X =x^y;
printf(After swapping\nx=%d\ny=%d\n",x,y); return 0; } Functions Function is a group of statements that together perform a task. Defining a Function Function Declarations Calling a Function /*fn returning the max between two nos */
int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } answer = max(a, b); You are building a ship game and are currently located at lat = 32 and lon = -64
You need to go south east by latitude -1 and lon +1
You can write a function to do the above :
go_south_east() N S W E longitude +1 l a t i t u d e
- 1
void go_south_east(int lat, int lon) { lat = lat - 1; lon = lon + 1; } Small Quiz #include <stdio.h>
int main() { int latitude = 32; int longitude = -64; go_south_east(latitude, longitude); printf(" Now at: [%d, %d]\n", latitude, longitude); return 0; } void go_south_east(int lat, int lon) { lat = lat - 1; lon = lon + 1; } What should print now?? Calling a function passing arguments Two ways of passing arguments to a function Pass by value Pass by reference The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. Calling a function by reference The call by reference method of passing arguments to a function copies the address of an argument Inside the function, the address is used to access the actual argument used in the call go_south_east(&latitude, &longitude); void go_south_east(int *lat, int *lon) { *lat = *lat - 1; *lon = *lon + 1; } & * * A l l
d i f f e r e n t
C - Arrays Array data structure which can store multiple variables of the same type in contiguous memory locations
double balance[5]; double balance[5] = {10.0, 2.0, 3.4, 17.0, 50.0}; double balance[] = {10.0, 2.0, 3.4, 17.0, 50.0}; Accessing Arrays double salary = balance[3]; For loops are commonly used to access and initialize the array elements int main () { int n[ 10 ]; int i; for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } 0 1 2 3 4 5 6 7 8 9 10 11 Two dimension Arrays int val = a[2][3]; int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} }; int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; int c = a[2][3] What will be the value of c? Pointer to an array An array name is a constant pointer to the first element of the array. double balance[50]; balance is a pointer to &balance[0], double *p; double balance[10]; p = balance; Hence you can do this *p and *balance can be used to print balance[0] *(p+1) and *(balance +1) can be used to print balance[1] Array of pointers Array of pointers is a array containing addresses int var[] = {10, 100, 200};
int i, *ptr[3]; for ( i = 0; i < MAX; i++) { ptr[i] = &var[i]; } for ( i = 0; i < MAX; i++) { printf("Value of var[%d] = %d\n", i, *ptr[i] ); } Strings in C The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; char greeting[] = "Hello"; 4 important string functions [string.h] strcpy(s1, s2); Copies string s2 into string s1.
strcat(s1, s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2. C Structures Arrays allow you to hold multiple data of the same kind What if you want to hold multiple data of different kinds cant do it in an array You need to use STRUCTURES or UNIONS ! What is the difference? Structure of a structure struct Books { int book_id; float price; }; Outside main() Inside main() struct Books b1;
b1. book_id = 101; b1. price = 122.50; struct Books *ptr; ptr = &b1; ptr -> book_id = 101; ptr -> price = 1225.50; int int float float float float 2 bytes 4 bytes sizeof(b1); Unions Unions differ from structure only in memory organization union Books { int book_id; float price; }; Outside main() Inside main() union Books b1;