C for Engineers

3,979 views

Published on

covers main titles of C Language for engineers with basic programing skills. Data types, Operators

Published in: Technology

C for Engineers

  1. 1. C for Engineers Julie Iskander, MSc. Communication and Electronics
  2. 2. Course Outlines • • • • • • Introduction to Programming C Program Data Types, Variable and Constants Control Statements and loops and functions Memory Management and Pointers Structures
  3. 3. Introduction
  4. 4. What is a Computer Program? • Computers are dumb machines. • A Computer Program is a set of instructions, written in a language the computer understands, to tell the computer what to do to solve a problem. • The approach or method used to solve a problem is called an algorithm • Example: • How to write a program to tell if a number is odd or even?
  5. 5. Programming Language • Machine Language • Low-level languages • High level languages
  6. 6. Compilers • To support a higher-level language, a special computer program must be used that translates the statements of the high-level language program into the particular instructions of the computer. • A compiler analyzes a program and then translates it into a form that is suitable for execution on your particular computer system. • Types of errors: • Syntax error  detected by compiler • Logical error  is not detected by compiler, but makes code give unpredicted results.
  7. 7. Programming Methodologies • Linear Programming • Structural Programming • Object Oriented Programming
  8. 8. Software Development Life Cycle • • • • • Analysis Design Implementation Testing Maintenance
  9. 9. Dennis Ritchie (1941-2011) • Designer and original developer of the C programming language. • A central figure in the development of Unix. • Was awarded the Turing Award in 1983, and the National Medal of Technology in 1999. • "Ritchie's influence rivals Jobs's; it's just less visible," James Grimmelman observed on Twitter. "His pointer has been cast to void *; his process has terminated with exit code 0."
  10. 10. C Programming Language • C is a general-purpose programming language initially developed by Dennis Ritchie between 1969 and 1973 at AT&T Bell Labs. • Its design provides efficient mapping to typical machine instructions, thus substitutes assembly language, • Portable, as it is not difficult to write programs that can be run without change on a variety of hardware • Most of the Linux and UNIX operating systems are written in C.
  11. 11. C is a “higher-level language,” yet it provides capabilities that enable the user to “get in close” with the hardware and deal with the computer on a much lower level. “PROGRAMMING IN C”, THIRD EDITION, STEPHEN G. KOCHAN
  12. 12. C Compiler *.c compiler .obj linker .exe Compilers translate an entire file of code all at once, rather than line by line. Generate all error messages Creates an intermediate file, waiting to be linked to any external libraries needed, to create a final executable file Linker combines your object file with object files already found in the libraries.
  13. 13. C Program Structure
  14. 14. C Program PreProcessor Program Body #include <stdio.h> int main() { printf(“Hello C ”); return 0; }
  15. 15. #include directive • Tells the compiler to insert another file at this location of your source code. • The new inserted code is compiled with the rest of the source code. • Also include header files (*.h). • A header file is a file that contains the function prototype of the functions defined in the library file before compilation, the compiler will add the header file contents to the source code. At compilation, the compiler can check function signatures against syntax errors.
  16. 16. Program Body Entry Point of the program. A program must contain atleast on function, main() int main() { variable or constant declaration; statements; return 0; } All variables must be declared before any statement is executed
  17. 17. C Comments • Not executable statement, documents the code • Ignored by compiler • Single line Comment // this is a single line comment • Multi – line Comment /* This is a longer comment That spans across multiple lines ……………………….. */
  18. 18. Data types, Variables , Constants
  19. 19. Data types • There are 5 fundamental data types 1. 2. 3. 4. 5. char (1 byte) int (2 bytes) float (4 bytes) double (8 bytes) Void • Size may differ from platform to another • Can add type modifier to the data types to alter its meaning (unsigned, signed, long, short) • Example • Signed char  0 to 255 • unsigned char  -127 to 127
  20. 20. Variables • A place to store data, for further usage. • Declaring Variables: • datatype variable_name • datatype variable_list • Example: • int x; • char a,b,c,e; • C doesn’t initialize variables. • After declaring a variable, it can be used multiple times
  21. 21. Variables Local Variables Global Variables • Declared inside a function • Available only for the function. • Ends with the function, closing brackets of the function • Declared out of any function • Available for all functions • Not recommended to use it extensively.
  22. 22. Constants • A fixed value, that can’t be changed at any part of the program • There are two ways to define a constant value • As a macro, in the preprocessor using define • #define PI 3.14 • In a program body • const int pi=3.14; • Must be initialized when declared
  23. 23. Statements • Are executable lines of code • Ends in ; • Can be a input statement, expression or operation or output statement
  24. 24. I/O statements • Output function: display the results on the screen • printf() • printf(“string”,*,data+); • Example: printf(“Hello”); int x=3; printf(“x is %d”,x); • Format specifiers • • • • %d integer %f float %c char %lf double • putchar(): puts a character on the screen. • Example: • putchar(‘a’) ; or putchar(23);
  25. 25. I/O statements • Input function: wait for user to enter values and save it. • scanf(“format-specifier”, address -of-var): Wait for user to input, must specify the data type of the input (format specifier) and the address to store value in • getchar() Reads one character only from keyboard and wait for carriage return, character is printed to screen • getch() (only bc) Reads one character only from keyboard without waiting for carriage return, character is not printed to screen • getche() (only bc) Reads one character only from keyboard without waiting for carriage return, character is printed to screen
  26. 26. Operators
  27. 27. Operators
  28. 28. Operators
  29. 29. C Memory Managment Stack Heap Uninitialized data segment Global and static Variables Section (Initialized Data Segment) Executable Code Section (Code Segment)
  30. 30. Assignments • Assignment 1: The history of programming languages. • Assignment 2: Interpreter Versus Compiler • Assignment 3: What’s the output of the following: int a=25, b=3; printf("%d", a/b*b); Why?
  31. 31. Lab • Install Borland C 3.1 or Cygwin • Write hello.c to print Hello world • Write a program to print the following with the same format *********** **Hello all** *********** with one printf statement. Use escape sequences like n,t,…..etc. • Fix errors in error1.c and error2.c. • Write a program to ask user to enter the number of the day in a year and the program will output the day and month. Assume all month has 30 days. • Try writing a function for the previous assignment • Try casting and operator precedence
  32. 32. Branching
  33. 33. if statement if(condition) { statements } else { statement }
  34. 34. • Write a program to specify if a number is odd or even int main() { int num; printf(“Enter a number: ”); scanf(“%d”, &num); if(num%2) { printf(“Odd”); } else { printf(“Even”); } return 0; }
  35. 35. Nested if if(condition) { statements } else { if(condition) { statement } else { statement } } if(condition) { statements } else if(condition) { statement } else { statement }
  36. 36. • Write a program to print grade of students according to his marks int main() { int mark; printf(“Enter your mark: ”); scanf(“%d”, &mark); if(mark>=90) printf(“A”); else if(mark>=80) printf(“B”); else if(mark>=70) printf(“C”); else printf(“Failed”); return 0; }
  37. 37. switch................case switch(expression) { case const1: { statement; break; } case const2: { statement; break; } case const3: { statement; break; } default: { statement; } }
  38. 38. Write a program to print marks range of students according to his grade int main() { char mark; printf(“Enter your mark: ”); scanf("%c",&mark); switch (mark) { case ‘A’:, printf(“Marks between 100 and 90”); break; } case ‘B’: , printf(“Marks between 90 and 80”); break; } case ‘C’: { printf(“Marks between 80 and 70”); break; } default: { printf(“less than 70”); } } return 0; }
  39. 39. break • What if we forget a break in any case? Fall through • All sequential cases till the first break or end of cases will be evaluated
  40. 40. Looping
  41. 41. Looping • Is repeating a block of code for a specific times or until a condition is satisfied. • Loops can be terminated using break statement, or an iteration skipped using continue statement.
  42. 42. for loop for( initialization ; condition ; increment ) { statements to be repeated; } • Initialization is a statement executed once at the start of the loop. • Condition is evaluated before every iteration, to decide to go on or quit the loop, must evaluate to true/false • Increment is a statement executed at the end of each iteration • Used for repeating code a specific number of times
  43. 43. • Write a program to print numbers from 1 to 100 int main() { int i; for(i=1; i<=100 ;i++) { printf("%dn",i); } return 0; }
  44. 44. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { if(i==10) continue; printf("%dn",i); } return 0; }
  45. 45. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { printf("%dn",i); if(i==10) break; } return 0; }
  46. 46. • What’s the output? int main() { int i; for(i=1; i<=100 ;i++) { if(i==10) break; printf("%dn",i); } return 0; }
  47. 47. • What’s the output? int main() { int i=0; for(; ;) { i++; printf("%dn",i); } return 0; }
  48. 48. • Write a program to take a character and print it till z is entered? int main() { char c; for(c=0; c!='z';) { printf("Enter a character"); c=getchar(); getchar(); } return 0; } Why do we need to add another getchar()?
  49. 49. • Write a program to calculate the average of marks of 10 students int main() { int i, mark ; int sum=0, avg; for(i=0; i<10 ;i++) { printf("Enter a student mark : "); scanf(“%d”, &mark); sum+=mark; } avg=sum/10; printf(“Average of student marks is %d”,avg); return 0; }
  50. 50. Nested for loops What’s the output? int main (void) { int n, number, triangularNumber, counter; for ( counter = 1; counter <= 5; ++counter ) { printf ("What triangular number do you want? "); scanf ("%i", &number); triangularNumber = 0; for ( n = 1; n <= number; ++n ) triangularNumber += n; printf ("Triangular number %i is %inn", number, triangularNumber); } return 0; }
  51. 51. while loop while(condition) { statements to be repeated; } • Used for repeating a block of code until a condition is met, the condition is tested before executing the block of code. • The block of code can never be executed
  52. 52. int main() { int n,x,i=1,multi=1; printf(“Enter x:”); scanf(“%d”,&x); printf(“Enter n:”); scanf(“%d”,&n); while(i<=n) { multi*=x; i++; } printf(“y is %d”,multi); return 0; }
  53. 53. do…….while loop do { statements to be repeated; } while(condition); • Used for repeating a block of code until a condition is met, the condition is tested after executing the block of code. • The block of code is executed at least once
  54. 54. What is the error in this code? int main() { int n,x,i=1,multi=1; printf(“Enter x:”); scanf(“%d”,&x); printf(“Enter n:”); scanf(“%d”,&n); do{ multi*=x; i++; } while(i<=n); printf(“y is %d”,multi); return 0; }
  55. 55. Function
  56. 56. Functions • Is a block of code, that does a specific task. • Each program has atleast one function , main • Functions reduce duplicate code and make maintenance and modification easier and quicker • Any function has: • • • • Function name Return type List of input arguments body
  57. 57. Functions • Function definition Return_type fun_name(list of args) { function body return statement } • A function can be defined before the main. • If defined after main, add a signature before the main. Used by compiler to check for syntax errors. • The return statement terminates the function and returns control to the calling function, is used to return a value
  58. 58. Write a function to print a message #include <stdio.h> void sayhi(void); int main() { int a,b,y; sayhi(); } void sayhi(void); { printf(‘hi from function’); }
  59. 59. Write a function to add 2 numbers #include <stdio.h> int add(int x, int y); int main() { int a,b,y; printf(“enter 2 numbers”); scanf(“%d”, &a); scanf(“%d”, &b); y=add(a,b); printf(“the sum is %d”,y) } int add(int x, int y) { int z; z=x+y; return z; } What happens in the memory during execution?
  60. 60. Passing values to a function • Call by value • Where the whole data type is sent to the function and stored as a local variable to the function, a copy is made. • Changes done in the function as no effect on the original variables of the calling function • Call by address • Only the address of the argument is sent and stored with the function • Changes in the function affects the original variable in the calling function as it is referenced by its address • The calling and called functions access the same memory address
  61. 61. Call by address • Both references the same memory location. Calling function x Called function Address of x
  62. 62. Call by value • Each has it’s own version of the argument. Calling function x Called function x
  63. 63. Assignments • Assignment 1: What is a conditional operator or ? Operator ? • Assignment 2: What are the pros and cons of using call-byvalue and call-by-address?
  64. 64. Lab • Fix the errors in error1.c and error2.c • Write a function to calculate the factorial of n, use this function in main. • Write a function to reverse the digits in a given number, use this function in main. • Write a function that draws a MagicBox table, given its dimension, use function gotoxy to e able to draw it on the screen. • Write a program that inputs 5 numbers then prints out the min and max.
  65. 65. Magic Box 6 1 8 7 5 3 2 9 4 • The size must be odd eg. 3x3, 5x5, 7x7, ……………. • Number 1 is put in row= 1 and col = (size+1)/2 • Numbers from 2 till size*size are put acc. to the following rule • If(number-1)%size ==nonzero • row-1 and col-1 • Or else • row+1
  66. 66. Static Variables and Functions
  67. 67. Scope Rules • All functions are global , no nested functions in C • A function’s code is private to the function, can’t be accessed by other functions • Variables declared inside a block of code, is local to that block. They’re destroyed at the end of the block of code. • The input arguments of a function are local variables to it, declared in the definition of the function. void func1() { int x; x=10; } void func2() { int x; x=-1999; } • The variable x is declared twice, with no relation to each other. Each one is stored in a separate memory location and func1 can’t access the x in func2.
  68. 68. Scope Rules • Global variables are declared out of all functions and can be accessed by all.
  69. 69. What is the output? int count; int main() { count=100; printf("In main, count is %dn", count); func1(); printf("After func1 call in main count is %dn", count); } void func1() { printf("In func1, count is %dn", count); func2(); printf("In func1 after func2 call, count is %dn", count); } void func2() { int count=2; printf("In func2, count is %dn", count); }
  70. 70. Static Variables • Are permanent variables within their own functions or file. • Not accessible to functions outside their function. • Maintain their values between function calls.
  71. 71. What is the output? int main() { printf(“series is %d ", series()); printf(“series is %d", series()); printf(“series is %d", series()); } int series() { int num=0; num=num+23; return num; }
  72. 72. What is the output now? int main() { printf(“series is %d", series()); printf(“series is %d", series()); printf(“series is %d", series()); } int series() { static int num=0; num=num+23; return num; }
  73. 73. Recursion
  74. 74. Recursive Functions • A function that calls itself. • Must contain a condition, to ensure a finite execution. • Example: factorial function • 5! = 5*4*3*2*1 • Using for loop int t=5, ans=1; for(; t>=1;t--) { ans*=t; } • 5! = 5*4! = 5*4*3!= ………………………..
  75. 75. Recursive Functions • Since • 5! = 5*4! = 5*4*3!= ……………………….. • Then we can use recursive functions • Where n is multiplied by factorial n-1 • What is the terminating condition ? • N reaches 1
  76. 76. double power(double x, int n) { if(n==0) return 1.0; return x*power(x, n-1); }
  77. 77. Arrays
  78. 78. Arrays • A collection of variables of the same type, stored consecutively in the memory and referenced by a single name • Single Dimensional Arrays • Datatype varname[size] • Size must be a constant , can’t be a variable and can’t be changed at runtime. • Example: • int ar[5] Allocates 5 integer addresses in the memory. • Elements are accessed by indexing the array name, index are zero based • ar[0]  1st elelment • ar[3]  4th element
  79. 79. Arrays • Take care that C doesn’t check for out-of –boundary errors. It is the programmer’s responsibility. • For loops are closely related to arrays since it is used to sequentially read/write array elements. • Remember: first element the name of the array is the address of the
  80. 80. Write a program that fills an array with numbers from 1 to 100, then print them to the screen. int main() { int x[100]; int t; for(t=0;t<100;t++) { x[t]=t+1; } for(t=0;t<100;t++) { printf(“%dn”, x*t+); } }
  81. 81. Write a program that let user input 5 employee salaries and calculate sum of salaries. int main() { float sum=0; float salary[100]; int t; for(t=0;t<5;t++) { printf(“Enter Salary: ”); scanf(“%f”, &salary*t+); } for(t=0;t<5;t++) { sum+=salary[t]; } printf(“nSum of Salaries: %f”,sum); return 0; }
  82. 82. Array Initialization • int ar[5]={1,2,3,4,5}; • int ar[]={1,2,3,4,5}; • int ar[5]={1,2,3};  the rest of the elements are initialized to zero.
  83. 83. 2D Array • datatype varname[size1][size2] • Example: int ar[5][10];  2D array of size 5 rows and 10 cols • For 2D arrays we need to use nested for loops. • Accessing a 2D array element through 2 indexes. • ar[1][2] is elemetn in 2nd row, 3rd column
  84. 84. Write a program to fill a 3x4 array with numbers 112 and print them int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for(row=0;row<3;row++) { for (col=0;col<=4;col++) { print(“%dt”,num[row][col]); } } return 0; }
  85. 85. Write a program to fill a 3x4 array with numbers 112 and print them in reverse order int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for(row=2;row>=0;row--) { for (col=3;col>=0;col--) { print(“%dt”,num[row][col]); } } return 0; }
  86. 86. Write a program to fill a 3x4 array with numbers 112 and print them in col by col order int main() { int row,col,count=1,num[3][4]; for(row=0;row<3;row++) { for (col=0;col<4;col++) { num[row][col]=count++; } } for (col=0;col<4;col++) { for(row=0row<=3;row++) { print(“%dt”,num[row][col]); } } return 0; }
  87. 87. 2D Array initialization • int ar[3][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; • int ar[3][5]= {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
  88. 88. Passing arrays to functions • We can’t pass the whole array values to a function, we just pass the address of the first location. • Examples • void fun1(int ar[]) • int fun2(char carr[]) WHY????? • void fun3(int ar[][4])  must give the second dimension.
  89. 89. What’s the output? void fun1(int x[]) { int t; for(t=0;t<5;t++) x[t]=t+1; } int main() { int x[5]={1,2}; int t; for(t=0;t<5;t++) printf("%dn", x[t]); fun1(x); for(t=0;t<5;t++) printf("%dn", x[t]); return 0; }
  90. 90. Characters and Strings
  91. 91. Characters in Memory • Characters are stored in their ascii codes. Each key on the keyboard has a representation in ascii codes. A65, a97, ~126 • C stored characters in one byte. • C divides keyboard keys into 2 categories • Normal keys: • When pressed only one byte is sent to the buffer. • 0 -> 32 control characters • 33 -> 127 printable characters • Extended keys • When pressed sends two bytes to the buffer, the first one as a null(‘0’) or 0 ascii code.
  92. 92. What is the output? int main() { char c; c=getch(); if(!c){ printf("extended key"); c=getch(); printf("%d",c); } else printf("normal key %d",c); return 0; }
  93. 93. Write a program that prints the characters from Ascii 60 to 80. int main() { int i; for(i=60; i<=80;i++) { printf(“%c  %dn”, I,I); } return 0; }
  94. 94. Character Library - ctype.h • • • • • • • • • isalnum isalph isdigit isspace isprint islower isupper toupper tolower
  95. 95. Strings • C doesn’t have a data type called strings • To define a string , define an array of characters • Example: • char a[10]  defines a string of 9 characters and a terminating null character • Must always add an element for null • char str*+=“hello”;  reserves 5+1=6 bytes to save the array • char str*+=,‘h’,’e’,’l’,’l’,’o’-; incorrect initialization since no null character to terminate string, causes unpredictable o/p • char str*6+=,‘h’,’e’,’l’,’l’,’o’-; adds a null automatically
  96. 96. printf and scanf • To print a string, instead of character by character • Use “%s” format specifier with printf() • Use puts() • To input a string, instead of character by character • Use “%s” format specifier with scanf() • Use gets(); • Remember: name of string is a pointer to first char element
  97. 97. string.h • • • • strcpy strcat strlen strcmp
  98. 98. Write a program input first and last name to print the full name int main() { char fname[10], lname[10], full[20]; scanf(“%s”,fname); scanf(“%s”, lname); strcpy(full,fname); strcat(full,” “); strcat(full,lname); printf(“%s”,full); return 0; }
  99. 99. Assignments • Assignment 1: Search for Fibonacci Numbers, write a function to generate an array of them
  100. 100. Lab • Write a program to calculate volume of 5 rooms, first save width, breadth and height of each room. • Write a function for the previous program to take the 2d array describing the rooms and return the sum of volumes. • Write a function to create a serial-number generator, where each call to the function returns a number incremented by 23. • Write a function to ask user for his name and input it character by character into an array, then print it in uppercase as a string.
  101. 101. Bonus • Write a program to print the following menu and navigate through it using UP,DOWN arrows. ESC ends the program. Enter prints the users choice. If Enter is pressed on Close, the program ends too. Open Edit Save Close
  102. 102. Pointers
  103. 103. Pointers • Is a variable carrying the address of another. • Declaring a pointer, using * unary operator int count=10; int * int_pointer; int_pointer=&count;
  104. 104. Pointers int count=10; int * int_pointer; int_pointer=&count; int x; x=*int_pointer ; • Remember • * in declaration of variable denotes a pointer declaration • * pointer_var in any statement denotes the value the pointer points at • & count denotes the address of count
  105. 105. What’s the output? int main (void) { int count = 10, x; int *int_pointer; int_pointer = &count; x = *int_pointer; printf ("count = %d, x = %dn", count, x) }
  106. 106. What’s the output? int main () { char c = 'Q'; char *char_pointer = &c; printf ("%c %cn", c, *char_pointer); c = '/'; printf ("%c %cn", c, *char_pointer); *char_pointer = '('; printf ("%c %cn", c, *char_pointer); return 0; }
  107. 107. Pointers and Arrays int values[10]={1,2,3,4,5,6,7,8,9,10}; int *pv=NULL; pv=values or pv=&values[0]; • To assign a pointer to an array we declare a pointer to the data-type of the array, then assign it to the first element
  108. 108. What’s the output? int arraySum (int array[], const int n) { int sum = 0, *ptr; int * arrayEnd = array + n; for ( ptr = array; ptr < arrayEnd; ++ptr ) sum += *ptr; return sum; } int main () { int values[10] = { 3, 7, -9, 3, 6, -1, 7, 9, 1, -5 }; printf ("The sum is %dn", arraySum (values, 10)); return 0; }
  109. 109. Accessing Elements • values[3]  *(valuesPtr+3)  to access value stored in 4th location • &value[2]  values+2  address of 3rd element. • We can use either way as they are both equivalent
  110. 110. Operations on Pointers • Add or subtract integer values from pointers. • Compare two pointers to see if they are equal or not, or if one pointer is less than or greater than another pointer. • subtracting two pointers of the same type, the result is the number of elements contained between the two pointers. • Examples: • • • • p1=&values[2]; p2=&values[7]; p1+4  &values[6] as an address to this element p2-p1  5 as an integer
  111. 111. Write a function to count string length using pointers int stringLength (char *string) { char *cptr = string; while ( *cptr ) ++cptr; return cptr - string; } int main (void) { printf ("%d ", stringLength ("stringLength test")); printf ("%d", stringLength ("")); return 0; }
  112. 112. Note • Arrays are passed to functions as addressed (Call-by-address) always int fun1(int ar[]) == int fun1(int * ar) • For better performance, • If we deal with arrays sequentially  use pointers • If we deal with arrays randomly  use Index.
  113. 113. Pointers and Functions • Revisiting Call-by-address • Pointers are passed to a function as arguments. • The contents of the address can be accessed freely from within the function.
  114. 114. Write a function to swap 2 numbers. void swap(int x, int y); int main() { int a=5, b=7; swap(a,b); printf(“a= %d and b= %d”,a,b); return 0; } void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } ?
  115. 115. Write a function to swap 2 numbers. void swap(int *x, int *y); int main() { int a=5, b=7; swap(&a, b); printf(“a= %d and b= %d”,a,b); return 0; } void swap(int *x, int *y) { int temp; temp=*x; *x=*y; *y=temp; }
  116. 116. Returning Pointers • Never return a pointer to a local variable.
  117. 117. What’s the output? void test (int *int_pointer) { *int_pointer = 100; } int main (void) { int i = 50, *p = &i; printf ("Before the call to test i = %dn", i); test (p); printf ("After the call to test i = %dn", i); return 0; }
  118. 118. What do this program do? char* match(char c, char *c); int main() { char s[10], *p, ch; gets(s); ch=getchar(); p=match(ch,s); if(*p) printf(“%s”,p); else printf(“No match found”); return 0; } char * match(char c , char*s) { while(c!=*s && *s) s++; return (s); }
  119. 119. Array of Strings/Pointers char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  120. 120. Pointers & Dynamic Allocation
  121. 121. Dynamic Allocation • A program can obtain memory while running. • Memory allocated in the heap. • Gives us the flexibility of allocating a variable amount of memory in the runtime. • stdlib.h • void * malloc(numbytes) • void free(void* )
  122. 122. Write a program to allocate an integer. int main() { int *pn=NULL; pn=(int)malloc(sizeof(int)); if(!pn) printf(“Out of memory”); else { scanf(“%d”, pn); printf(“%d”, *pn); free(pn) } }
  123. 123. Note • It is your responsibility to free any allocated memory.
  124. 124. To allocate an array int *pn; pn=(int *)malloc(10*sizeof(int)); free(pn)
  125. 125. To allocate a variable length array of names( variable length too) char **names; int len; int n =5; //number of names names = (char **)malloc(n*sizeof(char*)); for(i-0; i<n;i++){ scanf(“%d”,&len); names[i]= (char *)malloc(len*sizeof(char)); } Pointer to pointer
  126. 126. Structure
  127. 127. Structure • Is a group of variables under one name and is called an aggregate data type. • Structure Declaration: • Must declare a template to be used to create structure variables. • The declaration must be global so that all functions can use it. struct struct_name { type var1; type var2; type var3; } ;
  128. 128. Structure • Example struct addr { char street[10]; int streetNo; char city[20]; } ;
  129. 129. Declaring a struct variable • Declaration use keyword struct with name of structure • struct addr addr1; • addr1 is a variable, allocated space in the memory according to data types defined in the struct addr declaraion • Accessing elements inside structures using “.” dot notation. • addr1.streetNo=3; • strcpy(addr1.street,“New street”); • strcpy(addr1.city,“Alex”);
  130. 130. Write a program to get your address then print it on the screen struct addr{ char street[40]; int streetNo; }; int main() { struct addr myaddr; printf(“Enter your address:n Street: ”); scanf(“%s”,myaddr.street); printf(“Street No: ”); scanf(“%d”,&myaddr.streetNo); printf(“The address entered is Street %s no. %d ”, myaddr.street, myaddr.streetNo); }
  131. 131. Arrays • Declaring an array of 10 elements of struct addr • struct addr arr[10]; • To access streetNo of element 3 • arr[2].streetNo=7
  132. 132. Functions • Passing a structure as an argument to a function can be done by callby-value or call-by-address like a normal variable. • Example: void func1(struct addr x) { printf(“Address is : %d %s”, x.streetNo, x.street); } int main() { struct addr add; add.streetNo=5; strcpy(add.street,“My street”); func1(add); return 0; }
  133. 133. Pointer to structure • Declaring a pointer to structure • struct addr * padd; • To access elements, we use “->” arrow operator. • padd->streetNo=6; • Don’t forget that before using the pointer it must be assigned an address of a structure, or dynamically allocated. NEVER use unassigned pointers.
  134. 134. Example struct date { int month; int day; int year; }; int main() { struct date today, *datePtr; datePtr=&today; datePtr->month =10; datePtr->day =2; datePtr->year=2013; printf(“Today is %d-%d-%d”, datePtr>day,datePtr->month,datePtr->year); return 0; }
  135. 135. Structures containing a pointer struct mys { int *p1; int * p2; }; int i1=100, i2=200; struct mys s; s.p1=&i1; s.p2=&i2; *s.p2=88; printf ("i1 = %d, *s.p1 = %dn", i1, *pointers.p1); printf ("i2 = %d, *s.p2 = %dn", i2, *pointers.p2);
  136. 136. Nested structures and arrays • A structure can contain another structure (must be declared before it) or array. • Example: struct addr{ char street[10]; int streetNo; }; struct student{ char name[20]; int marks[5]; struct addr homeaddress; };
  137. 137. Nested structures and arrays • To access elements in a variable of type struct employee struct student st1; strcpy(st1.name,“Ahmed”); st1.marks[3]=100; st1.homeaddress.streetNo=20;
  138. 138. Assignments • Assignment 1: How can we initialize Structures and Array of structures? • Assignment 2: What are pointers to functions • Assignment 3: Read on linked lists on page 244. Write a program to traverse a Linked List and Search for a value in it.
  139. 139. Lab • Write a function trim4 that takes a string and truncates the characters after the 4th and returns the new truncated string without changing the original. • Write a function that reverse a string using pointers. • Create the following structures: • date(int day, int month , int year), • Student(int serial, char[] name, int marks) • school(student* students, int numofStudents , char[] address, char name[] ) • Write a function to fill data of a school. • Write a function to print data of a school. • Write a program to fill and print data of n schools (Bonus))
  140. 140. Bonus • Add Highlighting to the previous Menu bonus • Hint: Search for the following functions can be helpful textattr(), textcolor(), textbackground()

×