├── hello_world.h ├── tpcs.h ├── stringsfile ├── SCRIPT ├── 07_more_looping.md ├── 14_more_complexity.md ├── combine-mds.sh ├── 00_A_course_info.md ├── 16_linked_list.md ├── 17_mergesort.md ├── 15_structure.md ├── 11_multid_arrays.md ├── 09_strings.md ├── 18_quicksort.md ├── Makefile ├── 00_books.md ├── 00_motivation.md ├── 13_complexity_sorting_searching.md ├── 12_functions.md ├── 06_looping.md ├── 10_strings_libraries.md ├── 08_arrays.md ├── 05_conditional_indenting.md ├── 03_binary_rep.md ├── 04_confidence_fileio.md ├── 02_expr_stmt_var.md └── 01_intro_crud_compile.md ├── CLASS ├── test_Assn_1.pdf ├── test_Assn_2.pdf ├── Function-call.pptx ├── LinkedLists.pptx ├── BinarySearch_MergeSort.pptx ├── in_class_programming_exercise_1.pdf ├── in_class_programming_exercise_2.pdf ├── using-make │ ├── Makefile.v00 │ ├── ops.h │ ├── Makefile.v01 │ ├── Makefile.v1 │ ├── ops.c │ ├── mymain.c │ ├── Makefile.v3 │ └── Makefile.v2 ├── 09-19.txt ├── 09-26.txt ├── 10-27.txt ├── 08-26.txt ├── 09-12.txt ├── 08-29.txt ├── 10-20.txt ├── 10-03.txt ├── 10-31.txt ├── 10-17.txt ├── 11-07.txt ├── 09-22.txt ├── 10-06.txt ├── in_class_programming_exercise_3.txt ├── 09-15.txt ├── 09-29.txt ├── material_outside_KR ├── 09-01.txt ├── 00-future.txt ├── in_class_programming_exercise_4.txt ├── 09-08.txt ├── notables.txt ├── test_Assn_2_answers.txt ├── 09-05-exercises.txt ├── in_class_programming_exercise_5.txt └── in_class_programming_exercise_extra.txt ├── slides ├── 15-FileIO.pptx ├── 08-Pointers.pptx ├── 14-LinkedLists.pptx ├── 09-for-do-loops.pptx ├── 13-Structs-Unions.pptx ├── 16-Miscellaneous.pptx ├── 00-x-GettingStarted.pptx ├── 02-if-switch-while.pptx ├── 09-ArrayExploration.pptx ├── 10-enum-define-typedef.pptx ├── 11-Three-Basic-Sorts.pptx ├── 00-Intro-memory-function.pptx ├── 00-x-Flowcharts-to-code.pptx ├── 06-Operators-Precedence.pptx ├── 00-x-Model-of-Programming.pptx ├── 12-BinarySearch_MergeSort.pptx ├── 04-Variables-scope-storage-class.pptx ├── 07-Arrays-char-ASCII-strings-fns.pptx ├── 01-operators-assignment-functions.pptx ├── 03-functions-params-return-values.pptx ├── 05-Function-call-detailed-recursion.pptx ├── 05a-Recursion-Another-Visualization.pptx └── Flowcharts │ ├── F02-factorial.fprg │ ├── F03-sumofnumbers.fprg │ ├── F00-quad1.fprg │ ├── F04-dotproduct.fprg │ ├── F05-isprime.fprg │ ├── F01-integrate.fprg │ ├── F00-quad2.fprg │ └── integrate.fprg ├── hello_world.c ├── print_next_char.c ├── MiscCProgs-2025 ├── points ├── integrate.c ├── float.c ├── small.c ├── time_to_minutes.c ├── integrate1.c ├── index.txt ├── mmpy.py ├── studentschocolates.c ├── mmc.c ├── vadasdosas.c ├── pouringwatersim.c ├── 15puzzle.c ├── towersim.c ├── GtGrLi.c └── ll-examples.c ├── threePieces.c ├── 3np1.c ├── graph_info ├── for_break_continue.c ├── main_argc.c ├── tpcs.c ├── arraySizePtr.c ├── list_avg_f.c ├── list_avg_array.c ├── list_avg_d.c ├── funcs_params.c ├── fileio_simple.c ├── const.c ├── limit_explore.c ├── stats.c ├── static.c ├── integrate.c ├── timeutil.h ├── address_explore.c ├── fillin_file.c ├── fillin_findmax_loop.c ├── fillin_if.c ├── timeutil.c ├── simple_timing.c ├── funcs_scope.c ├── fillin_while.c ├── eratosthenes_simple.c ├── list_avg_w.c ├── split_sentence.c ├── discriminant.c ├── matrix_ops.c ├── varargs.c ├── funcs_scope2.c ├── apnf.c ├── fact.c ├── conversions.c ├── do_op.c ├── matmul.c ├── simple_event_count.c ├── eratosthenes.c ├── lcm.c ├── find_max.c ├── related_arrays.c ├── gcd.c ├── shortcircuit.c ├── linked_list_intro.c ├── simple_malloc.c ├── graph_am.c ├── macro_substitution.c ├── union_simple.c ├── msort.c ├── Makefile ├── sort_indices.c ├── eratosthenes_timer.c ├── arraysptr.c ├── qsort.c ├── simple_expressions.c ├── funcs.c ├── search.c ├── fileio.c ├── array_ops.c ├── very_first.c ├── qsort_extraspace.c ├── queens.c ├── minor.c ├── ptrs-exp.c ├── fillin_simple.c ├── fillin_qsort.c ├── recursion_simple.c ├── array_struct.c ├── swap_story.c ├── matrix_inv.c ├── pointer_simple.c ├── input_output.c ├── string_simple.c └── linked_list.c /hello_world.h: -------------------------------------------------------------------------------- 1 | #define NAME "Vatsa" 2 | -------------------------------------------------------------------------------- /tpcs.h: -------------------------------------------------------------------------------- 1 | int test(); 2 | 3 | extern int num; 4 | -------------------------------------------------------------------------------- /stringsfile: -------------------------------------------------------------------------------- 1 | adam 2 | built 3 | castles 4 | in 5 | the 6 | west 7 | -------------------------------------------------------------------------------- /SCRIPT/07_more_looping.md: -------------------------------------------------------------------------------- 1 | 2 | # More Practice Exercises 3 | TBD 4 | -------------------------------------------------------------------------------- /CLASS/test_Assn_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/test_Assn_1.pdf -------------------------------------------------------------------------------- /CLASS/test_Assn_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/test_Assn_2.pdf -------------------------------------------------------------------------------- /slides/15-FileIO.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/15-FileIO.pptx -------------------------------------------------------------------------------- /CLASS/Function-call.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/Function-call.pptx -------------------------------------------------------------------------------- /CLASS/LinkedLists.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/LinkedLists.pptx -------------------------------------------------------------------------------- /slides/08-Pointers.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/08-Pointers.pptx -------------------------------------------------------------------------------- /slides/14-LinkedLists.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/14-LinkedLists.pptx -------------------------------------------------------------------------------- /slides/09-for-do-loops.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/09-for-do-loops.pptx -------------------------------------------------------------------------------- /slides/13-Structs-Unions.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/13-Structs-Unions.pptx -------------------------------------------------------------------------------- /slides/16-Miscellaneous.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/16-Miscellaneous.pptx -------------------------------------------------------------------------------- /slides/00-x-GettingStarted.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/00-x-GettingStarted.pptx -------------------------------------------------------------------------------- /slides/02-if-switch-while.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/02-if-switch-while.pptx -------------------------------------------------------------------------------- /slides/09-ArrayExploration.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/09-ArrayExploration.pptx -------------------------------------------------------------------------------- /CLASS/BinarySearch_MergeSort.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/BinarySearch_MergeSort.pptx -------------------------------------------------------------------------------- /slides/10-enum-define-typedef.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/10-enum-define-typedef.pptx -------------------------------------------------------------------------------- /slides/11-Three-Basic-Sorts.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/11-Three-Basic-Sorts.pptx -------------------------------------------------------------------------------- /slides/00-Intro-memory-function.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/00-Intro-memory-function.pptx -------------------------------------------------------------------------------- /slides/00-x-Flowcharts-to-code.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/00-x-Flowcharts-to-code.pptx -------------------------------------------------------------------------------- /slides/06-Operators-Precedence.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/06-Operators-Precedence.pptx -------------------------------------------------------------------------------- /slides/00-x-Model-of-Programming.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/00-x-Model-of-Programming.pptx -------------------------------------------------------------------------------- /slides/12-BinarySearch_MergeSort.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/12-BinarySearch_MergeSort.pptx -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/in_class_programming_exercise_1.pdf -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/CLASS/in_class_programming_exercise_2.pdf -------------------------------------------------------------------------------- /hello_world.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "hello_world.h" 3 | 4 | int main(){ 5 | 6 | printf("Hello dear %s\n",NAME); 7 | } 8 | -------------------------------------------------------------------------------- /slides/04-Variables-scope-storage-class.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/04-Variables-scope-storage-class.pptx -------------------------------------------------------------------------------- /slides/07-Arrays-char-ASCII-strings-fns.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/07-Arrays-char-ASCII-strings-fns.pptx -------------------------------------------------------------------------------- /CLASS/using-make/Makefile.v00: -------------------------------------------------------------------------------- 1 | # Makefile.v00 2 | # We list how to build the executable 3 | myprog: 4 | gcc ops.c mymain.c -o myprog 5 | 6 | -------------------------------------------------------------------------------- /CLASS/using-make/ops.h: -------------------------------------------------------------------------------- 1 | void testf(); 2 | void testdiv(); 3 | int test(); 4 | enum ranks { first=100, second=102, third=101, fourth }; 5 | 6 | -------------------------------------------------------------------------------- /print_next_char.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | printf("Give me a character"); 4 | char c = getchar(); 5 | putchar(c+1); 6 | } 7 | -------------------------------------------------------------------------------- /slides/01-operators-assignment-functions.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/01-operators-assignment-functions.pptx -------------------------------------------------------------------------------- /slides/03-functions-params-return-values.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/03-functions-params-return-values.pptx -------------------------------------------------------------------------------- /slides/05-Function-call-detailed-recursion.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/05-Function-call-detailed-recursion.pptx -------------------------------------------------------------------------------- /slides/05a-Recursion-Another-Visualization.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rbadrinath/FCP/HEAD/slides/05a-Recursion-Another-Visualization.pptx -------------------------------------------------------------------------------- /MiscCProgs-2025/points: -------------------------------------------------------------------------------- 1 | 0.0 0.0 2 | 0.0 6.0 3 | 8.0 0.0 4 | 8.0 6.0 5 | 5.0 4.0 6 | 3.0 5.0 7 | 6.0 1.0 8 | 4.0 2.0 9 | 5.0 3.0 10 | 2.0 5.0 11 | -------------------------------------------------------------------------------- /CLASS/using-make/Makefile.v01: -------------------------------------------------------------------------------- 1 | # Makefile.v01 2 | # The target line included the dependencies 3 | myprog: ops.c mymain.c 4 | gcc ops.c mymain.c -o myprog 5 | 6 | -------------------------------------------------------------------------------- /threePieces.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "tpcs.h" 3 | 4 | 5 | // Where are x and m declared 6 | void main(){ 7 | int i; 8 | x++; 9 | num++; 10 | i = test(); 11 | printf("%d\n",i); 12 | } 13 | -------------------------------------------------------------------------------- /3np1.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | int n = 29; 4 | while ( n != 1 ) { 5 | printf(" %d \n",n); 6 | if ( n%2 == 0 ) 7 | n = n/2; 8 | else 9 | n = 3*n + 1 ; 10 | } 11 | printf(" %d \n",n); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /SCRIPT/14_more_complexity.md: -------------------------------------------------------------------------------- 1 | # Algorithm Complexity Calculation 2 | * Revisit the three sorting algorithms 3 | * Searching, linear and binary search 4 | * Analysis including that of recursion 5 | * Using a recursion tree for analysis 6 | -------------------------------------------------------------------------------- /CLASS/09-19.txt: -------------------------------------------------------------------------------- 1 | Done: 2 | We revised material from last class. 3 | We also talked about recursion. 4 | We saw that recursion is no different from other funciton calls. 5 | We understand now the call stack. 6 | 7 | The planned stuff moved to next class. 8 | -------------------------------------------------------------------------------- /SCRIPT/combine-mds.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "NOTE: This file is automatically generated by running make" 3 | for i in *.md ; do 4 | echo "" 5 | echo "" 6 | echo "[comment]: # (---------" $i "---------)" 7 | cat $i 8 | echo "" 9 | echo "" 10 | done 11 | -------------------------------------------------------------------------------- /CLASS/09-26.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | 1. Recall last class : arrays, pointers and arrays as function parameters 3 | 2. We do a small programming exercise to revise these concepts 4 | 3. strings as arrays of characters with a special marker 5 | 6 | Pushed to next class: 7 | 4. FILE IO 8 | -------------------------------------------------------------------------------- /CLASS/using-make/Makefile.v1: -------------------------------------------------------------------------------- 1 | # We list how to build the .o 2 | # We list how to build the executable 3 | mymain.o: mymain.c ops.h 4 | gcc -c mymain.c 5 | 6 | ops.o: ops.c ops.h 7 | gcc -c ops.c 8 | 9 | myprog: ops.o mymain.o 10 | gcc ops.o mymain.o -o myprog 11 | 12 | -------------------------------------------------------------------------------- /graph_info: -------------------------------------------------------------------------------- 1 | 0 1 1 1 1 2 | 1 0 0 0 1 3 | 1 0 0 0 1 4 | 1 0 0 0 1 5 | 1 1 1 1 0 6 | 7 | 8 | 0 and 4 are adjacent too all other nodes (1 2 and 3) and to eachother. 9 | no other nodes are adjacent 10 | Here we have set a[i][i] (the diagonal values) to zero, just a convention 11 | -------------------------------------------------------------------------------- /SCRIPT/00_A_course_info.md: -------------------------------------------------------------------------------- 1 | # Course Information 2 | This is originally motivated by creating contents for the course 3 | _Fundamentals of Computing and Programming_ [(see here)](https://www.isibang.ac.in/~adean/infsys/database/Bmath/FCP.html) for the first term of 4 | the academic year 2022-2023. 5 | -------------------------------------------------------------------------------- /for_break_continue.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main(){ 4 | int i,n; 5 | scanf("%d",&n); 6 | for(i=0;i= 3 ) 9 | break; // change to continue to see what happens 10 | */ 11 | printf("%d\n",i); 12 | } 13 | printf("Outisde : %d\n",i); 14 | } 15 | -------------------------------------------------------------------------------- /SCRIPT/16_linked_list.md: -------------------------------------------------------------------------------- 1 | # Linked List 2 | * Linked list as a useful higher level data structure 3 | * (So called recursive structure notion) 4 | * advantages over an array 5 | * Example implementation 6 | * Insert at the beginning 7 | * Insert at the end 8 | * print elements of the linked list 9 | -------------------------------------------------------------------------------- /SCRIPT/17_mergesort.md: -------------------------------------------------------------------------------- 1 | # Advanced sort - Mergesort 2 | * Algorithm - This is the more important part 3 | * Plan of the algorithm 4 | * Simple split 5 | * The recursion 6 | * How to merge two arrays - what is the base case (no further recursive calls needed) 7 | * Lets fill in the code 8 | * see msort.c 9 | -------------------------------------------------------------------------------- /main_argc.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(int argc, char * argv[]){ 3 | int i; 4 | for ( i=0;argv[i]!=NULL;i++) 5 | printf("%d %s\n",i, argv[i]); 6 | 7 | /* 8 | for (i=0;i 2 | // this #include "tcps.h" declares the function prototype of test() 3 | // also declares the global extern int num 4 | #include "tpcs.h" 5 | 6 | int num= 0B00001000; 7 | int x=1; // what if we made x to be static 8 | 9 | int test(){ 10 | x++; 11 | return num; 12 | } 13 | -------------------------------------------------------------------------------- /CLASS/using-make/ops.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include "ops.h" 4 | 5 | void testf(){ 6 | int i=0; 7 | int j=1; 8 | if (i < j) 9 | printf("yes"); 10 | } 11 | 12 | void testdiv(){ 13 | if ( 5/2 == 5.0/2 ) 14 | printf("YES\n"); 15 | else 16 | printf("NO\n"); 17 | } 18 | int test(){ 19 | return 0B00001000; 20 | } 21 | -------------------------------------------------------------------------------- /arraySizePtr.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main(){ 4 | int a[40]; 5 | int *p[40]; 6 | int (*q)[40]; 7 | // usage 8 | p[0]=a; 9 | q=a; 10 | printf(" p = %p\n p+1 = %p\n diff = %d\n",p,p+1,(p+1) - p); 11 | printf(" sizeof(a) = %lu\n sizeof(p) = %lu \n sizeof(q) %lu\n", 12 | sizeof(a), sizeof(p),sizeof(q)); 13 | } 14 | -------------------------------------------------------------------------------- /list_avg_f.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i; 5 | int sum=0; 6 | int n; 7 | int x; 8 | printf("Howmany numbers to sum? "); 9 | scanf("%d",&n); 10 | printf("Enter %d numbers to sum ",n ); 11 | for (i=0; i < n ; i ++){ 12 | scanf("%d",&x); 13 | sum+=x; 14 | } 15 | printf("Sum is %d\n",sum); 16 | } 17 | -------------------------------------------------------------------------------- /CLASS/10-27.txt: -------------------------------------------------------------------------------- 1 | Done: 2 | * Learn linked lists: Now see linked_list.c 3 | do the standard linked_list operations 4 | insert a new value, 5 | read a value, 6 | search a value, 7 | update a value, 8 | delete a value 9 | 10 | * Intro to graph representation and graph traversal 11 | see graph_am.c and graph_info 12 | 13 | -------------------------------------------------------------------------------- /CLASS/using-make/mymain.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ops.h" 3 | 4 | void main(){ 5 | int i; 6 | i = test(); 7 | printf("%d\n",i); 8 | int n=0; 9 | n?printf("A\n"):printf("B\n"); 10 | n++; 11 | n?printf("A\n"):printf("B\n"); 12 | 13 | float p1x,p1y; 14 | testdiv(); 15 | enum ranks r=fourth; 16 | printf("%d\n",r); 17 | } 18 | -------------------------------------------------------------------------------- /list_avg_array.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i; 5 | int sum=0; 6 | int n; 7 | int arr[100]; 8 | printf("Howmany numbers to sum? "); 9 | scanf("%d",&n); 10 | printf("Enter %d numbers to sum ",n ); 11 | for (i=0; i < n ; i ++){ 12 | scanf("%d",&arr[i]); 13 | sum+=arr[i]; 14 | } 15 | printf("Sum is %d\n",sum); 16 | } 17 | -------------------------------------------------------------------------------- /list_avg_d.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i; 5 | int sum=0; 6 | int n; 7 | int x; 8 | printf("Howmany numbers to sum? "); 9 | scanf("%d",&n); 10 | printf("Enter %d numbers to sum ",n ); 11 | i=0; 12 | do { 13 | scanf("%d",&x); 14 | sum+=x; 15 | 16 | i=i+1; 17 | } while (i < n); 18 | printf("Sum is %d\n",sum); 19 | } 20 | -------------------------------------------------------------------------------- /funcs_params.c: -------------------------------------------------------------------------------- 1 | #include 2 | // Aim show how functions and their prototypes work 3 | // notion of declare before use - just move around the function 4 | // same holds for variables. 5 | // show prototytpe 6 | // show scope 7 | 8 | void say(char * str){ 9 | printf("%s\n",str); 10 | } 11 | 12 | 13 | void main(){ 14 | say("hi"); 15 | say("bye"); 16 | } 17 | -------------------------------------------------------------------------------- /CLASS/08-26.txt: -------------------------------------------------------------------------------- 1 | 1. Motivation, book, other introductory stuff 2 | 2. Environment / tools familiarity - cp, mv, gedit, rm, cd; a bit about tree structure directory hiarchy 3 | 3. Download, compile find_max.c 4 | 4. Go through code find_max.c : The notion of functions as procedures with parameters; the notion of main(). 5 | 5. After class - MS Windows vs Ubuntu and environment questions 6 | -------------------------------------------------------------------------------- /fileio_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | int y=99,n=99; 4 | FILE * f1 = fopen("/tmp/blah","r"); 5 | n = fscanf(f1," %d", &y); 6 | if ( n == EOF ){ 7 | perror("try to read:"); 8 | } 9 | printf(" I got : %d items %d\n",n,y); 10 | fclose(f1); 11 | 12 | 13 | FILE * f2 = fopen("/tmp/blah","w"); 14 | int x=y+1; 15 | fprintf(f2,"%d",x); 16 | fclose(f2); 17 | } 18 | -------------------------------------------------------------------------------- /const.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printout(int const x, int const y){ 4 | x = 10, y=30; // These assignments wont work, compile and see 5 | printf("x = %d and y = %d\n",x,y); 6 | } 7 | 8 | void main(){ 9 | int const x=1100; 10 | int const * p; 11 | int const * q; 12 | int * const pp; 13 | int * const qq; 14 | int i=10; 15 | int j=20; 16 | 17 | printout(50,100); 18 | } 19 | -------------------------------------------------------------------------------- /SCRIPT/15_structure.md: -------------------------------------------------------------------------------- 1 | # Structure and Unions in C 2 | * Simple notions of structure type - declaration, access, via pointers? 3 | * Structure examples. 4 | * Typedef and its use in structures. Example is simple-timing.c 5 | * Arrays of structures. 6 | * Notions of declarations and typedef 7 | * Array of structure and multiple arrays comparision 8 | * Examples using structures, arrays, functions 9 | -------------------------------------------------------------------------------- /CLASS/09-12.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | 3 | Prototypes and declarations 4 | The notion of addresses as values 5 | The notion of pointer variable types to hold address values 6 | Examples of using pointers swap two variables. 7 | swapping pointers; we also saw pointers to pointers just for fun. 8 | We know why things go wrong if in scanf we do not give address of a variable 9 | 10 | QUIZ 1 done 11 | -------------------------------------------------------------------------------- /limit_explore.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void main(){ 4 | int j,k; 5 | // printf("%f %f",(float) (1/5), 1/5.0); 6 | int i=1; 7 | j=0; 8 | while( i > 0) { 9 | i<<=1; 10 | j++; 11 | printf("%2d %d \n",j,i); 12 | } 13 | printf("Here sizeof(int) is %d\n",(int) sizeof(int)); 14 | printf("INT_MAX is(hex) %x\n",INT_MAX); 15 | printf("INT_MAX is(dec) %d\n",INT_MAX); 16 | } 17 | -------------------------------------------------------------------------------- /MiscCProgs-2025/integrate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | float gf(float x){ 4 | return exp(-x*x); 5 | } 6 | int main(){ 7 | float a,b; 8 | scanf("%f%f",&a,&b); 9 | int steps=1000; 10 | float h=(b-a)/steps; 11 | float sum=0; 12 | float x=a; 13 | for(int i=0;i 2 | int main(){ 3 | int a1= 22; 4 | int a2= 8; 5 | int a3= 4; 6 | 7 | printf("Sum is %d \n",a1+a2+a3); //expect 34 8 | printf("Average is %f \n", (a1+a2+a3)/3.0); //expect 11.333333.... 9 | printf("The sum of the first two modulo the third is %d \n", 10 | (a1+a2) % a3); //expect 2 11 | /* 12 | printf("median is %d", .... ); 13 | printf("standard deviation is %f \n", ..... ); 14 | */ 15 | 16 | } 17 | -------------------------------------------------------------------------------- /static.c: -------------------------------------------------------------------------------- 1 | #include 2 | int counter(){ 3 | // static variables are: 4 | // scope: like local variables in terms of scope or visibility; 5 | // life: like global they exist throughout 6 | int static c=0; // done only once, just like a global 7 | c++; // cod executes on all calls, as usual 8 | } 9 | 10 | void main(){ 11 | for(int i=0;i<10;i++) 12 | counter(); // Here we are just neglecting the reurn value 13 | printf("%d\n",counter()); 14 | } 15 | -------------------------------------------------------------------------------- /CLASS/10-31.txt: -------------------------------------------------------------------------------- 1 | Done: 2 | * from last class Revisit graph representation and graph traversal 3 | see graph_am.c and graph_info 4 | 5 | - With an early introduction to the big-O notation O(n) 6 | 7 | * Search: 8 | Linear search in linked list and array 9 | Advantage of search when array is sorted 10 | Binary search. 11 | 12 | See the code in search.c 13 | 14 | - Analysis and the big-O notation 15 | 16 | * Introduction to sorting ... very first ideas of insert sort 17 | -------------------------------------------------------------------------------- /integrate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | float const PI=3.14159; 5 | float const delta=0.1; // step size 6 | float const start=0, end=2*PI; // integration limits 7 | float a=start, e=end; 8 | float t; float s = 0; 9 | while( a < e) { 10 | float t= sin(a); 11 | // printf("%f term is %f\n",a,t); 12 | s = t*delta + s; 13 | a=a + delta; 14 | } 15 | printf("Integral sin(x) from %f to %f is %f\n",start, end, s); 16 | } 17 | -------------------------------------------------------------------------------- /timeutil.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Must have a structure of the following type to use the functions 5 | typedef struct { 6 | struct timeval start; 7 | struct timeval end; 8 | } TimeStruct; 9 | 10 | // Log the start time 11 | void set_time_start(TimeStruct * times); 12 | // Log the end time 13 | void set_time_end(TimeStruct * times); 14 | // get the difference of the two times in microseconds 15 | long get_time_usage(TimeStruct * times); 16 | -------------------------------------------------------------------------------- /CLASS/10-17.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | * main() can take parameters too. has an array of strings 3 | * main() can have an integer return value too. 4 | see main_args.c 5 | argc, argv[], it includes the name of the program too 6 | return is related to exit value! 7 | * Learn to use free 8 | see simple_malloc.c 9 | Note: Once freed a memory shouldn't be used - unexpected result 10 | * Learn structures 11 | go through simple_struct.c 12 | * Learn linked lists 13 | We saw an introductory example 14 | -------------------------------------------------------------------------------- /CLASS/11-07.txt: -------------------------------------------------------------------------------- 1 | Done: 2 | 1. Recall information about Big-O notation form the examples 3 | of binary search and graphs. 4 | 5 | 2. Basic searching 6 | * Insertion Sort 7 | * Selection Sort 8 | - For each we did the core concept and code in class. 9 | - basic_sort.c is updated with the simplified versions of these as 10 | discussed in class. You may also see all the versions for 11 | your understanding. 12 | 13 | - we discussed that the selection sort algorithms was O(n^2) 14 | 15 | -------------------------------------------------------------------------------- /address_explore.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int g; 5 | 6 | 7 | void testaddress(int a, int b, int c){ 8 | int i,j,k; 9 | printf("function locals: %p %p %p\n",&i,&j,&k); 10 | printf("function params: %p %p %p\n",&a,&b,&c); 11 | return; 12 | } 13 | 14 | void main(){ 15 | int i,j,k; 16 | 17 | printf("main locals: %p %p %p\n",&i,&j,&k); 18 | printf("Global : %p\n",&g); 19 | printf("dynamic : %p\n",malloc(sizeof(int))); 20 | testaddress(i,j,k); 21 | } 22 | -------------------------------------------------------------------------------- /fillin_file.c: -------------------------------------------------------------------------------- 1 | #include 2 | void using_file(){ 3 | // Declare the number variables 4 | // Declare the file pointer 5 | // Now do the file opening 6 | // .... 7 | // Now modify the rest below to read from the input file 8 | // and write to the output file 9 | scanf("%d",&n, &m); 10 | avg = (n + m ) / 2.0 ; 11 | printf("The average is %f\n",avg); 12 | 13 | // Make sure the input file exists before running this program 14 | } 15 | void main(){ 16 | using_file(); 17 | } 18 | -------------------------------------------------------------------------------- /fillin_findmax_loop.c: -------------------------------------------------------------------------------- 1 | #include 2 | // PURPOSE: 3 | // Keep reading numbers and adding them 4 | // together until the sum is greater than 100 5 | // At that point print the sum and exit 6 | void main(){ 7 | // Declarations 8 | // initialize the sum to be 0 9 | // in a loop (for ? while ? do-while ?) do the following 10 | // read the next number 11 | // add it to the sum 12 | // repeat if sum is <=100 13 | // 14 | // Once done with the loop find the average and print it 15 | } 16 | -------------------------------------------------------------------------------- /fillin_if.c: -------------------------------------------------------------------------------- 1 | #include 2 | /* This program reads three numbers and checks if 3 | * the second number is between the first and the third 4 | */ 5 | 6 | int main() { 7 | // Declare 3 integers a,b and c 8 | 9 | printf("Give me 3 numbers "); 10 | scanf(); // read three integers call them 11 | 12 | if ( a > b ) { 13 | // if a > b then check b > c and decide to print "YES" or "NO" 14 | } else { 15 | // if a < b then check b < c and decide to print "YES" or "NO" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /SCRIPT/11_multid_arrays.md: -------------------------------------------------------------------------------- 1 | # Multi-dimensional arrays 2 | ## Objectives 3 | * more on pointers and arrays 4 | * multi dimentional arrays 5 | 6 | ## Declaratios and usage 7 | * Arrays of pointers 8 | * argv and argc 9 | * Multiple arrays in a program EXERCISE related\_arrays.c 10 | * Multidimentional arrays 11 | * More than two dimensions 12 | 13 | ## Examples and Execises 14 | * Matrix multiplication 15 | * matmul.c 16 | * matrix\_inv.c 17 | * matrix\_ops.c 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /timeutil.c: -------------------------------------------------------------------------------- 1 | #include "timeutil.h" 2 | void set_time_start(TimeStruct * times){ 3 | struct rusage usage; 4 | int r = getrusage(RUSAGE_SELF , &usage); 5 | times->start=usage.ru_utime; 6 | } 7 | void set_time_end(TimeStruct * times){ 8 | struct rusage usage; 9 | int r = getrusage(RUSAGE_SELF , &usage); 10 | times->end=usage.ru_utime; 11 | } 12 | long get_time_usage(TimeStruct * times){ 13 | return times->end.tv_sec*1000000+times->end.tv_usec 14 | - times->start.tv_sec*1000000+-times->start.tv_usec; 15 | } 16 | -------------------------------------------------------------------------------- /CLASS/using-make/Makefile.v3: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | EXECS=myprog 3 | OBJS=mymain.o ops.o 4 | # We use the fact that by default gcc is used to create .o file from .c file 5 | # so the rules for the .o are missing 6 | # This is the first target (hence 'make' called without a target does this) 7 | default: myprog 8 | 9 | mymain.o: mymain.c ops.h 10 | 11 | ops.o: ops.c ops.h 12 | 13 | myprog: ops.o mymain.o 14 | gcc ops.o mymain.o -o myprog 15 | 16 | clean: 17 | rm -f $(OBJS) $(EXECS) 18 | #same as rm -f mymain.o ops.o myprog 19 | -------------------------------------------------------------------------------- /simple_timing.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "timeutil.h" 3 | #define ILIMIT 10000 4 | #define JLIMIT 80000 5 | 6 | 7 | TimeStruct times; 8 | 9 | #define METHOD 2 10 | 11 | int main(){ 12 | int i,j,k,l,m,n; 13 | set_time_start(×); 14 | for(i=0;iB?A:B 4 | 1. "break" and "continue" in loops 5 | 2. More loops 'for' and 'do.. while' 6 | Some examples like printing in reverse 7 | 4. switch/case 8 | 5. arrays declaration, initialization and use, indexing 9 | arrays as addresses 10 | arrays as parameters to functions 11 | -- se apnf.c 12 | 13 | Pushed to next class: 14 | 6. Using Files for IO 15 | Using files for IO 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /funcs_scope.c: -------------------------------------------------------------------------------- 1 | #include 2 | // Aim show how functions and their prototypes work 3 | // notion of declare before use - just move around the function 4 | // same holds for variables. 5 | // show prototytpe 6 | // show scope 7 | 8 | char * str = "global hello" ; 9 | 10 | void say(char * str){ 11 | printf("%s\n",str); 12 | } 13 | 14 | void print_mystr(){ 15 | printf("%s\n",str); 16 | } 17 | 18 | void main(){ 19 | char * str = "local hello"; 20 | say("hi"); 21 | say("bye"); 22 | say(str); 23 | print_mystr(); 24 | } 25 | -------------------------------------------------------------------------------- /SCRIPT/09_strings.md: -------------------------------------------------------------------------------- 1 | # Strings and Arrays 2 | * Notion of strings and arrays 3 | * STRINGS of characters 4 | * Characters strings are just arrays 5 | * Notion of end of string marker 6 | * Can you now read a string and reverse it? 7 | * Can you now concatenate two strings into a third string? 8 | * Can you shuffle two strings? 9 | 10 | ## End of class check 11 | * Student should be able to walk through a string as an array and print 12 | its characters one by one and know when it ends. 13 | * Student should be able to capitalize a string of characters. 14 | -------------------------------------------------------------------------------- /SCRIPT/18_quicksort.md: -------------------------------------------------------------------------------- 1 | # Advanced Sorting - Quicksort 2 | 3 | ## The Algorithm 4 | * Plan of the algorithm - This is the more important part 5 | * How to get a good pivot (middle most?, worst ?) 6 | * How to partition around the pivot (a) with extra space vs (b) in-place 7 | 8 | ## Exercise 9 | * Start with fillin\_qsort.c (with extra space) answer is in qsort\_extraspace.c 10 | 11 | ## Finishing the algorithm 12 | * Hope and probability 13 | * The recursion - what is the base case (no further recursive calls needed) 14 | * Lets fill in the code 15 | * See qsort.c 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /fillin_while.c: -------------------------------------------------------------------------------- 1 | #include 2 | /* This program reads a number of numbers and sums them up until the sum 3 | * exceeds 100 4 | */ 5 | 6 | int main() { 7 | // Declare the number of numbers "n" 8 | // Declare the individual numbers to read 9 | // Declare the sum 10 | printf("How many numbers ? "); 11 | scanf(); // read three integers call them 12 | printf("Give me the numbers one by one "); 13 | // initialize ?? 14 | while ( ) { // get the next number until this condition is met 15 | scanf(); // read the number 16 | // add it to the sum 17 | } 18 | // print the sum 19 | 20 | } 21 | -------------------------------------------------------------------------------- /CLASS/10-06.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | 1. Revist 09-29.txt wiith emphasis on the exercises mentioned. 3 | 2. Relook at the in class programming exercise 3. 4 | - Can we use sscanf 5 | - Can we use string library functions. 6 | - atoi 7 | - using malloc in this context - we saw how to return an 8 | array of pointers to strings each containing a word 9 | - calloc, an equivalent of malloc 10 | 3. Ref SCRIPT/ for more examples on arrays 11 | 4. Two dimentional arrays matrix_ops.c matmul.c 12 | also see matrix_inv.c 13 | We understood row major form; how 2-D arrays are passed as parameters 14 | 15 | -------------------------------------------------------------------------------- /MiscCProgs-2025/float.c: -------------------------------------------------------------------------------- 1 | #include 2 | // a simple program to illustrate the difference between actual real numbers 3 | // and C's (and teh CPUs) floating point numbers 4 | // Idea is to define a few real numbers and do simple arithmetic 5 | int main(){ 6 | //float a=1.07, b=3.1412, c=2.71823, d=6.023; 7 | //float a=6.6, b=3.1412, c=2.7182, d=6.023; 8 | float a=6.62632293, b=3.1415932982, c=2.718234894, d=6.023345; 9 | 10 | // If these were real numbers, then by associativity 11 | // we should see the same number twice below 12 | printf("%f %f %f\n", a*(b*(c*d)),((a*b)*c)*d,(a*b)*(c*d)); 13 | } 14 | -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_3.txt: -------------------------------------------------------------------------------- 1 | Write a function for the following: 2 | Consider the string : 3 | 4 | "This is the \n house \t\t that Jack \n built" 5 | char s[100] = " kkkkk " ; 6 | 7 | It has newlines and tabs in it. 8 | 9 | Initialize an array to this string. 10 | 11 | From the array now just find individual words and write them out to the screen 12 | one line each. 13 | ------------------------------------------------------ 14 | As a second step now, only print those that are alpha-numeric. 15 | So for example " Hello Mr 123, how;are you" will simple treat 16 | comma and semicolon as if they were blanks. 17 | -------------------------------------------------------------------------------- /SCRIPT/Makefile: -------------------------------------------------------------------------------- 1 | OUTPUT=SCRIPT 2 | MD_FILES= 00_A_course_info.md 00_books.md 00_motivation.md 01_intro_crud_compile.md 02_expr_stmt_var.md 03_binary_rep.md 04_confidence_fileio.md 05_conditional_indenting.md 06_looping.md 07_more_looping.md 08_arrays.md 09_strings.md 10_strings_libraries.md 11_multid_arrays.md 12_functions.md 13_complexity_sorting_searching.md 14_more_complexity.md 15_structure.md 16_linked_list.md 17_mergesort.md 18_quicksort.md 3 | 4 | $(OUTPUT).md: $(MD_FILES) combine-mds.sh 5 | rm -f $(OUTPUT) $(OUTPUT).md 6 | ./combine-mds.sh > $(OUTPUT) 7 | mv $(OUTPUT) $(OUTPUT).md 8 | 9 | clean: 10 | rm -f $(OUTPUT) $(OUTPUT).md 11 | -------------------------------------------------------------------------------- /eratosthenes_simple.c: -------------------------------------------------------------------------------- 1 | // computing the primes upto a certain limit 2 | #include 3 | 4 | #define LIMITN 100000 // Look for primes under this limit 5 | // #define LIMITN 30 // Look for primes under this limit 6 | 7 | int main() 8 | { 9 | int n,j; 10 | // The goal is to print all prime numbers starting with 2 11 | for(n=2;n 2 | 3 | void average_list(){ 4 | int i; 5 | int sum=0; 6 | int n; 7 | int x; 8 | 9 | printf(" Howmany numbers to sum? "); 10 | scanf("%d",&n); 11 | 12 | printf(" Enter %d numbers to sum ",n ); 13 | 14 | i=0; // count howmany integers already read 15 | while (i < n ){ 16 | scanf("%d",&x); 17 | i=i+1; // increment number of integers read 18 | 19 | sum+=x; // add read integer to sum 20 | } 21 | printf(" Sum is %d\n",sum); 22 | } 23 | 24 | void factorial(){ 25 | int n; 26 | printf(" n = "); 27 | scanf("%d",&n); 28 | 29 | int i=1; 30 | int prod=1; 31 | while (i <= n ) { 32 | prod=prod*n; 33 | } 34 | 35 | printf(" Factorial is %d\n",prod); 36 | } 37 | 38 | void main(){ 39 | factorial(); 40 | // average_list(); 41 | } 42 | -------------------------------------------------------------------------------- /split_sentence.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | void split(const char s[]){ 6 | char word[20]; 7 | int i; 8 | for(i=0;s[i] != '\0';) { 9 | // eat all successive blank tab and newline 10 | while(s[i]==' ' || s[i]=='\t' || s[i]=='\n') 11 | i++; 12 | // put in w all the stuff that forms a word 13 | int w=0; 14 | while(s[i]!=' ' && s[i]!='\t' && s[i]!='\n' && s[i] != '\0') 15 | word[w++]=s[i++]; 16 | word[w]='\0'; 17 | // If a real word is found, then print it 18 | if(word[0] != '\0') 19 | printf("%s\n",word); 20 | 21 | } 22 | } 23 | 24 | 25 | void main(){ 26 | // char s[100]="This is the \n house, \t\t that Jack \n : ?? built."; 27 | char *s = readline("> "); 28 | split(s); 29 | } 30 | -------------------------------------------------------------------------------- /CLASS/09-15.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | 1. 3 | Comparision/Relational operators 4 | BITWIZE operators & | (and or ) ~ (not) << >> (shift operators) 5 | LOGICAL && || ! 6 | Arithmetic/Bitwise operators with effects: 7 | ++ -- += -= *= /= 8 | similarly <<= >>= &= |= ^0 9 | Precedence and Associativity 10 | Comparision operators (the compressed if-then-else) ?: (a ternary operator!) 11 | Comma as an (unusual) operator 12 | 13 | 2. return statement in C, how functions return values; 14 | 15 | 3. SCOPE and LIFETIME of variables 16 | Static vs auomatic lifetime storage class 17 | local vs global visibioity scope 18 | We did many examples to illustrate these 19 | 20 | 21 | Not yet done 22 | 1. Using Files for IO 23 | Using files for IO 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /MiscCProgs-2025/small.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // This is to illustrate something interesting 4 | // internal representations of everything -integers, floating point numbers or 5 | // characters - all of them are actually just binaries bit sequences 6 | int main(){ 7 | char a1='h', a2='e'; 8 | int a3=108, a4=108, a5=111; 9 | char a6='\n'; 10 | float f=3.1415; 11 | 12 | // write() function simply tries to print the first byte in the 13 | // given variable as a character 14 | // 'h' 'e' 15 | write(1,&a1,1); write(1,&a2,1); 16 | 17 | // 'l' 'l' 18 | write(1,&a3,1); write(1,&a4,1); 19 | 20 | // 'o' '\n' 21 | write(1,&a5,1); write(1,&a6,1); 22 | 23 | // ?? 24 | write(1,&f,1); printf("\n"); 25 | } 26 | -------------------------------------------------------------------------------- /discriminant.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // functions are similar to what we are used to in mathematics. 4 | // sin(x) where x is, say, pi/2 would be 1 5 | // Lets write a function to compute the well known discriminant 6 | 7 | // This says what the function with the name discriminant does with 8 | // its parameters 9 | float discriminant(float a, float b, float c){ 10 | // the parameters are assumed to be from a quadratic equation: 11 | // ax^2 + bx + c = 0 12 | return b*b - 4*a*c; 13 | } 14 | 15 | 16 | // In the main() function let's call the above function with 17 | // specific parameter values 18 | void main(){ 19 | float a,b,c,d; 20 | a=1; 21 | b=0; 22 | c=-1; 23 | d = discriminant(a,b,c); // This is a call to the function 24 | printf("%f\n",d); // This is a call to the function 25 | 26 | } 27 | -------------------------------------------------------------------------------- /matrix_ops.c: -------------------------------------------------------------------------------- 1 | #include 2 | /* 3 | // Define maximum columns for a row and the maximum ni of rows 4 | #define MAXC 5 5 | #define MAXR 6 6 | */ 7 | 8 | void swap(int a[][5],int i, int j){ 9 | int t; 10 | for(int k=0;k<5;k++) 11 | t=a[i][k], a[i][k]=a[j][k], a[j][k]=t; 12 | } 13 | 14 | void print_matrix(int a[][5], int nr, int nc){ 15 | for(int i=0;i 2 | // Find the difference in minutes between two given times in the same month 3 | // The two times are given as date and hrs eg. 23 15:32 (to mean 23rd 3 32 pm) 4 | // assume first is before second 5 | // convert each to minutes, then take the difference 6 | int main(){ 7 | // modeling the problem in variables 8 | // The first time 9 | int date,hrs,mins; 10 | // The second time 11 | int date2,hrs2,mins2; 12 | 13 | // read in the first time 14 | scanf("%d %d:%d",&date,&hrs,&mins); 15 | 16 | // read in the first time 17 | scanf("%d %d:%d",&date2,&hrs2,&mins2); 18 | 19 | 20 | // convert each of the above times to minutes 21 | int daymins=date*24*60+hrs*60+mins; 22 | int daymins2=date2*24*60+hrs2*60+mins2; 23 | 24 | // print the difference 25 | printf("%d\n",daymins2-daymins); 26 | } 27 | -------------------------------------------------------------------------------- /varargs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char * concatenate(char * name1, ...) 7 | { 8 | va_list ap; 9 | char * final=malloc(100); 10 | final[0]='\0'; 11 | strcpy(final,name1); 12 | char *p; 13 | va_start(ap, name1); // Use last named para of this function 14 | while( (p=va_arg(ap,char *)) != NULL) { 15 | // ps is the next argument as a (char *) 16 | // We expect NULL argument to indicate end of the args 17 | // alternately we could pass a count as a first arg 18 | 19 | // Add the string p to our local string variable 20 | strcat(final,p); 21 | } 22 | va_end(ap); 23 | return final; 24 | } 25 | 26 | void main(){ 27 | printf("%s\n",concatenate( "This ","is ", "nirvana.", " Always", " to ", "be happy!", NULL)); 28 | } -------------------------------------------------------------------------------- /funcs_scope2.c: -------------------------------------------------------------------------------- 1 | #include 2 | // Aim 1. Show how scope works for locals, parameters and globals 3 | // 4 | 5 | int g = 999 ; // This is a gloabal variable 6 | 7 | void showthis(int g){ // remember this local variable called g 8 | // receives a value when call is made 9 | // This name masks any global name g, inside this function 10 | printf("inside showthis %d\n",g); 11 | g = 666; 12 | } 13 | 14 | void printg(){ 15 | printf("inside printg %d\n",g); 16 | } 17 | 18 | void main(){ 19 | int g = 111; // This is a local variable called g 20 | // It is initialized a value in this function 21 | // This name masks any global name g, inside this func 22 | showthis(555); 23 | showthis(g); 24 | showthis(g); 25 | printg(); 26 | { 27 | int g=0; 28 | printf("main in block %d\n",g); 29 | } 30 | printf("main after block %d\n",g); 31 | } 32 | -------------------------------------------------------------------------------- /SCRIPT/12_functions.md: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | ## What and Why 4 | 5 | ## Concepts 6 | * Declaration syntax 7 | * Functions with no parametrs 8 | * The notion of call and return 9 | * The concept of returning values 10 | * EXAMPLE funcs.c 11 | * Function arguments 12 | * EXAMPLE funcs\_params.c 13 | * Arguments are values 14 | * swap revisited 15 | * swap revisited with pointers 16 | * Revisit scope 17 | ## Declaration vs Definition 18 | * Prototype declarations 19 | * Example: funcs\_scope.c 20 | * Examples with functions and pointers: 21 | * finding the minum in an array 22 | * magically array increment of all elements works very well 23 | * we can push any of our earlier examples into functions 24 | ## Recursion 25 | * Base case 26 | * recusion step 27 | * relationship to recursive definition 28 | * Recursion tree 29 | 30 | -------------------------------------------------------------------------------- /SCRIPT/06_looping.md: -------------------------------------------------------------------------------- 1 | # EXPRESSING REPEATED EXECUTION 2 | 3 | ## FOR 4 | * Looping through a sequence of values 5 | * FOR 6 | * findmax\_list\_f.c 7 | 8 | ## WHILE and its variations 9 | * LOOPING through a condition 10 | * WHILE see findmax\_list\_w.c , integrate.c 11 | * DO WHILE see findmax\_list\_d.c 12 | * What problems can you solve 13 | * PRACTICE fillin\_while.c fillin\_findmax\_loop.c 14 | * max of 10 items? 15 | * sum of 10 items ? 16 | * sum of an unfixed number of items ? 17 | * the 3np1 problem ? 18 | * find if a given number is prime ? 19 | 20 | ## Understanding the FOR better 21 | 22 | ## Exercise 23 | * Student should be able to find the avarage of an arbitrary 24 | number of integers input by the user. 25 | * See list\_avg\_f.c list\_avg\_w.c list\_avg\_d.c 26 | * Take a look at simple\_event\_count.c 27 | 28 | 29 | -------------------------------------------------------------------------------- /apnf.c: -------------------------------------------------------------------------------- 1 | #include 2 | // This is about arrays pointers and functions 3 | void f1( int x ){ 4 | x = 55; 5 | } 6 | 7 | void f2( int *p ){ 8 | *p = 55; 9 | } 10 | 11 | void f3( int *p ){ 12 | int i; 13 | for(i=0;i<10;i++) 14 | *(p+i)=i+55; // alernately p[i]=i+55 ; 15 | } 16 | 17 | void f4( int *p , int n){ 18 | int i; 19 | for(i=0;i 2 | 3 | // An introductory idea of recursion. This is a well known function 4 | // Mathematically: 5 | // factorial(n) :: 1 if n equals 0 6 | // :: n * factorial(n-1) if n > 0 7 | // We dont define it for negative numbers 8 | int fact(int n){ 9 | if (n == 0 ) 10 | // we call this the base case or *non*-recursive case 11 | return 1; 12 | else 13 | // we call this the recursive case 14 | return n*fact(n-1); 15 | // Draw a call tree to see what it looks like, then 16 | // draw a call stack. Also look at what gdb says 17 | } 18 | int test(int n){ 19 | // This is a simple function just to illustrate what 20 | // the frame looks like for a normal function call 21 | int x=10; 22 | n = x * n; 23 | return n; 24 | } 25 | int main(){ 26 | int n=0; 27 | int z=3; 28 | int v; 29 | scanf("%d",&n); 30 | 31 | v = test(n); // replace with fact(n) 32 | printf(" main got %d\n",v); 33 | } 34 | -------------------------------------------------------------------------------- /conversions.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main(){ 4 | // See https://en.cppreference.com/w/c/language/ascii 5 | // Print out as integer values in different ways 6 | printf("%d %d %d %d %d %d\n", 65, 0x41, 7 | 0101, 0b01000001, 8 | (int) 659.9999e-1, (int ) 'A'); 9 | // Print out as char values in different ways 10 | printf("%c %c %c %c %c %c\n", (char) 65, (char) 0x41, 11 | (char) 0101, (char) 0b01000001, 12 | (char) 659.999e-1, 'A'); 13 | // Print out as float values in different ways 14 | printf("%f %f %f %f %f %f\n", (float) 65, (float) 0x41, 15 | (float) 0101, (float) 0b01000001, 16 | 659.9999e-1, (float) 'A'); 17 | 18 | 19 | 20 | 21 | 22 | 23 | int i; 24 | short int si; 25 | long int li; 26 | float f; 27 | double d; 28 | long double ld; 29 | } 30 | -------------------------------------------------------------------------------- /MiscCProgs-2025/integrate1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // We wish to show how integration can be done over an interval for some 4 | // function that we can evaluate. 5 | 6 | // gf is the function we wish to integrate 7 | float gf(float x){ 8 | return exp(-x*x); 9 | } 10 | 11 | 12 | // Main idea: integration is by adding little rectangles 13 | // starting from a upto b 14 | 15 | int main(){ 16 | // interval for integration 17 | float a,b; 18 | scanf("%f%f",&a,&b); 19 | 20 | 21 | // number of rectangles 22 | int steps=1000; 23 | 24 | // rectangle width 25 | float h=(b-a)/steps; 26 | 27 | // this is the integral value 28 | float sum=0; 29 | 30 | // x is the bottom left of the rectangle 31 | // so gf(x) will be the height of the rectangle 32 | float x=a; 33 | int i=0; 34 | 35 | while(i 2 | int main(){ 3 | int i1, i2; 4 | char c; 5 | /* operator in between: 6 | * printf("Give me a simple arithmetic operation on integers " 7 | * "like 4 - 3:\n"); 8 | // Doesnt work: 9 | // scanf("%d %d ",&i1,&i2); 10 | // c = getchar(); 11 | // Works: 12 | // scanf("%d ",&i1); 13 | // c = getchar(); 14 | // scanf("%d",&i2); 15 | // Works 16 | // scanf("%d %c %d",&i1,&c,&i2); 17 | */ 18 | /* Operator at taken separately after operands: 19 | */ 20 | printf("Give me two integers :"); 21 | scanf("%d %d",&i1,&i2); 22 | printf("Give me an operator: "); 23 | // Doesnt work: 24 | scanf("%c", &c); 25 | // Works: 26 | // scanf(" %c", &c); 27 | 28 | switch(c){ 29 | case '+': printf("%d\n",i1+i2); 30 | break; 31 | case '-': printf("%d\n",i1-i2); 32 | break; 33 | case '*': printf("%d\n",i1*i2); 34 | break; 35 | case '/': printf("%d\n",i1/i2); 36 | break; 37 | default: printf("operator %c not implemented\n", c); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /matmul.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int matprint(float a[][10],int n){ 4 | for (int i = 0;i < n; i++) { 5 | printf("\n"); 6 | for (int j = 0;j < n; j++) { 7 | printf("%f ", a[i][j]); 8 | } 9 | } 10 | } 11 | int matread(float a[][10]){ 12 | int i,j,n; 13 | printf("Enter the order of the Matrix : "); 14 | scanf("%d", &n); 15 | printf("Enter the elements of the %dX%d Matrix row-wise: \n", n, n); 16 | for (i = 0;i < n; i++) { 17 | for (j = 0;j < n; j++) { 18 | scanf("%f", &a[i][j]); 19 | } 20 | } 21 | return n; 22 | } 23 | 24 | void matmul(float a[][10], float b[][10], float c[][10], int n){ 25 | for (int i = 0;i < n; i++) { 26 | for (int j = 0;j < n; j++) { 27 | c[i][j]=0; 28 | for (int k=0; k< n ; k++ ) 29 | c[i][j]+=a[i][k]*b[k][j]; 30 | } 31 | } 32 | } 33 | 34 | int main(){ 35 | float a[10][10],b[10][10],c[10][10]; 36 | int n; 37 | n=matread(a); 38 | n=matread(b); 39 | matmul(a,b,c,n); 40 | matprint(c,n); 41 | } 42 | -------------------------------------------------------------------------------- /CLASS/09-29.txt: -------------------------------------------------------------------------------- 1 | DONE: 2 | 1. Some common errors from in-class Exercise 1 and Exercise 2 on arrays 3 | 2. Revisit strings 4 | 3. We mentioned that there are a bunch of string library funcitons. 5 | We looked at 'man string' on Linux 6 | (can also look for this on an internet search) 7 | We saw that it would take some effort if we wanted to implement those 8 | functions themselves. 9 | Useful functions: strcpy, strcat, strchr, strcmp, strlen 10 | Student is urged to explore how these can be used. 11 | 12 | 4. FILE IO: We saw that scanf and printf were just simplified ways of using 13 | fscanf with 'stdin' or 'stdout' as a first argument. 14 | 'stdin' and 'stdout' are pre-defined "FILE *" (FILE pointers). 15 | We can create our own file pointers that refer to a file on the disk using 16 | the fopen() function. We call this opening a file. 17 | Refer 'man fopen'. 18 | See fileio.c on our course github. 19 | We used the EOF as well. 20 | 21 | 5. Class assignment 2 22 | -------------------------------------------------------------------------------- /MiscCProgs-2025/index.txt: -------------------------------------------------------------------------------- 1 | index.txt This file 2 | ------------------------------------- 3 | 4 | float.c (Early) highlights crazy stuff about the floating point arithmetic 5 | small.c (Early) writes out integers as characters 6 | studentschocolates.c (Modeling) word problem of chocolates and students 7 | vadasdosas.c(Modleing) word problems dosas and vadas and simultaneous equations 8 | 9 | mmc.c (C is fast) matrix multiply in C with timing 10 | mmpy.py (C is fast) matrix multiply in python with timing 11 | 12 | GtGrLi.c (Arrays) simulates input driven steps of the goat grass lion problem; also solves it 13 | 14 | integrate.c (for loop) shows integration by adding tiny squares 15 | pouringwatersim.c ( While, if) simulates measuring out water 16 | towersim.c ( While, if) simulates input driven towers of hanoi 17 | 18 | forces.c(Arrays, structs) simulates n-boady problem 19 | points(Data for forces.c) points of the initial n=10 bodies in the n-body simulation above 20 | 15puzzle.c(Arrays) simulates input driven steps of the 15-puzzle 21 | -------------------------------------------------------------------------------- /MiscCProgs-2025/mmpy.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | size = 10 5 | rows_a =rows_b=cols_a=cols_b=size 6 | result_matrix = [[0 for _ in range(cols_b)] for _ in range(rows_a)] 7 | 8 | def multiply_matrices_pure_python(matrix_a, matrix_b): 9 | """Multiplies two matrices using pure Python lists.""" 10 | 11 | for i in range(rows_a): 12 | for j in range(cols_b): 13 | for k in range(cols_a): 14 | result_matrix[i][j] += matrix_a[i][k] * matrix_b[k][j] 15 | return result_matrix 16 | 17 | # Generate two sizexsize matrices with random values 18 | matrix1 = [[random.randint(1, 100) for _ in range(size)] for _ in range(size)] 19 | matrix2 = [[random.randint(1, 100) for _ in range(size)] for _ in range(size)] 20 | 21 | # Time the core computation 22 | start_time = time.perf_counter() 23 | result_pure_python = multiply_matrices_pure_python(matrix1, matrix2) 24 | end_time = time.perf_counter() 25 | 26 | print(f"Time taken for pure Python matrix multiplication: {end_time - start_time:.6f} seconds") 27 | -------------------------------------------------------------------------------- /CLASS/material_outside_KR: -------------------------------------------------------------------------------- 1 | Some material taught may not be available in the Kernighan and Ritchie 2 | text book on the C Programming language. 3 | 4 | I believe that the material as explained and code made 5 | available on github suffices. But some students may wish to read from a 6 | text book. So here is some reference: 7 | 8 | All that material is available in : 9 | Robert Sedwick's algorithms book: A free downloadable version is available here: 10 | https://theswissbay.ch/pdf/Gentoomen%20Library/Algorithms/Algorithms%20in%20C.pdf 11 | 12 | NOTE: THE SAME BOOK is available as 4th edition which is perfectly good, except it uses C++. 13 | 14 | Parts that are useful: 15 | Ch 6 : Analaysis of algorithms 16 | Ch 8 : Basic Sorting: insertion sort, selection sort and bubble sort - there are 17 | other sorts too, but you can neglect 18 | Ch 12 : Mergesort: I would restrict to pages 163 - 166 which focusss on arrays 19 | Ch 14 : page 198 has binary search. You may want to read the part before pp 198 it has 20 | some relevant stuff too. 21 | -------------------------------------------------------------------------------- /MiscCProgs-2025/studentschocolates.c: -------------------------------------------------------------------------------- 1 | // I have N chocolates and wish to divide it as equally as possible among S students. 2 | // How must I distribute the chocolates 3 | // Idea: Quite simple every body gets at least N div S chocolates. 4 | // K=N % S students get one more each (N div S)+1 chocolates 5 | // and S - K Students get N div S chocolates 6 | // 7 | #include 8 | int main(){ 9 | // modeling the chocolates, students 10 | int nChokos,nStudents; 11 | // nMore is the number of studnts who get one more chocolate 12 | int nMore; 13 | printf("Please enter the number of chocolates available and the number of students: "); 14 | scanf("%d %d",&nChokos, &nStudents); 15 | // number of students who get more than the others 16 | nMore=nChokos%nStudents; 17 | 18 | if (nMore == 0) 19 | printf("All %d students get %d chokos\n",nStudents,nChokos/nStudents); 20 | else { 21 | printf("%d students get %d chokos\n",nMore, nChokos/nStudents+1); 22 | printf("%d students get %d chokos, and\n",nStudents-nMore, nChokos/nStudents); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /simple_event_count.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // 5 | // A coin is flipped twice in an experiment 6 | // (obsx,obsy) are the observed values from the first and second flip. 7 | // For convenience an observation=0 means tails and an observation=1 is heads 8 | // so possible outcomes are (0,0), (1,0), (0,1) and (1,1) 9 | // We want to count frequency of both being tails i.e., occurence of (0,0) 10 | // on repeating the experiment 100 times 11 | // Ideally the observed frequency should be close to 1/4. 12 | #define NEXP 100 // We can change this 13 | void main(){ 14 | int i; 15 | int obsx,obsy,event_00_count; 16 | float observed_freq; 17 | event_00_count=0; 18 | // srandom(0); // neglect this initially 19 | for (i=0; i < NEXP ; i++) { 20 | // (obsx,obsy) are the results of the two flips 21 | obsx=random()%2; 22 | obsy=random()%2; 23 | if (obsx==0 && obsy==0) 24 | event_00_count++; 25 | } 26 | observed_freq=(1.0*event_00_count)/NEXP; 27 | printf("00 occurred with frequency: %f\n",observed_freq); 28 | } 29 | -------------------------------------------------------------------------------- /slides/Flowcharts/F02-factorial.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /MiscCProgs-2025/mmc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define SIZE 10 5 | 6 | int main() { 7 | int matA[SIZE][SIZE], matB[SIZE][SIZE], matC[SIZE][SIZE]; 8 | int i, j, k; 9 | clock_t start, end; 10 | double cpu_time_used; 11 | 12 | // Seed the random number generator 13 | srand(time(NULL)); 14 | 15 | // Initialize matrices with random values 16 | for (i = 0; i < SIZE; i++) { 17 | for (j = 0; j < SIZE; j++) { 18 | matA[i][j] = (rand() % 100) + 1; 19 | matB[i][j] = (rand() % 100) + 1; 20 | } 21 | } 22 | 23 | // Time the matrix multiplication 24 | start = clock(); 25 | for (i = 0; i < SIZE; i++) { 26 | for (j = 0; j < SIZE; j++) { 27 | matC[i][j] = 0; 28 | for (k = 0; k < SIZE; k++) { 29 | matC[i][j] += matA[i][k] * matB[k][j]; 30 | } 31 | } 32 | } 33 | end = clock(); 34 | 35 | cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; 36 | 37 | printf("Matrix multiplication completed in %f seconds\n", cpu_time_used); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /CLASS/09-01.txt: -------------------------------------------------------------------------------- 1 | 1. Notion of function invocation. How the control flows. Concept of variables 2 | (including parameters being local to a function). We took a swap example. 3 | 4 | 5 | 2. Notion of "Everything is a (binary) number" 6 | - Base-2 notion. Byte. 2's complement concept. 7 | - Character as integer 8 | - ASCII 9 | 10 | 3. Operators in C 11 | Arithmetic: 12 | numbers -> numbers 13 | + - / * (dependnce on types) 14 | Conditional: 15 | numbers -> True/False 16 | == >= <= 17 | Logical: 18 | True/False -> True/False 19 | && || ! 20 | 21 | 4. *TBD* Formally define the types and variable definitions in C 22 | 5. Simple if and while using the conditionals above 23 | - notion of codes block in { } 24 | 6. Binary representation 25 | Simple notions of binary arithmetic 26 | * TBD * Bitwise operations and or and not 27 | * TBD * Other interesting operations: shift 28 | 7. Fill this form: http://shorturl.at/bgmws 29 | 30 | EXERCISE : fillin_simple.c print_next_char.c 31 | EXERCISE : Look at main.c, stats.c hello_world.[ch] 32 | EXERCISE : do the 09-05-exercises and prepare for a quiz. 33 | -------------------------------------------------------------------------------- /eratosthenes.c: -------------------------------------------------------------------------------- 1 | // computing the primes upto a certain limit 2 | #include 3 | #define METHOD 1 4 | #define LIMITN 100000 // Look for primes under this limit 5 | // #define LIMITN 30 // Look for primes under this limit 6 | #define ASIZE 20000 // This will hold all the primes 7 | int main() 8 | { 9 | 10 | struct { 11 | long int rem; 12 | long int prime; 13 | } factor[ASIZE]; 14 | int idx=0, n, isprime, j; 15 | printf("Will list primes starting from 2 upto %d\n",LIMITN); 16 | for(n=2;n 15 | 16 | int main(){ 17 | float v1, d1, c1, v2, d2, c2; // we read in these, BTW, why float? 18 | scanf("%f %f %f %f %f %f",&v1,&d1,&c1,&v2,&d2,&c2); 19 | 20 | // Now it is about solving for v and d 21 | // first row multiplied by v2/v1 and subtracting 22 | // it from second row will eliminate the vada cost from second row 23 | d2-=d1*v2/v1; 24 | c2-=c1*v2/v1; 25 | // now we can compute cost of dosa: 26 | float v,d; 27 | d=c2/d2; 28 | // we now use the first equation to compute the cost of the vada: 29 | v=(c1-d1*d)/v1; 30 | 31 | printf("%f %f\n",v,d); 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /lcm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // To find LCM we can use a common divisor. 4 | // We just find the smallest 5 | int find_smallest_divisor(int a , int b){ 6 | for (int i=2;i<= b; i++) { 7 | if ( a%i == 0 && b %i == 0 ) 8 | return i; 9 | } 10 | return 1 ; 11 | } 12 | int lcm (int n1, int n2 ) { 13 | // make sure the numbers are positive 14 | // And that neither is zero 15 | // LCM is product if there is no common factor, ie gcd=1 16 | // The shortcut method using gcd: 17 | // find the gcd 18 | // LCM is product / gcd 19 | // In the long method 20 | // 1. we find a smallest common factor 21 | // let f be the common factor found 22 | // 2. if f is 1 then 23 | // lcm is the product 24 | // 3. else // common factor is > 1 25 | // lcm(n1,n2)=f * lcm (n1',n2') where ni'=ni/f 26 | // We program the long method here: 27 | // 28 | // 1. 29 | int f = find_smallest_divisor(n1,n2); 30 | // 2. 31 | if ( f==1 ) return n1*n2; 32 | // 3. 33 | else { 34 | n1=n1/f ; n2 = n2/f ; 35 | return f * lcm(n1,n2); 36 | } 37 | 38 | } 39 | 40 | int main(){ 41 | int n1,n2; 42 | while(1) { 43 | printf("Give me two numbers"); 44 | scanf("%d %d", &n1, &n2); 45 | printf("lcm is %d\n",lcm(n1,n2)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /find_max.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Here we read three numbers and find their maximim 4 | int read_and_find_max(){ 5 | int a, b, c; 6 | printf("Give me three numbers: "); 7 | scanf("%d",&a); 8 | scanf("%d",&b); 9 | scanf("%d",&c); 10 | printf("Max is : "); 11 | if ( a > b ) { 12 | if (a > c ) 13 | printf("%d",a); 14 | else 15 | printf("%d",c); 16 | } else { 17 | if (b > c ) 18 | printf("%d",b); 19 | else 20 | printf("%d",c); 21 | } 22 | printf("\n"); 23 | } 24 | 25 | // Here is a function to find the max of 2 numbers 26 | // run it to see what happens 27 | void find_max_of_2(int a, int b){ 28 | if ( a > b ) 29 | printf("Maximum is %d\n",a); 30 | if ( b > a ) { 31 | printf("a is %d, b is %d\n",a,b); 32 | printf("Maximum is %d\n",b); 33 | } 34 | } 35 | 36 | 37 | // Here is a function for the maximum of 3 numbers 38 | // Run it see what happens 39 | void find_max_of_3(int a, int b, int c){ 40 | if ( a > b && a > c) 41 | printf("Maximum is %d\n",a); 42 | if ( b >a && b > c) 43 | printf("Maximum is %d\n",b); 44 | if ( c >a && c > b) 45 | printf("Maximum is %d\n",c); 46 | } 47 | 48 | void main(){ 49 | // try one of these three 50 | // find_max_of_2(10,20); 51 | // find_max_of_3(10,30,20); // for fun also try 100,100,100 52 | // read_and_find_max(); 53 | } 54 | -------------------------------------------------------------------------------- /related_arrays.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX_STUDENTS 20 4 | #define NAME_LENGTH 15 5 | void show_a_student_info(char name[MAX_STUDENTS][NAME_LENGTH], float score[MAX_STUDENTS], int size, char q[]){ 6 | int idx=0; 7 | for( idx=0 ; idx < size ; idx++ ){ 8 | if (strcmp(name[idx],q) == 0 ){ 9 | printf("%s %f\n",q,score[idx]); 10 | return; 11 | } 12 | } 13 | printf("%s not found!\n",q); 14 | } 15 | 16 | int read_all_students_info(char name[MAX_STUDENTS][NAME_LENGTH], 17 | float score[MAX_STUDENTS]){ 18 | // number of students 19 | int n; 20 | int idx; 21 | printf("Howmany students ? "); 22 | scanf("%d",&n); 23 | printf("Now input student name and score for each :\n"); 24 | for (idx=0; idx < n ; idx++ ){ 25 | printf("%2d:",idx+1); 26 | scanf("%s %f",name[idx],&score[idx]); 27 | } 28 | return n; 29 | } 30 | 31 | void main() { 32 | char name[MAX_STUDENTS][NAME_LENGTH]; 33 | float score[MAX_STUDENTS]; 34 | int nstudents=0; 35 | char q_name[NAME_LENGTH]; 36 | nstudents = read_all_students_info(name,score); 37 | 38 | printf("Now lets look for a student in this list .. \n"); 39 | while (1) { 40 | printf("Give me a student's name :"); 41 | scanf("%s", q_name); 42 | show_a_student_info(name,score,nstudents,q_name); 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /slides/Flowcharts/F03-sumofnumbers.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // A Method to compute the GCD of two given numbers 4 | // 5 | // This is written this C function called gcd() 6 | // It takes two parameters 7 | // n1, n2 which are the two numbers 8 | // It returns a value which is the gcd of the two numbers 9 | int gcd(int n1, int n2){ 10 | // How it works: 11 | // 1. Lets assume n1 >= n2 > 0 (Otherwise our description doesnt work) 12 | // 2. GCD of 1 and another number is 1 13 | // 3. If n2 | n1 then n2 is the GCD 14 | // 4. Else the GCD of two numbers is the same as 15 | // the gcd of n2 and the remainder of n1/n2 16 | // i.e. GCD of n1 and n2 is same as gcd n2 and n1%n2 17 | // 18 | // ----- Now the same in the C Language ----- 19 | // 1. Here we are checking for the violation of the assumption 20 | if ( n1 < n2 || n2 <= 0 ) { 21 | printf(" The given values are not as assumed; " 22 | "error! Just cant compute exiting\n"); 23 | exit(1); 24 | } 25 | // 2. 26 | if (n2 == 1) 27 | return 1; 28 | // 3. 29 | if (n1%n2 == 0 ) 30 | return n2; 31 | // 4. 32 | else { 33 | int n3=n1%n2; 34 | return gcd(n2,n3); 35 | } 36 | } 37 | 38 | int main(){ 39 | int n1,n2; 40 | 41 | do { 42 | printf("Give me two numbers: "); 43 | scanf("%d %d",&n1,&n2); 44 | printf("GDC is %d\n",gcd(n1,n2)); 45 | } while (n1 > 0 && n2 > 0 ); 46 | } 47 | -------------------------------------------------------------------------------- /shortcircuit.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | void main(){ 6 | 7 | // Short circuit evaluation 8 | // Example 1 9 | printf("I will keep printing 10..1 until I get an 'x'\n"); 10 | int a=0; 11 | while( a || (a = 10)){ // a=10 only happens if a == 0 12 | printf("%d",a--); 13 | int opt = getchar(); 14 | if ( opt == 'x') // some decent loop termination 15 | break; 16 | } 17 | 18 | // Example 2 19 | printf("Give me an integer and I will print one of 10..40 for 1..4\n"); 20 | printf("... until you give me something outside this range\n>"); 21 | int b[5]={0,10,20,30,40}; 22 | int i; 23 | while(1){ 24 | scanf("%d",&i); 25 | if ( b[i]==0 || i>4 || i< 0 ) // This order is bad, why? 26 | break; 27 | printf("%d\n>",b[i]); 28 | } 29 | 30 | // Example 3 31 | // the idea is that start at position i 32 | // and as long as p is not NULL and the item pointed to 33 | // by p is non-zero keep repeating the loop 34 | 35 | printf("read an index and if it is positive print b[i],b[i+1]...\n"); 36 | printf("until your hit a zero...\n"); 37 | printf(" The pointer us NULL if it is not a valid location.so exit..\n"); 38 | int *p = NULL; 39 | scanf("%d", &i); 40 | if ( i < 0 || i >4 ) 41 | p=NULL; 42 | else 43 | p=&b[i]; 44 | while ( *p != 0 && p !=NULL ) { // This order is bad, why? 45 | i++; 46 | if ( i > 4 ) 47 | p=NULL; 48 | else 49 | p=&b[i]; 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /linked_list_intro.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Here is an interesting structure 5 | struct node { 6 | int val; 7 | struct node * next; 8 | }; 9 | // The above has two members one of which is a pointer type. 10 | 11 | // Below is a simple funciton to get a new "struct node" node 12 | struct node * new_node(){ 13 | return (struct node *) malloc(sizeof(struct node)); 14 | } 15 | 16 | // Here is how one struct node node can have its "next" field point 17 | // to another node. 18 | void join_next(struct node *node1, struct node *node2){ 19 | node1->next=node2; 20 | } 21 | 22 | // For fun here is a function that simply adds 10 new nodes one 23 | // after the other to the end of a given node called node1. 24 | void join_n_new(struct node *node1, int n){ 25 | struct node * p=node1; 26 | for (int i; i next=new_node(); 28 | p=p->next; 29 | } 30 | // what is p at the end? 31 | } 32 | 33 | 34 | // Can you write a function to simply go throu all nodes in the 35 | // linked list of nodes and set the val field to some number, say 100. 36 | void set_list_values( struct node * node){ 37 | } 38 | 39 | // Can you write a function to read from the user values and add them 40 | // as new nodes into an existing list who's only node in the beginning 41 | // is given? 42 | void read_list_values( struct node * node){ 43 | } 44 | 45 | void main() { 46 | // figure out what you want to test here 47 | } 48 | -------------------------------------------------------------------------------- /slides/Flowcharts/F00-quad1.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /simple_malloc.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Using malloc to allocate an array of integers 5 | void main(){ 6 | void allocate_and_fill_arrays(int *q[], int n); 7 | void free_up_arrays(int *q[], int n); 8 | 9 | int * p; 10 | p = malloc(50*sizeof(int)); 11 | for(int i=0;i<50;i++) 12 | p[i]=i; 13 | 14 | // IMPORTANT: when the program finishes all the memory 15 | // allocated to the program including dynamic memory 16 | // is freed up. 17 | // 18 | // However as a discipline, when you no longer need 19 | // the memory free it up: 20 | 21 | free(p); 22 | 23 | // note that at this point we cannot use whatever p points to! 24 | // printf("%d \n",p[0]); may work, but it is a problem! 25 | 26 | int * q[5]; // array of pointers to integers 27 | allocate_and_fill_arrays(q,3); 28 | free_up_arrays(q,3); 29 | } 30 | 31 | // Using malloc to allocate multiple such arrays and put them into 32 | // into an array of pointers! 33 | void allocate_and_fill_arrays(int *q[],int n){ 34 | for(int i=0;i 2 | 3 | // 1. reading a graph 4 | void read_graph(int a[][5], int n){ 5 | FILE * fp=fopen("graph_info","r"); 6 | for(int i=0; i 2 | #include 3 | 4 | 5 | // before doing the compiling to create a.out 6 | // try compiling with the -E option to see what the preprocessor does 7 | 8 | 9 | // MACRO simply substitute the left item by the right item, literally. 10 | // MACROs come in two varieties - wihout a parameter and with parameters: 11 | // 1st kind: 12 | // NUM below is not a variable 13 | // is not a constant variable (unline const) 14 | // It is just a constant! 15 | #define NUM 10 16 | // SIMILARLY THIS 17 | #define INC ++ 18 | // AND THIS 19 | #define BYE printf("bye bye\n") 20 | 21 | // 2nd kind: 22 | // MAX below is not a function!! 23 | // It is just a macro 24 | #define MAX(X,Y) X > Y ? X : Y 25 | 26 | 27 | // Here is an unusual trick that helps when writing some macros 28 | // The hash sign in front of a variable converts it to a string when used in the macro body 29 | #define check(expr) (expr)? 1 : (printf("Error with %s, aborting!\n",#expr),exit(1)) 30 | 31 | void main(){ 32 | int z = NUM; 33 | z++; 34 | printf("%d\n",z); 35 | 36 | int * p; // can I assing p to point to NUM? 37 | // ....NO! because it is just a constant 38 | 39 | // This is a common use: 40 | char a[NUM] = "Hello"; 41 | int i=10,j=20; 42 | i INC ; 43 | BYE; 44 | 45 | printf("MAX(i,j) is %d\n",MAX(i,j)); 46 | 47 | printf("Give me an integer, +ve is all good, but otherwise it will abort :"); 48 | scanf("%d",&i); 49 | check(i>0); 50 | printf("All good\n"); 51 | } 52 | -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_4.txt: -------------------------------------------------------------------------------- 1 | Define a structure with the following fields to hold information about 2 | a student: 3 | - name (use an array of 20 characters) 4 | - scholarship : is an integer indicating one of two values 5 | 0 - not a scholarship holder 6 | 1 - is an active scholarship holder 7 | - amount : if the student holds a scholarship, then the amount. 8 | if the student does not hold a scholarship, it is neglected 9 | - score : an integer indicating total marks 10 | 11 | 12 | Functions on the student: 13 | - read_student(struct student * s) 14 | will read student info for a student form the user 15 | - print_student(struct student s) 16 | will print student info for a student 17 | - print_scholarhsip_holders(struct student s[], int n) 18 | will look at s[0]..s[n-1] and print only 19 | those student's names who are scholarship holders 20 | - compute_total_amount(struct student s[], int n) 21 | will print the total scholarship amount spent on 22 | students who are receiving scholarship 23 | - set_scholarship(struct student s[], int i, int amount) 24 | sets s[i] to be an active scholaship holder 25 | and sets that person's scholarship amount to the given value 26 | - find_best_non_scholarship(struct student s[], int n) 27 | Of all the non-scholarship holders, find the one 28 | with maximum score. 29 | 30 | 31 | Now write a main() function to read student info into an array 32 | of structures, then print a menu for the operations above. 33 | Ask user for input and perform the operation. 34 | -------------------------------------------------------------------------------- /CLASS/09-08.txt: -------------------------------------------------------------------------------- 1 | Plan: 2 | 1. Repeat the main concepts in programming: 3 | Notion of stored variables 4 | Notion of algorithm with instructions 5 | C Programs comprise functions for instructions, variables as storage 6 | Define (declare) before use 7 | Notion of expression, assignment, statement and block; 8 | In particular assignment 9 | Recall the interesting m = n = 5 ; 10 | In C function calls only values are passed, not variables! 11 | Everything is binary 12 | Operators: Arithmetic, comparision and logical (we didnt do examples of logical) 13 | Arithmetic operation and (automatic) type conversions 14 | Recalle 13/2 is different from 13/2.0 15 | printf(), scanf() and elementery notion of the format string 16 | if (conditions) { } else { } 17 | while { } 18 | Always remember the (edit, compile, execute) loop 19 | 2. Towards end of class some unanswered questions include what is the & in scanf 20 | 3. A bit about seeing the binary in the files. od -cx and gdb 21 | Use gdb also to step through the execuiton 22 | 4. 10 Exercises in 09-05-exercises.txt 23 | The aim today is to simply do all those exercises. 24 | Along the way we re-emphasises the notions studied so far. 25 | 5. Homework: 26 | (1) Read for the quiz on 12-09 (Monday) 27 | (2) Read up about operator precedence (only for those operators taught in class). You can read from the Kernighan and Ritchie book (2nd Ed. pp 52-53) or from online sites, like: https://en.cppreference.com/w/c/language/operator_precedence 28 | -------------------------------------------------------------------------------- /SCRIPT/08_arrays.md: -------------------------------------------------------------------------------- 1 | # Arrays 2 | ## Objective 3 | * Arrays definition 4 | * Arrays usage via indexing 5 | * Arrays end 6 | * Array usage without loops 7 | * Array usage with loops 8 | * Student should be able to write a small program to 9 | read and and write into an array 10 | find an element in the array 11 | 12 | ## Basic usage 13 | * Notion of indexing 14 | 15 | ## Usage in loops 16 | * arrays and for and while loops - BE CAREFUL ABOUT THE END OF THE ARRAY 17 | * arrays and reading from files 18 | * writing arrays to files 19 | * finding max in an array 20 | * finding average of items in an array using for, while, do 21 | 22 | ## Exercise 23 | * reverse a list of numbers and print in reversed order 24 | * compute the standard deviation of a given se of numbers 25 | * Using multiple arrays 26 | * student\_id[] 27 | * marks\_sub1[] 28 | * marks\_sub2[] 29 | * marks\_sub3[] 30 | * Find the student(s) with maximum marks in sub1. 31 | * Find the student(s) with maximum marks in all three subs taken together. 32 | * Using multiple arrays 33 | * list1[] has n integers 34 | * list2[] has m integers 35 | * make a new list list3[] with items from both list1[] and list2[] 36 | * what if you wanted to shuffle the elements of list1[] and list2 into list3 37 | * Assume list1 and list2 are sorted, can you merge them together into list3? 38 | 39 | ## End class check 40 | * Student should be able to write a small program to 41 | * read and and write into an array 42 | * find an element in the array 43 | * EXERCISE list\_avg\_array.c 44 | -------------------------------------------------------------------------------- /CLASS/notables.txt: -------------------------------------------------------------------------------- 1 | 1. If the function has a return type defined but nothing is returned 2 | using a return statement in the function, 3 | then the value returned is not defined. Eg 4 | int f(int x){ 5 | if ( x > 0 ) 6 | return 1; 7 | } 8 | Now, what is returned if the function is called as f(-10)? 9 | The C standard document says the return value is not definied. 10 | So we cant say what the expression printf(" % d ",f(-10)) will print. 11 | If you are interested the latest free version of the document is here: 12 | https://web.archive.org/web/20181230041359if_/http://www.open-std.org/jtc1/sc22/wg14/www/abq/c17_updated_proposed_fdis.pdf see section 6.9.1, item number 12. 13 | FINAL SAY: Never assume that no return statement means th same as "return 0;" 14 | 15 | 2. Variable size arrays: 16 | More recent versions of C allow array size to be variable. The simplest 17 | two ways to use it are: 18 | (a) The is a *local variable* declared in the body of a function, maybe in a block. 19 | The size will be determined by evaluating the size at the time the 20 | array variable declaration is encountered. 21 | { 22 | int size; 23 | scanf("%d ", &size); 24 | int a[size]; 25 | } 26 | (b) The array is in the *parameter of a function*, and the size is also a parameter. 27 | int f( int n, int a[n]){ 28 | ... 29 | } 30 | 31 | 3. Nested function definitions: 32 | The C standard does not support nested funciton definitions. 33 | However, certain compilers (such as gcc) allow it as an extended feature. 34 | The advice is to be aware, but *do not* use it. 35 | -------------------------------------------------------------------------------- /slides/Flowcharts/F04-dotproduct.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /union_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define SIZE 4 3 | 4 | // a union is very much like a structure in appearance 5 | union id { 6 | int id_i; 7 | char id_s[20]; 8 | }; 9 | 10 | // Here is a simple declaraction 11 | union id g; 12 | // Here note that the space allocated the maximum sized field 13 | // so here it is max(4,20) ie 20 bytes 14 | 15 | // Here is a function to print and see sizes of the variable g and its fields 16 | void printsizes(){ 17 | printf("sizeof(g)=%ld, sizeof(g.id_i)=%ld, sizeof(g.id_s)=%ld\n\n", 18 | sizeof(g), sizeof(g.id_i), sizeof(g.id_s)); 19 | } 20 | 21 | // This function reads a 'union id' into a variable whos pointer is given 22 | // The return value is the type of the id read 23 | // User will give type 0 to indicate integer 24 | // and type 1 to indicate string 25 | int read_id(union id * x){ 26 | int t; 27 | scanf("%d",&t); 28 | t==0?scanf("%d",&x->id_i):scanf("%s",x->id_s); 29 | return t; 30 | } 31 | 32 | // print a 'union id' given its type 33 | void print_id(int t, union id x){ 34 | t==0?printf("%d",x.id_i):printf("%s",x.id_s); 35 | } 36 | 37 | void main(){ 38 | // This stores the ids 39 | union id id_vals[SIZE]; 40 | // This stores the type information for each id 41 | int id_types[SIZE]; 42 | 43 | // printing the sizes 44 | printsizes(); 45 | 46 | // lets read SIZE number of ids into the id_vals array 47 | // lets also make sure to remember their 48 | // types in the id_types array in the corresponging position 49 | // 50 | for(int i=0;i 2 | 3 | void merge(int * a, int left, int p, int right){ 4 | int l, r, i; 5 | int left_array[100], right_array[100]; 6 | // copy a[left] to a[p] into left_array[] 7 | for( i=left, l=0; i<=p; i++){ 8 | left_array[l++]=a[i]; 9 | } 10 | int ln=l; 11 | // copy a[p+1] to a[right] into right_array[] 12 | for( i=p+1, r=0; i<=right; i++){ 13 | right_array[r++]=a[i]; 14 | } 15 | int rn=r; 16 | // now copy the elemens in sorted order back to a 17 | l=r=0; 18 | for( i=left; i <= right; i++ ){ 19 | if (l == ln ) // copy from r 20 | a[i]=right_array[r++]; 21 | else if (r == rn ) // copy form l 22 | a[i]=left_array[l++]; 23 | else // now copy depending on comparision 24 | if (left_array[l] <= right_array[r]) 25 | a[i]=left_array[l++]; 26 | else 27 | a[i]=right_array[r++]; 28 | 29 | } 30 | } 31 | 32 | void merge_sort(int * a, const int left, const int right){ 33 | // if right-left < 1 then nothing to sort 34 | if ( right-left < 1 ) 35 | return ; 36 | int p=(right+left)/2; 37 | merge_sort(a, left, p); // small change 38 | merge_sort(a, p+1, right); 39 | // now merge the left sorted arrand and the right sorted array 40 | merge(a,left,p,right); 41 | } 42 | 43 | int main(){ 44 | // i is an iteration variable 45 | // n is number of items to read in to sort 46 | int i,n; 47 | // a is the array to store the numbers read in 48 | int a[100]; 49 | 50 | // Prompt and read in the numbers one by one 51 | printf("n=?"); 52 | scanf("%d",&n); 53 | for (i=0; i < n; i++) 54 | scanf("%d",&a[i]); 55 | printf("\n"); 56 | 57 | // Sort the numbers in the array positions 0..n-1 58 | merge_sort(a,0,n-1); 59 | 60 | // print the sorted array 61 | for (i=0; i < n; i++) 62 | printf("%d ",a[i]); 63 | 64 | 65 | } 66 | -------------------------------------------------------------------------------- /SCRIPT/05_conditional_indenting.md: -------------------------------------------------------------------------------- 1 | # Conditional Statements 2 | ## Objective 3 | * Why do we need conditionals 4 | * if and switch 5 | 6 | ## Attempt to write more useful programs: 7 | * The one that requires checking a condition 8 | * The one that requires repeatedly doing something 9 | * The one that requires us to store a large number of values of the same kind 10 | 11 | ## Examples - go through by hand 12 | * read 2 numbers and print the maximum and the minumum 13 | * read a number and find its smallest factor > 1 14 | * read a sequence of numbers and find the maximum 15 | * read a sequence of numbers and find the average 16 | * read a sequence of numbers and find the standard deviation 17 | * read a sequence of numbers and print them in reverse order 18 | * Find the mental constructs needed for each of these. 19 | * Note the need for comparision of some kind in each of these 20 | 21 | ## IF () expression 22 | * Which problems can you solve 23 | * what about quadratic solving 24 | * Can you find max of 2 items 25 | * what about 3 items ? 26 | * what about 4 items ? 27 | * Does the program grow really big? 28 | * EXERCISE fillin\_if.c // answer is in find\_max.c ; 29 | what if you wanted to do different things on different values of a variable. 30 | 31 | ## SWITCH() statement 32 | * read two integers x and y 33 | * read a third character 34 | * do the correspinding operation, see do\_op.c 35 | 36 | * Why we should write well indented code. See examples. 37 | 38 | * End of class check: 39 | * Student should be able to write a program to swap two variables. 40 | * Student should be able to write a program to check that numbers are 41 | give in order, increasing or decreasing and make a statement. 42 | 43 | 44 | -------------------------------------------------------------------------------- /slides/Flowcharts/F05-isprime.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /CLASS/test_Assn_2_answers.txt: -------------------------------------------------------------------------------- 1 | Here are brief answers to come questions on Asseignment 2 2 | If you see any errors mail them to me at my class email address. 3 | 4 | Q1. All programs start at main(). 5 | 5 6 2 7 2 8 6 | 7 | Q2. (a) is right shift by 5 bits. 8 | (b) is bitwise 'and' 9 | (c) first i is assigned 5, then p is assigned 32, then this is compared 10 | with 16, resulting in true which causes the value of p which is 32. 11 | So the answer is 32. 12 | (d) first i is assigned 5. Then i is assigned 50, which is the result. 13 | 14 | 15 | Q3. Note that f() receives a pointer to an integer and that integer is 16 | what it prints. It does not modify that integer. So main() too prints the 17 | same. So both print 555. 18 | 19 | Q4. 20 | 21 | g() m is 100 22 | f() n is 101 23 | main() n is 100 -------> this is the bottom of the stack 24 | 25 | 26 | Q5 & 6. 27 | f always prints what is in the global variable 28 | g always prints what is in its local variable 29 | 30 | In Q5 the local variable g is automatic so initialised each time, so it 31 | prints the same value 201 each time it is invoked. 32 | In Q5 the local variable g is static so initialised once only, so it 33 | prints the 201 th first time and 202 the second time it is invoked. 34 | 35 | 36 | Q7. STOP STOP STOP FLY - seems obvious 37 | 38 | Question - What would happen if we exchanged the order of printf("FLY "); 39 | and f(n-1); 40 | 41 | Q8. 42 | float sum(int n){ 43 | if ( n==0 ) 44 | return 1; 45 | else 46 | reurn sum(n-1)+1/pow(2,i) ; 47 | } 48 | 49 | Q9. 50 | The only two values of n for which the if statement is not executed are 51 | 10 and 5. So these are the only values printed. 52 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Here is the rule: 2 | # : 3 | # 4 | # 5 | # The EXECS need just the default compilation, with perhaps -lm 6 | # NOTE IF IT EXTENDS TO MULTIPLE LINES DONT PUT A BLANK AFTER THE "\" 7 | EXECS= very_first fileio_simple union_simple simple_malloc pointer_simple \ 8 | recursion_simple address_explore apnf \ 9 | array_ops arraySizePtr arraysptr array_struct \ 10 | conversions discriminant \ 11 | gcd lcm 3np1 fact do_op hello_world simple_event_count \ 12 | stats eratosthenes eratosthenes_simple eratosthenes_timer \ 13 | fileio print_next_char find_max \ 14 | for_break_continue \ 15 | simple_expressions integrate \ 16 | funcs funcs_params funcs_scope funcs_scope2 \ 17 | list_avg_f list_avg_w list_avg_d list_avg_array shortcircuit \ 18 | related_arrays matrix_inv matmul matrix_ops \ 19 | search string_simple \ 20 | simple_struct linked_list graph_am \ 21 | basic_sorts qsort qsort_extraspace msort 22 | 23 | # These dont compile; students will complete them in class 24 | FILLIN= fillin_if fillin_while fillin_file fillin_findmax_loop fillin_simple fillin_qsort 25 | 26 | # This is all objs that gets used in some of the executables 27 | OBJS=timeutil.o 28 | 29 | # Programs other than EXECS which need some special compilation, not the default 30 | OTHERS=simple_timing 31 | 32 | CC=gcc 33 | LDLIBS=-lm 34 | 35 | 36 | # By default build all OBJS and all EXECS 37 | all: $(OBJS) $(EXECS) 38 | 39 | # This is some objs being built used mostly as local utilities 40 | timeutil.o: timeutil.c timeutil.h 41 | gcc -c timeutil.c 42 | 43 | # This is the OTHERS built one by one 44 | simple_timing: simple_timing.c timeutil.h $(OBJS) 45 | gcc -o simple_timing simple_timing.c $(OBJS) 46 | 47 | fillin: $(FILLIN) 48 | 49 | clean: 50 | rm -f $(EXECS) $(OBJS) $(FILLIN) $(OTHERS) a.out 51 | -------------------------------------------------------------------------------- /SCRIPT/03_binary_rep.md: -------------------------------------------------------------------------------- 1 | # Binary Representatation 2 | ## Objective: Binary representations and arithmentic 3 | ## Binary Numbers in Computers 4 | * Important to know 5 | * The notion of binary representations 6 | * Why binary? 7 | * A game of coding Lets say A : "00" ; B : "01" ; C : "10" ; D : "11" 8 | * Can you decode **100001** 9 | * Can you encode **ABBA** 10 | * examples of binary representations 0 1 2 4 8 3 5 7 16 15 11 | * easier ways to talk binary - Octal and hexadecimal 12 | * How to store a number in binary? examples 13 | (Just to understand you can see od -cx) and also refer ascii table 14 | * One important concept is that a number like 108 needs only one bytes . 15 | However to store it as characters needs 3 bytes 16 | 17 | * Remember **all** stuff is in binary inside the computer. 18 | So are non-numbers too. 19 | 20 | * With some proactice can you refer ASCII table and say what is stored for 21 | "good" in hexadecimal ? What about a word like "hello"? 22 | wha about doing a od -cx on a file containing exactly that. 23 | 24 | ## Binary Operations 25 | * How does arithmetic work on binary numbers 26 | *Addition* 27 | 28 | * The problem with representation and signs 29 | *Subtraction* is addition of 2's complement 30 | 31 | * More operations in Binary world - Bit operations (AND OR NOT) 32 | 33 | * What is overflow ? 34 | Problems of integers and precision 35 | 36 | * The more important thing is that everything is represented in binary 37 | for example characters and even non integer floats 38 | 39 | ## Exercise: can you use od -cx to see the contents of a file. 40 | In particular a character file? 41 | Can you create a simple ASCII table (char vs hexadecimal) 42 | convert these decimal numbers to binary and vice-versa 43 | Why is hexadecimal so common ? 44 | 45 | -------------------------------------------------------------------------------- /slides/Flowcharts/F01-integrate.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /sort_indices.c: -------------------------------------------------------------------------------- 1 | #include 2 | // We illustrate repurposing bubble sort 3 | // This time not to sort the original array, but to sort an index array 4 | 5 | void readarray(int a[], int n){ 6 | for(int i=0;i a[j] we check a[idx[i]] > a[idx[j]] 25 | // It returns 1 if and only if the above is true else it returns 0 26 | int greater(int *a, int *idx, int i, int j){ 27 | if(a[idx[i]] > a[idx[j]]) 28 | return 1; 29 | return 0; 30 | } 31 | // We also need a way to swap two items in an array 32 | // (this time it is used to swap items in the index array) 33 | void swap(int *a, int i, int j){ 34 | int t; 35 | t = a[i]; 36 | a[i]=a[j]; 37 | a[j]=t; 38 | } 39 | 40 | // now the core bubble sort: 41 | void sort(int *a, int*idx, int n){ 42 | for(int hp=n-1;hp>0;hp--) 43 | for(int i=0;i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /eratosthenes_timer.c: -------------------------------------------------------------------------------- 1 | // computing the primes upto a certain limit 2 | #include 3 | #include 4 | #include 5 | struct { 6 | struct timeval start; 7 | struct timeval end; 8 | } times; 9 | void set_time_start(){ 10 | struct rusage usage; 11 | int r = getrusage(RUSAGE_SELF , &usage); 12 | times.start=usage.ru_utime; 13 | } 14 | void set_time_end(){ 15 | struct rusage usage; 16 | int r = getrusage(RUSAGE_SELF , &usage); 17 | times.end=usage.ru_utime; 18 | } 19 | long get_time_usage(){ 20 | return times.end.tv_sec*1000000+times.end.tv_usec 21 | - times.start.tv_sec*1000000+-times.start.tv_usec; 22 | } 23 | 24 | 25 | #define METHOD 1 26 | #define LIMITN 100000 // Look for primes under this limit 27 | // #define LIMITN 30 // Look for primes under this limit 28 | #define ASIZE 20000 // This will hold all the primes 29 | int main() 30 | { 31 | 32 | struct { 33 | long int rem; 34 | long int prime; 35 | } factor[ASIZE]; 36 | int idx=0, n, isprime, j; 37 | printf("Will list primes starting from 2 upto %d\n",LIMITN); 38 | set_time_start(); 39 | for(n=2;n 2 | 3 | void printarray(int a[], int n){ 4 | // prints n elements starting at a[] 5 | for(int i=0;i 2 | 3 | void make_pivot_the_first(int a[], const int left, const int right){ 4 | // lets assume the first element (leftmost) is the pivot. So no work. 5 | return ; 6 | } 7 | 8 | // In-place pivotting of the array, that means we do not use additional array space 9 | int pivot_the_array(int a[], const int left, const int right){ 10 | int l,r,i; 11 | make_pivot_the_first(a,left,right); 12 | int pv=a[left]; 13 | l=left, r=right; 14 | while( l <= r ) { 15 | // We loop as long as there is something in the range l .. r (ie l <= r ) 16 | while ((l <= r) && (a[l]<=pv) ) // stop when you find an item in a greater then pv 17 | l++; 18 | while ((l <= r ) && (a[r] > pv)) // stop when you find an item in a less than or equal to pv 19 | r--; 20 | if ( l > r ) // break for sure condition 21 | break; 22 | else { // swap a[l] and a[r] 23 | int t = a[l]; 24 | a[l]=a[r]; 25 | a[r]=t; 26 | } 27 | } 28 | int pivot_pos=l-1; // This is the position where pv will sit, it is now at a[left] 29 | int t = a[left]; // 30 | a[left]=a[pivot_pos]; 31 | a[pivot_pos]=t; 32 | 33 | return pivot_pos ; 34 | 35 | } 36 | 37 | void quicksort(int * a, const int left, const int right){ 38 | // if right-left < 1 then nothing to sort 39 | if ( right-left < 1 ) 40 | return ; 41 | int p=pivot_the_array(a,left,right); 42 | quicksort(a, left, p-1); 43 | quicksort(a, p+1, right); 44 | } 45 | 46 | int main(){ 47 | // i is an iteration variable 48 | // n is number of items to read in to sort 49 | int i,n; 50 | // a is the array to store the numbers read in 51 | int a[100]; 52 | 53 | // Prompt and read in the numbers one by one 54 | printf("n=?"); 55 | scanf("%d",&n); 56 | for (i=0; i < n; i++) 57 | scanf("%d",&a[i]); 58 | printf("\n"); 59 | 60 | // Sort the numbers in the array positions 0..n-1 61 | quicksort(a,0,n-1); 62 | 63 | // print the sorted array 64 | for (i=0; i < n; i++) 65 | printf("%d ",a[i]); 66 | 67 | } 68 | -------------------------------------------------------------------------------- /CLASS/09-05-exercises.txt: -------------------------------------------------------------------------------- 1 | Write programs in C for each of the following. 2 | Make sure you put comments that explain your algorithm. 3 | 4 | Every program consists of reading some input and printing some output. 5 | 6 | In each case please test your program with several inputs 7 | covering multiple cases and seeing what the output is: 8 | 9 | 1. Read four integers, and print their mean, 10 | median and the standard deviation. 11 | 12 | 2. Read two characters. Check first that they are both lower case alphabets. 13 | If the distance between the two is odd, then the middle character is unique. 14 | Find and print it. 15 | If the distance between them is even, then print the middle two characters. 16 | 17 | 3. Read three points each point represented by its x and y coordinates 18 | which are floating point numbers and 19 | check if they are colinear and print the appropriate message. 20 | 21 | 4. Read a positive integer and compute the factorial of that number 22 | by repeated multiplication - i.e., 5! is 1*2*3*4*5 23 | (You'll need a loop like whileto do this) 24 | 25 | 5. Write a program to read a character and test if it is an 26 | upper case letter or a lower case letter and print the message 27 | 28 | 6. Read a fraction(ie, a float type), call it r (eg 0.3), 29 | and a positive integer call it n (eg 10) 30 | Print the sum to n terms of the corresponding 31 | geometric series starting at 1 and with r as the common ratio. 32 | 33 | 7. Read a positive integer n and test if it is prime by dividing it by 34 | each integer from 2 to n-1. Print the conclusion. 35 | 36 | 8. Read a positive integer and determine if it is a power of two. 37 | Print your conclusion. 38 | 39 | 9. Look at the program 3np1.c on github. Modify it so that it counts how many 40 | intermediate numbers before it hit 1. Print that count. 41 | 42 | 10. Read a positive integer n. Then read n integers one by one. 43 | After the n integers are read, print out their sum. 44 | 45 | 46 | -------------------------------------------------------------------------------- /simple_expressions.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | /* 5 | This is a comment 6 | over one or more lines 7 | and ends next line 8 | 9 | IMPORTANT: compile with a -lm , because it uses math functions 10 | */ 11 | 12 | // This is also a comment 13 | // Comments have no significance to the behaviour of the program 14 | // 15 | void blah(){ // this is a function definition expression 16 | 7+4; 17 | sin(5.2); // This is a function call expression 18 | } 19 | void testf(){ 20 | } 21 | 22 | int main(){ 23 | // Statements from simple expressions. 24 | 7+4; // arithmetic expression 25 | 7 ; // A value is an expression 26 | 0x7f; 27 | 072 + 4 + 0x7f ; 28 | { // This is a block 29 | 3.41 +6.023e23 ; 30 | } 31 | 5 < 3; // A comparision (relational) expression 32 | // Variable definitions 33 | int i,j,k; 34 | // Assignment is an expression 35 | i = 7 + 4; // Obvious 36 | j = (i = 3); // i = 3 gives a value of 3! 37 | // Note assignment is different from stating equality! 38 | // Arithmetic Expression statements 39 | k = 5 - 3 + 2 ; // associativity is what makes it evaluate the way 40 | // we think! (5-3)+2 41 | k = 5 - 3 * 2 ; // precendence is what makes it evaluate the way 42 | // we think! 5 - (3*2) 43 | k = 5 % 2 ; // This is the "mod" or remainder operator 44 | // Relational expressions 45 | i >= j ; 46 | i > j ; 47 | i > j > k ; // This is a statement, but not what you think! 48 | // Relational expressions are used to check conditions 49 | if ( i>j) 50 | if (j > k ) 51 | printf("i j and k are in decreasing order\n"); 52 | // This is the right way to do the check! 53 | // Logical expressions 54 | if ( (i > j ) && ( j > k )) 55 | printf("i j and k are in decreasing order\n"); 56 | 57 | // Function call expressions 58 | // all calls to printf() above 59 | i = random(); //random is a library function being used to get a value 60 | printf("Trig sum is %f \n",sin(0.1)+cos(0.2) ); 61 | 62 | testf(); // This is a function-call expression 63 | } 64 | -------------------------------------------------------------------------------- /funcs.c: -------------------------------------------------------------------------------- 1 | #include 2 | // Aim 1. show how functions and their prototypes work 3 | // 2. show how the call sequence works 4 | // 3. show how the returns and parameter lists work 5 | 6 | // notion of declare before use - just move around the function 7 | // show prototytpe - needs edits 8 | 9 | 10 | 11 | void saybye(){ 12 | printf(" bye\n"); 13 | } 14 | 15 | void sayhi(){ 16 | printf(" hi\n"); 17 | printf(" Now calling sayhello\n"); 18 | sayhello(); 19 | printf(" back from sayhello\n"); 20 | } 21 | 22 | void sayhello(){ 23 | printf(" hello\n"); 24 | } 25 | 26 | void main(){ 27 | printf("main\n"); 28 | printf("Now calling sayhi\n"); 29 | sayhi(); 30 | printf("back from sayhi\n"); 31 | printf("Now calling saybye\n"); 32 | saybye(); 33 | printf("back from saybye\n"); 34 | } 35 | // ------------- demonstrate parameters and return values 36 | // Modify main to call there one by one 37 | // 38 | int get_number(){ 39 | printf("Will return a value\n"); 40 | return(5); 41 | } 42 | 43 | void print_number(int n){ 44 | printf("print_number: Will receive a value and print it\n"); 45 | printf("%d", n); 46 | } 47 | 48 | int add_numbers(int n, int m){ 49 | printf("add_numbers: Will print received numbers and return their sum\n"); 50 | printf("add_numbers: numbers received are %d and %d\n",n,m); 51 | return n+m; 52 | } 53 | 54 | void compute_average(){ 55 | float n=10.0; 56 | float m=20.0; 57 | printf("Average is %f\n", (n+m)/2); 58 | } 59 | 60 | void compute_average_2(int n, int m){ 61 | // there is some implicit type conversion happening 62 | n=10.0; 63 | m=20.0; 64 | printf("Average is %f\n", (float) (n+m)/2); // compile without the (float) 65 | } 66 | 67 | void another(){ 68 | // Illustrate parameters: 69 | compute_average(); 70 | // compute_average_2(22.0, 28.0); 71 | // float p=8.0, q=24.0; 72 | // compute_average_2(p,q); 73 | 74 | /* 75 | // Illustrate return values: 76 | int x=0; 77 | x=get_number(); 78 | printf("main: %d",x); 79 | print_number(x+100); 80 | x = add_numbers(100,200); 81 | printf("main: %d",x); 82 | */ 83 | 84 | } 85 | 86 | -------------------------------------------------------------------------------- /search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int linear_search( int a[], int left, int right, int q){ 4 | int i; 5 | for( i=left; i <= right ; i++ ){ 6 | if ( a[i] == q ) 7 | return i; 8 | } 9 | return -1; 10 | } 11 | 12 | int binary_search( int a[], int left, int right, int q){ 13 | int m; 14 | int r; 15 | // Base case is if there is only one element 16 | if (left==right) 17 | if (a[left]==q) 18 | return left; 19 | else 20 | return -1; 21 | 22 | // non base case, will have recursion 23 | m = (left+right)/2; 24 | // find how the query key compares with the middle item 25 | // depending on that recurse on one of the sides only 26 | if ( q <= a[m]) 27 | r = binary_search(a, left, m, q); 28 | else 29 | r = binary_search(a, m+1, right, q); 30 | return r; 31 | } 32 | 33 | // A simple iterative version of binary search 34 | int binary_search_loop(int a[], int n, int q){ 35 | int i; 36 | int r=n-1; 37 | int l=0; 38 | while(r-l >= 0 ){ 39 | int mid=(r+l)/2; 40 | if( a[mid] == q ) 41 | return mid; 42 | if( a[mid] > q ) 43 | r=mid-1; 44 | else 45 | l=mid+1; 46 | printf("%d \n",mid); 47 | } 48 | return -1; 49 | 50 | } 51 | 52 | int main(){ 53 | // i is an iteration variable 54 | // n is number of items to read in 55 | int i,n,q; 56 | // a is the array to store the numbers read in 57 | int a[100]; 58 | 59 | // Prompt and read in the numbers one by one 60 | printf("Howmany numbers (n)? "); 61 | 62 | scanf("%d",&n); 63 | printf("Enter the %d numbers( a[] ) :",n); 64 | for (i=0; i < n; i++) 65 | scanf("%d",&a[i]); 66 | printf("\n"); 67 | 68 | // Ask what to search for, ie the query value/ search key 69 | printf("What is the search key (q)? "); 70 | scanf("%d",&q); 71 | 72 | // search for the number in the array 73 | 74 | int idx; 75 | // First using the linear search method 76 | idx = linear_search(a,0,n-1,q); 77 | printf("Found the element at index %d\n",idx); 78 | 79 | // Second using the binary search method 80 | // idx = binary_search(a,0,n-1,q); 81 | idx = binary_search_loop(a,n,q); 82 | printf("Found the element at index %d\n",idx); 83 | } 84 | -------------------------------------------------------------------------------- /fileio.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define INFILE "/tmp/input_file" 6 | #define OUTFILE "/tmp/output_file" 7 | 8 | 9 | #define main_fileio main 10 | 11 | void using_standardio(){ 12 | int n; 13 | char sign; 14 | printf(" Give me a number : "); 15 | scanf("%d",&n); 16 | sign= n < 0 ? '-' : '+' ; 17 | printf("This is %cve\n",sign); 18 | } 19 | void using_file(char *inputfname, char *outputfname){ 20 | int n; 21 | int i; 22 | char sign; 23 | FILE * fp1, * fp2 ; 24 | // printf(" Give me a number : "); Skip this; not doing user interaction 25 | 26 | fp1=fopen(inputfname,"r"); 27 | if (fp1 == NULL ) { // Good idea to check if the open worked 28 | printf("Couldnt open file to read! Exiting!\n"); 29 | exit(1); 30 | } 31 | 32 | fp2=fopen(outputfname,"w"); 33 | if (fp2 == NULL ) { // Good idea to check if the open worked 34 | printf("Couldnt open file to write! Exiting!\n"); 35 | exit(1); 36 | } 37 | 38 | for (i=0;i<5; i++) { // Lets read from the input file now 39 | fscanf(fp1,"%d",&n); 40 | /* 41 | if ( fscanf(fp1,"%d",&n) == EOF) { 42 | printf("TOO FEW NUMBERS IN FILE\n"); exit(1); 43 | } 44 | */ 45 | sign= n < 0 ? '-' : '+' ; 46 | fprintf(fp2,"This is %cve\n",sign); // replace this by stdout for fun 47 | } 48 | fclose(fp1); 49 | fclose(fp2); 50 | } 51 | long rand_from_time(){ 52 | struct timeval tv; struct timezone tz; 53 | gettimeofday(&tv,&tz); 54 | return (long) tv.tv_usec; 55 | } 56 | void seed_random(){ 57 | srand(rand_from_time()); 58 | } 59 | void add_a_quote(FILE * fp){ 60 | static char * quotes[]={"Let go, or be dragged.", 61 | "Look before you leap.", 62 | "No pain, no gain.", 63 | "Do not let the behavior of others destroy your inner peace."}; 64 | fprintf(fp,"%s\n",quotes[0]); 65 | /* 66 | seed_random(); 67 | int i=random()%4; 68 | fprintf(fp,"%s\n",quotes[i]); 69 | */ 70 | } 71 | void append_to_file(char * filename){ 72 | FILE * fp = fopen(filename,"a"); 73 | add_a_quote(fp); 74 | fclose(fp); 75 | } 76 | 77 | // define one of these as main() for testing 78 | void main_fileio(){ 79 | using_file(INFILE,OUTFILE); 80 | // append_to_file(OUTFILE); 81 | } 82 | 83 | void main_stdio(){ 84 | using_standardio(); 85 | } 86 | -------------------------------------------------------------------------------- /slides/Flowcharts/integrate.fprg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /array_ops.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define MAX_STRING_SIZE 100 5 | 6 | // read an array of integers from standard input 7 | int read_iarray(int a[]){ 8 | // Prompt and read in the numbers one by one 9 | int n; 10 | printf("Howmany numbers? "); 11 | scanf("%d",&n); 12 | printf("Give the %d numbers : ",n); 13 | for(int i=0;i 2 | 3 | void main(){ 4 | // Here is some interesting stuff to try out: 5 | 6 | // To print a sequence of numbers 1..4 7 | printf("A sequence of integers:"); 8 | printf("%d",1); 9 | printf("%d",2); 10 | printf("%d",3); 11 | printf("%d",4); 12 | // The %d says we want to print an integer 13 | // Note: Anything we put inside a pair of 14 | // double quotes is called a *string* 15 | // "%d" is called the *format string* 16 | // The 1,2,3, or 4 is the *value* we want to print 17 | // So the rule with printf is: 18 | // printf("format string", value) 19 | 20 | // The next statement 'return' terminates this function 21 | return; // move it around to see what happens 22 | 23 | // Here is another example of printing: 24 | printf("%d",123*45-345/3); 25 | // Here the value to print is got by 26 | // doing arithmetic 27 | 28 | 29 | // The format string can contain normal 30 | // text also: 31 | printf("I have %d horses",3); 32 | // Just the combination of two characters 33 | // %d is called a conversion 34 | 35 | // Just like %d is a conversion 36 | // we can also have special characters 37 | // Note: Special characters always have 38 | // a backslash '\' before them 39 | printf("I have\n %d horses\n",3); 40 | // as you se above \n is a special one and causes a break in the line. 41 | // We can us multiple conversions to 42 | // print multiple values: 43 | printf("%d %d buckle my shoe!\n",1,2); 44 | // So the (updated) rule with printf is: 45 | // printf("format string", value1, value2, ...) 46 | 47 | // We can also simply omit a value, like: 48 | printf("Hello world\n"); 49 | // This is used very often 50 | 51 | // To print 1, 2, 3, 4 separated by spaces 52 | printf("1 2 3 4\n"); 53 | // Also 54 | printf("%d %d %d %d\n",1,2,3,4); 55 | 56 | // Another way to print 1, 2, 3 and 4 57 | printf("Here is another way:\n"); 58 | for (int i=0; i<=4; i++) 59 | printf("%d\n",i); 60 | // The above method uses a concept - loop 61 | 62 | // Printing variable values 63 | printf("Variable usage:\n"); 64 | int a, b; 65 | a = 1; 66 | b = 2; 67 | printf("%d\n",a); 68 | printf("%d\n",b); 69 | // OR 70 | printf("%d\n%d\n",a,b); 71 | // also we can print the sum : 72 | printf(" THE SUM IS : "); 73 | printf("%d\n",a+b); 74 | 75 | // What about the sequence of instructions to compute the sum 76 | } 77 | -------------------------------------------------------------------------------- /qsort_extraspace.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void make_pivot_the_first(int a[], const int left, const int right){ 4 | // lets assume the first element (leftmost) is the pivot. So no work. 5 | return ; 6 | } 7 | 8 | /* Pivot using extra space :- */ 9 | int pivot_the_array(int a[], const int left, const int right){ 10 | 11 | // temporary arrays to store smaller= and larger elements 12 | int left_array[100], right_array[100]; 13 | // l and r are indices to left_array[] and right_array[] 14 | // i is index to a[] 15 | int l,r,i; 16 | 17 | // OK this call does nothing 18 | make_pivot_the_first(a,left,right); 19 | // assumes pivot value is a[left] 20 | int pv=a[left]; 21 | 22 | // Since we are sorting in increasing order... 23 | // Move all items from a[] to left_array[] if item is <= pv except pv ie a[left] 24 | // and to right_array[] if item is > pv 25 | for(l=0, r=0, i=left+1 ; i<=right ; i++ ){ 26 | if (a[i]<=pv ) 27 | left_array[l++]=a[i]; 28 | else 29 | right_array[r++]=a[i]; 30 | } 31 | 32 | // Now there are l elements in the first and r elements in the second 33 | // First move all items from left_array to a 34 | for(i=0 ; i < l ; i++){ 35 | a[left+i]=left_array[i]; 36 | } 37 | 38 | a[left+l]=pv; 39 | int pivot_pos=left+l; 40 | 41 | l++; 42 | // Second move all items from right_array to a 43 | // but start from position "l" 44 | for(i=0 ; i < r ; i++){ 45 | a[left+l+i]=right_array[i]; 46 | } 47 | 48 | // we always return the last point of the lesser-than-equals elements 49 | return pivot_pos ; 50 | } 51 | 52 | void quicksort(int * a, const int left, const int right){ 53 | // if right-left < 1 then nothing to sort 54 | if ( right-left < 1 ) 55 | return ; 56 | int p=pivot_the_array(a,left,right); 57 | quicksort(a, left, p-1); 58 | quicksort(a, p+1, right); 59 | } 60 | 61 | int main(){ 62 | // i is an iteration variable 63 | // n is number of items to read in to sort 64 | int i,n; 65 | // a is the array to store the numbers read in 66 | int a[100]; 67 | 68 | // Prompt and read in the numbers one by one 69 | printf("n=?"); 70 | scanf("%d",&n); 71 | for (i=0; i < n; i++) 72 | scanf("%d",&a[i]); 73 | printf("\n"); 74 | 75 | // Sort the numbers in the array positions 0..n-1 76 | quicksort(a,0,n-1); 77 | 78 | // print the sorted array 79 | for (i=0; i < n; i++) 80 | printf("%d ",a[i]); 81 | 82 | } 83 | -------------------------------------------------------------------------------- /queens.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int happy(int queens[],int size){ 4 | if (size<=1) 5 | return 1; // small board always happy! :-) 6 | 7 | // check if each tgt queen is happy with its followers 8 | for(int tgt=0;tgt=0){ 23 | queens[max]=(queens[max]+1)%size; 24 | if (queens[max]!=0) 25 | break; 26 | max=max-1; 27 | } 28 | return ; 29 | } 30 | 31 | // simple way to show a board 32 | void show(int queens[],int size){ 33 | for(int i=0;i 2 | #define LENGTH 5 3 | 4 | // When declaring as a parameter a 2-D Matrix, 5 | // you need to mention the second dimension, No escaping!! 6 | // something like read_matrix( int a[][] ) **will not** work! 7 | // 8 | // Mentioning the first dimension's length alone is optional 9 | // Dimensions are understood a[]...[] 10 | // So a 3-D Matrix as a parameter may be a[][SIZE1][SIZE2] 11 | void read_matrix( int a[][]){ 12 | // assumes a is LENGTH x LENGTH 13 | for(int i=0;i 2 | #include 3 | 4 | // A few early explorations around pointers and arrays 5 | 6 | // Exploration - 1 7 | // note that int * a and int a [ ] 8 | // are interchangable 9 | void foo(int a[ ]){ 10 | 11 | int i = 0; 12 | while (i < 5) { 13 | printf("%d\n", a[i] ); 14 | i++; 15 | } 16 | 17 | } 18 | /* 19 | // Exploration - 20 | // Returning adress values (pointers) is ok, 21 | // However, you cant return a local variable's address 22 | char * bloo(){ 23 | char a[10]="hello"; 24 | return a ; 25 | } 26 | */ 27 | 28 | void main(){ 29 | int x=10,y=100; 30 | int *p, *q, *r; // Note: Declaring multiple points together 31 | 32 | p = &x; 33 | q = &y; 34 | 35 | /* 36 | // Exploration - 2 37 | // print a bunch of pointers (addresses) 38 | printf("%p %p %p %p\n", p, q, &x, &y); 39 | // We can also print addresses of p and q variables 40 | printf("%p %p\n",&p, &q); 41 | // printing contents pointed to by pointers 42 | printf("%d %d %d %d\n", *p, *q, x, y); 43 | // printing contents pointed to by uninitialized pointer - dangerous: Runtime error 44 | printf("%d\n",*r); 45 | // What is the size of a pointer vs integer on my system? 46 | printf("%d %d\n", sizeof(int), sizeof(int *)); 47 | */ 48 | 49 | /* 50 | // Exploration - 3 51 | // We can now understand scanf a bit better 52 | int z=0; 53 | printf("%p\n",&z); 54 | // Here if we call the function with z instead of &z what goes wrong? 55 | scanf("%d", z); 56 | printf("The value of z is %d\n",z); // should never come to this line 57 | */ 58 | 59 | /* 60 | // Exploration - 4 61 | // the zero-th index item, ie a[0] 62 | int a[10]={1,2,3,4,5}; 63 | a = 0; // bound to fail: Error - you cant assign to an array! 64 | // also array name is like a constant address 65 | a[0]= 0; // This is assigning to an array element 66 | // 67 | // What is the value of a vs &a[0] ? 68 | printf("\n\n%p\n",a); 69 | printf("\n\n%p\n",&a[0]); 70 | // Lesson - An array name is a constant value wiz., the location of the 71 | // beginning of the array 72 | */ 73 | /* 74 | // Exploration - 5 using array name as an address 75 | // Since an array name is an address, 76 | // an integer pointer (int *p) can be assigned the value a 77 | p = a; // inititlizes p to the address a 78 | printf("%p %p\n",p,a); 79 | // A function parameter of type (int *) can also receive the value a 80 | foo(a); 81 | */ 82 | 83 | /* 84 | // Exploration - 6 85 | int m; 86 | p = &m; 87 | printf("%p %p %p\n",p,p+1,p+2); 88 | printf("%d %d %d\n",*p,*(p+1),*(p+2)); 89 | printf("%p %p %p\n",p[0],p[1],p[2]); 90 | */ 91 | } 92 | -------------------------------------------------------------------------------- /SCRIPT/04_confidence_fileio.md: -------------------------------------------------------------------------------- 1 | # CONFIDENCE BUILDING EXERCISES AND A LITTLE MORE I/O 2 | 3 | ## Objective: 4 | * Student is more confident with number representations 5 | * Student can understand ASCII order 6 | * Student understands address vs value 7 | * Student udnerstands logical and other operators too 8 | * Operator precedence 9 | * Student understands the notion of a file and file-IO 10 | * Understand that a function is simply another control flow change 11 | 12 | ## EXPRESSIONS 13 | * Simple expressions and simple programs 14 | * Write a simple program with input and outputs 15 | * Revisit the notion of expressions and values 16 | * Can you check print\_next\_char.c 17 | 18 | ## More on Expressions, lvalue and rvalue 19 | * Recall the notion of expression values 20 | * an interesting expression value is address 21 | * the notion of left and right side of assignment operator 22 | * lvalue and rvalue 23 | * the notion of address and a pointer variable type to hold address 24 | the way to print address and to print what is in an address 25 | 26 | ## IO 27 | * learn more about printf and scanf .... in particular scanf 28 | * reading a writing from files - fprintf, fscanf 29 | * fopen, fscanf 30 | * See fileio.c and io.c 31 | 32 | ## Exercise 33 | * Remember to check the return value for error 34 | * fillin\_file.c 35 | * fillin\_simple.c 36 | * The notion of function calls as simply changing flow of control: funcs.c 37 | 38 | 39 | ## More on IO 40 | * Write more interesting programs using scanf and printf 41 | * Revisit the guessing problem. 42 | * Other problems like check if one number is a factor of another. 43 | 44 | ## More about operators 45 | * ARITHMETIC OPERATORS in C 46 | * \+ - * / % 47 | * COMPARISION (RELATIONAL) OPERATORS in C 48 | * > >= < <= == != 49 | * LOGICAL OPERATORS in C 50 | * && || ! 51 | * BITWISE OPERATORS in C 52 | * & | ^ ~ 53 | 54 | 55 | ### Notion of operator precedence and associativity. 56 | * Consider 5 + 3 * 2 57 | * Consider 5 - 3 + 2 58 | * Refer pp 52 of K&R 59 | * One online reference is [here](https://en.cppreference.com/w/c/language/operator_precedence) 60 | 61 | ## End of class check: 62 | * Student should be able to write a program corresponding to a simple word 63 | problem. Eg. Find the number that is 1/5th of 17 more than twice the number. 64 | * How does one write the output of the hello world program to a file? 65 | * Can you read an integer from a file and print twice its value to another file? 66 | * what does bitwise left shift to a number do? 67 | * Can you check if a&b is giving you the right value through some examples? 68 | -------------------------------------------------------------------------------- /fillin_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void swap_two_variable_values(){ 4 | // var1 and var2 are the two variables for which we want to interchange the contents. 5 | int var1; 6 | int var2; 7 | // We'll also need a temporary variable 8 | int temp; 9 | 10 | scanf("%d %d", &var1, &var2); 11 | printf("Got before swap var1=%d, var2=%d \n", var1, var2); 12 | 13 | // Now do the swapping steps should interchange their values 14 | 15 | 16 | // After this, we should see the variable values interchanged 17 | printf("Now after swap var1=%d, var2=%d \n", var1, var2); 18 | 19 | // POSTSCRIPT: I think it would be a good thing to try to interchange strings or other types, just for fun. 20 | } 21 | 22 | void solve_quadratic(){ 23 | float a,b,c; 24 | float d; 25 | float root1, root2; 26 | 27 | // Use scanf and read in the coefficients a,b and c 28 | 29 | // compute discremenant, ie b squared minus 4ac 30 | // d=... 31 | 32 | // compute roots root1 and root2 33 | // 34 | 35 | // Now print the roots 36 | } 37 | 38 | void compute_vector_components(){ 39 | // read in vector magnitute r (+ve float) and the direction theta (in radians) 40 | 41 | // compute the x coordinate ( r cos theta ) and y coordinate ( r sin theta ) 42 | 43 | // print the coordinates 44 | } 45 | 46 | void compute_vector_mag_and_direction(){ 47 | // read in the (x,y) coordinates of the vector 48 | 49 | // compute the magnitude 50 | 51 | // compute the direction then 52 | 53 | // print the mag and direcion 54 | } 55 | 56 | void convert_to_upper(){ 57 | // Let us declare a variable and iniialize its contents. 58 | char name[20]="My Dear Friend\n"; 59 | int i; 60 | for (i=0; name[i]!='\0' ; i++ ) 61 | if (isalpha(name[i])) 62 | name[i]=toupper(name[i]); 63 | printf("Name after conversion is:%s",name); 64 | } 65 | 66 | void show_sizes(){ 67 | printf("\n For commonly used types :\n"); 68 | printf("sizeof(char) is %ld\n",sizeof(char)); 69 | printf("sizeof(int) is %ld\n",sizeof(int)); 70 | printf("sizeof(float) is %ld\n",sizeof(float)); 71 | printf("sizeof(double) is %ld\n",sizeof(double)); 72 | printf("sizeof(int *) is %ld\n",sizeof(int *)); 73 | 74 | printf("\n\n Additionally :\n"); 75 | 76 | 77 | printf("sizeof(short int) is %ld\n",sizeof(short int)); 78 | printf("sizeof(unsigned short int) is %ld\n",sizeof(unsigned short int)); 79 | printf("sizeof(long int) is %ld\n",sizeof(long int)); 80 | printf("sizeof(unsigned long int) is %ld\n",sizeof(unsigned long int)); 81 | printf("sizeof(long long int) is %ld\n",sizeof(long long int)); 82 | printf("sizeof(unsigned long long int) is %ld\n",sizeof(unsigned long long int)); 83 | } 84 | 85 | void main(){ 86 | convert_to_upper(); 87 | } 88 | -------------------------------------------------------------------------------- /MiscCProgs-2025/pouringwatersim.c: -------------------------------------------------------------------------------- 1 | // Simulate the scenario 2 | // You want to demostrate measure out 5 L 3 | // You have a 7 L and 4 L can filled with water 4 | // Modeling : 5 | // ** two jars named 1 and 2 (Fixed) 6 | // ** each has howmuch water it holds at any point in time - cal these w1 and w2 7 | // ** Each jar has a capacity call them c1 and c2 (read in) 8 | // ** Target amount (read in - this is the amount to measure out exactly) 9 | // ** current amount measured out already - call this measured 10 | // Operations possible 11 | // F 1/2 Fill up Jar 1 or Jar 2 from the tap 12 | // E 1/2 Empty out Jar 1 or 2 13 | // M 1/2 Measure out Jar 1 or 2 (ie entire contents of that jar) 14 | // P 1 2 Pour from Jar 1 to Jar 2 until Jar 1 empties or Jar 2 fills which ever is earlier 15 | // similarly P 2 1 16 | #include 17 | #include 18 | 19 | #define equals(X,Y) (strcmp(X,Y)==0) 20 | #define min(X,Y) (X 2 | 3 | void make_pivot_the_first(int a[], const int left, const int right){ 4 | // lets assume the first element (leftmost) is the pivot. So no work. 5 | return ; 6 | } 7 | 8 | /* Pivot using extra space :- */ 9 | int pivot_the_array(int a[], const int left, const int right){ 10 | 11 | // temporary arrays to store smaller= and larger elements 12 | int left_array[100], right_array[100]; 13 | // l and r are indices to left_array[] and right_array[] 14 | // i is index to a[] 15 | int l,r,i; 16 | 17 | // OK this call does nothing 18 | // make_pivot_the_first(a,left,right); 19 | // assumes pivot value is a[left] 20 | int pv=a[left]; 21 | 22 | // Since we are sorting in increasing order... 23 | // Move all items from a[] to left_array[] if item is <= pv except pv ie a[left] 24 | // and to right_array[] if item is > pv 25 | for(l=0, r=0, i=left+1 ; i<=right ; i++ ){ 26 | if ( ) // if i-th element is less than or equal to pv move it to the left_array 27 | left_array... 28 | else // if i-th element is greater than pv move it to the right_array 29 | right_array... 30 | } 31 | 32 | // Now there are l elements in the left_array and r elements in the right_array 33 | // First move all items from left_array to a 34 | for(i=0 ; i < l ; i++){ 35 | a[....]=left_array[...]; 36 | } 37 | // move pv to the next position ie ... 38 | a[ ]=pv; 39 | int pivot_pos=left+l; 40 | 41 | l++; 42 | // Next move all items from right_array to a 43 | // after pv in a 44 | for(i=0 ; i < r ; i++){ 45 | a[...]=right_array[...]; 46 | } 47 | 48 | // we always return the last point of the lesser-than-equals elements 49 | return pivot_pos ; 50 | } 51 | 52 | void quicksort(int * a, const int left, const int right){ 53 | // if 1 or fewer elements between left and right, then nothing to do 54 | if ( right-left < 1 ) 55 | return ; 56 | // Else 57 | // partition the array around a pivot value .. this will cause elements to move around 58 | // But the item at index p is ins right place and there is no need to move that! 59 | int p=pivot_the_array(a,left,right); // p is the pivot value's index in a. a[p] has found its home! 60 | quicksort(a, left, p-1); // now sort the part that has values smaller than or equal to the pivot value 61 | quicksort(a, p+1, right); // next sort the part that has values greater than the pivot value 62 | } 63 | 64 | int main(){ 65 | // i is an iteration variable 66 | // n is number of items to read in to sort 67 | int i,n; 68 | // a is the array to store the numbers read in 69 | int a[100]; 70 | 71 | // Prompt and read in the numbers one by one 72 | printf("n=?"); 73 | scanf("%d",&n); 74 | for (i=0; i < n; i++) 75 | scanf("%d",&a[i]); 76 | printf("\n"); 77 | 78 | // Sort the numbers in the array positions 0..n-1 79 | quicksort(a,0,n-1); 80 | 81 | // print the sorted array 82 | for (i=0; i < n; i++) 83 | printf("%d ",a[i]); 84 | 85 | } 86 | -------------------------------------------------------------------------------- /SCRIPT/02_expr_stmt_var.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Expressions, Statements and Blocks in C 5 | ## Objective: 6 | * Notion of expressions, statements, blocks 7 | ( Lets try to look at programs and what its elements are. ) 8 | * Notion of constants and opetators 9 | * Write a program independently 10 | * Notion of a variable 11 | * Notion of value vs address 12 | 13 | ## Expressions and Values 14 | * A program as a collection of expressions. 15 | * Expressions are used mainly to get values. 16 | * They can be arithmetic, logical, etc. 17 | * See expr.c 18 | * Here are many expressions 19 | ~~~text 20 | 5+3 is an expression. 21 | 5 (note that expressions dont need to have operators) 22 | 6.023 * 2 ( numbers can be non-integers too) 23 | 'R' is a sigle character expression 24 | Another expression is "hello world" (this is a sequence of characters) 25 | 5 < 3 is a logic expression 26 | Same with 5 < 3 && 2 > 1 27 | ~~~ 28 | Clearly we can put paranethesis to make it clear to us (and to others) 29 | ~~~text 30 | (5-3)-2 31 | (5-(3-2)) 32 | 5-3-2 33 | ~~~ 34 | 35 | * An arithmetic expression can be converted to a statement by using a ";" 36 | at the end. 37 | 38 | * Lets write a fully working program with this expression. 39 | 40 | * Exercise: Download and edit simple\_expressions.c 41 | 42 | * Lets summarize the learning: 43 | ~~~text 44 | | Expressions | "Type" of the value in C 45 | | --------------------- | ------------------------ 46 | | 5 | integer 47 | | 5+3 | integer 48 | | 6.023 * 2 | float (real number) 49 | | 'c' | character 50 | | "Hello world" | character sequence (a pointer to the first character) 51 | | sin(0.5) | (function call expression resulting in) a floating point value 52 | ~~~ 53 | 54 | ## Notions of constants and operators in expressions 55 | 56 | ## Practicalities 57 | * Expressions are good but 58 | we would like to see something when a program is run 59 | * We can use some help to print using puts, putchar or printf 60 | 61 | ## Notion of Stored Values and Variables 62 | * storing values is an important expression using the familiar '=' sign 63 | variables have address as well as value, but expressions only have value 64 | * Notions of memory 65 | * MODEL of storage and instructions. 66 | * go back to objdump --disassemble 67 | ## Concept of definition of variables 68 | * List of types in variable definitions 69 | * Notion of scope 70 | * (also declaration) - how with extern declaration of a global 71 | * We will learn more when we talk about functions 72 | 73 | ## Lets write a fully working proram with the storing idea 74 | ## Proacticality - reading and printing 75 | * expression and printing is good, but we may want to read something 76 | into variables instead of fixing them in the program 77 | * we can use some help to read using scanf 78 | 79 | ## Exercise: 80 | * The game of guessing 2(x+10)-2x = 20 81 | * Is it possible to get the address value ? 82 | 83 | -------------------------------------------------------------------------------- /recursion_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define main_sum main 4 | 5 | 6 | // print all characters upto a given character 7 | void printupto(char c){ 8 | 9 | // base case is a character less than 'a' : do nothing 10 | if (c < 'a') 11 | return ; 12 | 13 | 14 | // usual case 15 | // first print all characters upto the previous character. 16 | printupto(c-1); 17 | // then print this given character 18 | printf("%c",c); 19 | 20 | // use gdb and investigate what the frame/stack looks like 21 | } 22 | 23 | // add numbers upto a given number and return the total 24 | // mathematically 25 | // sum(n) is 26 | // 0 if n <=0 (base case) 27 | // 28 | // n+sum(n-1) otherwise (recursion case) 29 | int sum(int n) { 30 | // base case 31 | if (n <= 0 ) 32 | return 0; 33 | 34 | int s; 35 | // otherwise 36 | // find the sum of upto n-1 37 | s = sum(n-1); 38 | // add n to that 39 | s += n; 40 | return s; 41 | } 42 | 43 | void main_print(){ 44 | char c; 45 | scanf(" %c",&c); 46 | 47 | // we want the character to be one of 'a' ... 'c' 48 | if ( c > 'z' || c < 'a' ) 49 | exit(1); 50 | 51 | printupto(c-1); 52 | printf("%c\n",c); 53 | } 54 | 55 | void main_sum(){ 56 | int n; 57 | scanf("%d",&n); 58 | int s = sum(n); 59 | printf("sum of integers from 0 to %d is %d\n",n,s); 60 | } 61 | 62 | // Recursiv structure of any problem solution can be used to create a 63 | // recursive function 64 | // Exercise: 0. Write a recursive function to print the triangle of stars 65 | // left justified. triangle1(n): 66 | // The idea is: if n<=0 nothing to print 67 | // else print n stars in a row and a newline 68 | // and recursively call to print triangle1(n-1) 69 | // but with n-1 70 | // 1. recursively print similar to triangle1 but inverted! 71 | // 2. recursively print paranthesis(n) will be 72 | // ((((... n times followed by )))) equal number of times 73 | // a recursive way to look at it is 74 | // ( followed by parenthesis(n-1) followed by ) 75 | // 3. recursively print a palindrome. If someone gave 'c' print 76 | // mypal('c') would print cbabc 77 | // mypal('e') would print edcbabcde 78 | // Exercise: 1. write a recursion for the sum 0-1+2-3+4-5 ...... upto given n 79 | // note if n is odd we subtract. If n is even we add. 80 | // he sums will look like 0 -1 1 -2 2 -3 3 ... 81 | // 82 | // 2. Write a recursion for the fibonacci sequence with base cases: 83 | // f0 = 0 and f1 = 1 84 | // f(n) = f(n-1) + f(n-2) for n > 1 85 | // 86 | // 3. nCr = 0 if nr and r=0 89 | // = n-1Cr + n-1Cr-r if n > r > 0 90 | // assume of course than n >=0 and r >= 0 91 | // and compute nCr for given n and r 92 | -------------------------------------------------------------------------------- /array_struct.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define konstant 8.98e09 4 | 5 | // This is a structure to represent a charged particle on a plane. 6 | struct particle { 7 | float x; // x position on a plane 8 | float y; // y position on a plane 9 | float q; // charge in culomb 10 | }; 11 | 12 | // To read one particle into the given parameter 13 | void read_a_particle(struct particle *p){ 14 | } 15 | 16 | // To read an integer n from the user 17 | // allocate an array to hold n particles 18 | // Now read the particles one by one into a[0]..a[n-1] 19 | // return the pointer to the allocated array 20 | struct particle * get_new_particle_array(int *length){ 21 | struct particle *arrayp; 22 | // write all the code to read n, then malloc, then read n particles 23 | // set *length to the number of particles, ie value of n 24 | return arrayp; 25 | } 26 | 27 | // To print a particle array with n particles 28 | void print_particle_array( struct particle * p, int n){ 29 | 30 | } 31 | 32 | // To join(concatenate) two particle arrays into a new one 33 | struct particle * join_particle_arrays(struct particle a1[],int n1, struct particle a2[], int n2){ 34 | // new array has a1[0]..a1[n1-1] a2[0]..a2[n2-1] 35 | // allocate then copy particles 36 | // return pointer to the newly allocated array 37 | 38 | } 39 | 40 | // find the force between two particles 41 | float find_force(struct particle p1, struct particle p2){ 42 | float force; 43 | // by definition force = konstant * (q1*q2)/(r*r) 44 | return force; 45 | } 46 | 47 | // sorting an array of particles (just to show sorting on structure arrays) 48 | 49 | // First we need a greater than function: returns 1 if and only if a[i]>a[j] 50 | // else it returns 0 51 | int greater(struct particle *a, int i, int j){ 52 | if(a[i].x > a[j].x) 53 | return 1; 54 | if( (a[i].x == a[j].x) && (a[i].y > a[j].y) ) 55 | return 1; 56 | return 0; 57 | } 58 | // We also need a way to swap to particles in an array 59 | void swap(struct particle *a, int i, int j){ 60 | struct particle t; 61 | t = a[i]; 62 | a[i]=a[j]; 63 | a[j]=t; 64 | } 65 | 66 | // Now the core bubble sort algorithm - really no change 67 | void sort(struct particle *a, int n){ 68 | for(int hp=n-1;hp>0;hp--) 69 | for(int i=0;i 7 | #include 8 | 9 | // we have three globals - not a good idea, however 10 | int zi,zj; 11 | int square[4][4]; 12 | 13 | 14 | // Initializes a 4x4 square as a solved square with bottom right being the empty square represented by zero 15 | int initialize(int square[][4]){ 16 | for(int i=0;i<15;i++) 17 | square[i/4][i%4]=i+1; 18 | square[3][3]=0; 19 | zi=zj=3; 20 | } 21 | 22 | // Check if a 4x4 square is indentical to the square as initilized above. 23 | // return 1 if solved, 0 if not 24 | int checkIfSolved(int square[][4]){ 25 | for(int i=0;i<15;i++) 26 | if(square[i/4][i%4]!=i+1) 27 | return 0; 28 | return 1; 29 | } 30 | 31 | // swap the contents of (i1,j1) wiht (i2,j2) 32 | void swap(int square[][4], int i1, int j1, int i2, int j2){ 33 | int t = square[i1][j1]; 34 | square[i1][j1]=square[i2][j2]; 35 | square[i2][j2]=t; 36 | } 37 | 38 | // randomly pick two square positions and interchange their content 39 | void randomize(int square[][4]){ 40 | // Idea: 41 | // find a random (i,j) each in 0..3 42 | // find another random (i,j) each in 0..3 43 | // make sure they are different 44 | // swap their contents 45 | int i1, j1, i2, j2; 46 | i1=random()%4; 47 | j1=random()%4; 48 | i2=random()%4; 49 | j2=random()%4; 50 | swap(square,i1,j1,i2,j2); 51 | printf("Swapped (%d,%d), with (%d,%d)\n",i1,j1,i2,j2); 52 | if (i1==zi && j1==zj) { 53 | zi=i2; zj=j2; 54 | } else if (i2==zi && j2==zj) { 55 | zi=i1; zj=j1; 56 | } 57 | } 58 | 59 | // print the contents of a square 60 | void print(int square[][4]){ 61 | for(int i=0;i<4;i++) { 62 | for(int j=0;j<4;j++) 63 | printf(" %3d",square[i][j]); 64 | printf("\n"); 65 | } 66 | } 67 | 68 | // Take input from user in terms of up/down/left/right and move the piece appropriately 69 | int solve(int square[][4]){ 70 | // ask for a move and do it 71 | char dir; 72 | printf("> "); 73 | scanf(" %c", &dir); 74 | int i=zi; 75 | int j=zj; 76 | if (dir=='u' || dir=='u') { 77 | if(i>0) zi-=1; 78 | } else if (dir=='d' || dir=='D') { 79 | if(i<3) zi+=1; 80 | } else if (dir=='r' || dir=='R') { 81 | if(j<3) zj+=1; 82 | } else if (dir=='l' || dir=='L'){ 83 | if(j>0) zj-=1; 84 | } else { 85 | printf("Bad input\n"); 86 | return 0; 87 | } 88 | swap(square,i,j,zi,zj); 89 | return checkIfSolved(square); 90 | } 91 | 92 | int main(){ 93 | int square[4][4]; 94 | srand(20); 95 | 96 | initialize(square); 97 | print(square); 98 | 99 | int k; 100 | printf("Howmany randomize steps: "); 101 | scanf("%d",&k); 102 | 103 | for(int i=0;i 2 | void bubble_sort(int a[], int n); 3 | void insert_sort(int a[], int n); 4 | void select_sort(int a[], int n); 5 | 6 | // Look at these functions one by one 7 | // 8 | // 1. Simple swap of any two indices 9 | // calling it with swap(a,i,i+1) would swap a[i] with a[i+1] 10 | void swap(int a[], int i, int j){ 11 | int t = a[i]; 12 | a[i]=a[j]; 13 | a[j]=t; 14 | } 15 | 16 | // 2. Modified swap of successive indices, but do it only if a[i] > a[i+1] 17 | void swap_greaterup(int a[], int i){ 18 | if (a[i] > a[i+1] ) 19 | swap(a,i,i+1); 20 | } 21 | 22 | // 3. Repeatedly do the modified swap above for each valid value of i 23 | void repeat_swap_greaterup(int a[], int n){ 24 | for(int i=0;i val ) 42 | break; 43 | // from position i move everything up one space 44 | // But do it in reverse order! 45 | for(int j=n-1;j>=i;j--) 46 | a[j+1]=a[j]; 47 | 48 | // insert the new value 49 | a[i]=val; 50 | } 51 | 52 | // 6. Return the largest element in an array 53 | int position_largest(int a[], int n){ 54 | int i=0; 55 | int largest_pos=0; 56 | int largest_val=a[0]; 57 | for(i=1; ilargest_val) { 59 | largest_val=a[i], largest_pos=i; 60 | } 61 | return largest_pos; 62 | } 63 | 64 | 65 | void main(){ 66 | int a[]={5,3,2,8,6,9,1,0}; 67 | int n = sizeof(a)/sizeof(int); 68 | 69 | printf("%d\n",n); 70 | print_array(a,n); // print the input 71 | 72 | // Swap greated up the array 73 | // repeat_swap_greaterup(a,n); // do the repeated swap 74 | 75 | /* 76 | // insert from array a[] into array b[] 77 | int m=0; 78 | insert_ordered(b,m,a[i]); m++; 79 | print_array(b,m); // print he array b[] 80 | 81 | // find greatest in array a[] and put it at the end 82 | // 83 | int l ; 84 | l = position_largest(a,n); 85 | swap(a,n-1,l); // put largest in the end, but keep all the elements 86 | */ 87 | 88 | select_sort(a,n); 89 | 90 | print_array(a,n); // print the result modified array 91 | } 92 | 93 | 94 | 95 | 96 | 97 | void bubble_sort(int a[], int n){ 98 | printf("%d\n",n); 99 | for(int i=0; i < n-1 ; i++) 100 | repeat_swap_greaterup(a,n); // do the repeated swap: (n-i, maybe?) 101 | } 102 | 103 | void insert_sort(int a[], int n){ 104 | int b[20]; 105 | int m=0; 106 | for( int i=0; i0;i--) { 114 | l = position_largest(a,i); 115 | swap(a,i-1,l); // put largest in the end, but keep all the elements 116 | } 117 | } 118 | 119 | -------------------------------------------------------------------------------- /matrix_inv.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | float determinant(float [][25], float); 4 | void cofactor(float [][25], float); 5 | void transpose(float [][25], float [][25], float); 6 | int main() 7 | { 8 | float a[25][25], k, d; 9 | int i, j; 10 | printf("Enter the order of the Matrix : "); 11 | scanf("%f", &k); 12 | printf("Enter the elements of %.0fX%.0f Matrix : \n", k, k); 13 | for (i = 0;i < k; i++) 14 | { 15 | for (j = 0;j < k; j++) 16 | { 17 | scanf("%f", &a[i][j]); 18 | } 19 | } 20 | d = determinant(a, k); 21 | if (d == 0) 22 | printf("\nInverse of Entered Matrix is not possible\n"); 23 | else 24 | cofactor(a, k); 25 | } 26 | 27 | /*For calculating Determinant of the Matrix */ 28 | float determinant(float a[25][25], float k) 29 | { 30 | float s = 1, det = 0, b[25][25]; 31 | int i, j, m, n, c; 32 | if (k == 1) 33 | { 34 | return (a[0][0]); 35 | } 36 | else 37 | { 38 | det = 0; 39 | for (c = 0; c < k; c++) 40 | { 41 | m = 0; 42 | n = 0; 43 | for (i = 0;i < k; i++) 44 | { 45 | for (j = 0 ;j < k; j++) 46 | { 47 | b[i][j] = 0; 48 | if (i != 0 && j != c) 49 | { 50 | b[m][n] = a[i][j]; 51 | if (n < (k - 2)) 52 | n++; 53 | else 54 | { 55 | n = 0; 56 | m++; 57 | } 58 | } 59 | } 60 | } 61 | det = det + s * (a[0][c] * determinant(b, k - 1)); 62 | s = -1 * s; 63 | } 64 | } 65 | 66 | return (det); 67 | } 68 | 69 | void cofactor(float num[25][25], float f) 70 | { 71 | float b[25][25], fac[25][25]; 72 | int p, q, m, n, i, j; 73 | for (q = 0;q < f; q++) 74 | { 75 | for (p = 0;p < f; p++) 76 | { 77 | m = 0; 78 | n = 0; 79 | for (i = 0;i < f; i++) 80 | { 81 | for (j = 0;j < f; j++) 82 | { 83 | if (i != q && j != p) 84 | { 85 | b[m][n] = num[i][j]; 86 | if (n < (f - 2)) 87 | n++; 88 | else 89 | { 90 | n = 0; 91 | m++; 92 | } 93 | } 94 | } 95 | } 96 | fac[q][p] = pow(-1, q + p) * determinant(b, f - 1); 97 | } 98 | } 99 | transpose(num, fac, f); 100 | } 101 | /*Finding transpose of matrix*/ 102 | void transpose(float num[25][25], float fac[25][25], float r) 103 | { 104 | int i, j; 105 | float b[25][25], inverse[25][25], d; 106 | 107 | for (i = 0;i < r; i++) 108 | { 109 | for (j = 0;j < r; j++) 110 | { 111 | b[i][j] = fac[j][i]; 112 | } 113 | } 114 | d = determinant(num, r); 115 | for (i = 0;i < r; i++) 116 | { 117 | for (j = 0;j < r; j++) 118 | { 119 | inverse[i][j] = b[i][j] / d; 120 | } 121 | } 122 | printf("\n\n\nThe inverse of matrix is : \n"); 123 | 124 | for (i = 0;i < r; i++) 125 | { 126 | for (j = 0;j < r; j++) 127 | { 128 | printf("\t%f", inverse[i][j]); 129 | } 130 | printf("\n"); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /MiscCProgs-2025/towersim.c: -------------------------------------------------------------------------------- 1 | // A B and C are three towers. 2 | // A has 1 on 2 on 3 on ... on N in that order. 3 | // Given a sequence of move like 4 | // A B 5 | // B A 6 | // B C 7 | // Detect if it is legal. If yes, then print the stacks A B and C after the moves. 8 | #include 9 | #include 10 | #define equals(X,Y) (strcmp(X,Y)==0) 11 | int main(){ 12 | int aTop=1, bTop=0, cTop=0; 13 | int aMid=2, bMid=0, cMid=0; 14 | int aBot=3, bBot=0, cBot=0; 15 | 16 | while ( cTop!=1 || cMid != 2 || cBot !=3 ){ 17 | printf("%3d %3d %3d\n",aTop,bTop,cTop); 18 | printf("%3d %3d %3d\n",aMid,bMid,cMid); 19 | printf("%3d %3d %3d\n",aBot,bBot,cBot); 20 | 21 | char f[10],t[10]; 22 | int i=0; 23 | printf("> from ? to ? :"); 24 | scanf("%s %s",f,t); 25 | if (equals(f,"A") ) { 26 | // pick up from the f stick 27 | if (aTop!=0) { i=aTop; aTop=0; } 28 | else if (aMid != 0 ) { i=aMid; aMid=0;} 29 | else if (aBot != 0 ) { i=aBot; aBot=0;} 30 | else { i=0; printf("Bad move, STOPPED***\n"); return 1; } 31 | 32 | //place on the appropriate t stick 33 | if (i!=0 && // if you found a disk, check destination size and move 34 | equals(t,"B")) { 35 | if (bBot==0) { bBot=i; } 36 | else if (bMid == 0 && bBot > i) { bMid=i;} 37 | else if (bTop == 0 && bMid > i) { bTop=i;} 38 | else { printf("Bad move, STOPPED***\n"); return 1;} 39 | } else if(i!=0 && 40 | equals(t,"C")) { 41 | if (cBot==0) { cBot=i; } 42 | else if (cMid == 0 && cBot > i) { cMid=i;} 43 | else if (cTop == 0 && cMid > i) { cTop=i;} 44 | else { printf("Bad move, STOPPED***\n"); return 1;} 45 | } 46 | } 47 | if (equals(f,"B") ) { 48 | if (bTop!=0) { i=bTop; bTop=0; } 49 | else if (bMid != 0 ) { i=bMid; bMid=0;} 50 | else if (bBot != 0 ) { i=bBot; bBot=0;} 51 | else { i=0; printf("Bad move, STOPPED***\n"); return 1; } 52 | 53 | //place on the appropriate t stick 54 | if (i!=0 && // if you found a disk, check destination size and move 55 | equals(t,"A")) { 56 | if (aBot==0) { aBot=i; } 57 | else if (aMid == 0 && aBot > i) { aMid=i;} 58 | else if (aTop == 0 && aMid > i) { aTop=i;} 59 | else { printf("Bad move, STOPPED***\n"); return 1;} 60 | } else if(i!=0 && 61 | equals(t,"C")) { 62 | if (cBot==0) { cBot=i; } 63 | else if (cMid == 0 && cBot > i) { cMid=i;} 64 | else if (cTop == 0 && cMid > i) { cTop=i;} 65 | else { printf("Bad move, STOPPED***\n"); return 1;} 66 | } 67 | } 68 | if (equals(f,"C") ) { 69 | if (cTop!=0) { i=cTop; cTop=0; } 70 | else if (cMid != 0 ) { i=cMid; cMid=0;} 71 | else if (cBot != 0 ) { i=cBot; cBot=0;} 72 | else { i=0; printf("Bad move, STOPPED***\n"); return 1; } 73 | 74 | //place on the appropriate t stick 75 | if (i!=0 && // if you found a disk, check destination size and move 76 | equals(t,"A")) { 77 | if (aBot==0) { aBot=i; } 78 | else if (aMid == 0 && aBot > i) { aMid=i;} 79 | else if (aTop == 0 && aMid > i) { aTop=i;} 80 | else { printf("Bad move, STOPPED***\n"); return 1;} 81 | } else if(i!=0 && 82 | equals(t,"B")) { 83 | if (bBot==0) { bBot=i; } 84 | else if (bMid == 0 && bBot > i) { bMid=i;} 85 | else if (bTop == 0 && bMid > i) { bTop=i;} 86 | else { printf("Bad move, STOPPED***\n"); return 1;} 87 | } 88 | } 89 | } 90 | printf("Done!\n"); 91 | 92 | } 93 | 94 | 95 | -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_5.txt: -------------------------------------------------------------------------------- 1 | 1. This is to give a good grounding in linked lists 2 | You will create and maintain an ordered linked list of structures. 3 | we'll call it struct person. 4 | It has these fields 5 | * character string name[] of length 20 6 | * integer age 7 | * integer id 8 | * integer occupation which is one of these codes: 9 | 0 - unoccupied 10 | 1 - student 11 | 2 - teacher 12 | 3 - homemaker 13 | 4 - employed 14 | 5 - others 15 | * a pointer used to point to the next node in the linked list. 16 | The nodes in the linked list will be ordered by the field called id. 17 | 18 | Here are the functions you need to write: 19 | struct person * read_new_person(); 20 | This will read from the input name, age, id and occupation 21 | and put these into a newly allocated structure and return that 22 | pointer to that structure. 23 | 24 | struct person * insert_person_into_list(struct person * head, struct person *newnode); 25 | This will insert the node pointed to by newnode into the list pointed to by head and return a pointer to the new list. It has to insert 26 | the new node in the right position so that the list is ordered 27 | by increasing id values. 28 | It returns a pointer to the head of this new list. 29 | 30 | struct person * read_person_list(); 31 | This will repeatedly call read_new_person and insert_person_into list 32 | functions so that a list of persons is read. You will of course 33 | have to ask for the number of persons to read into the list. 34 | It returns the pointer to the newly created list's head. 35 | 36 | struct person * delete_person_from_list(struct person * head, int id); 37 | This will search for the struc person in that list that matches that 38 | given id and if it exists, then delete that structure form the list. 39 | It returns a pointer to the head of the (possibly) changed list 40 | 41 | int list_length(struct person * head); 42 | It returns the number of structures in the list 43 | 44 | struct list * get_as_array(struct person * head, int n); 45 | It returns an array of n person structs. This array has same 46 | nodes as in the first n nodes in the linked list whose head is given. 47 | (so it simply duplicates part of the linked as as an array). 48 | /* notice how we use struct list * to also point to an array 49 | os structures! */ 50 | 51 | int binary_search(struct person a[], int id); 52 | This returns the index in the array 53 | if the person with id is in the list and -1 otherwise. 54 | It does this by using binary search on the array a. 55 | 56 | 57 | In your main program read a list of persons. The repeatdely get an id from the user and delete the person from the list. 58 | Check the length of the list before and after all the deletetions. 59 | Then in an array get all the persons in the linked list. 60 | Then use ask for an id from the user and use binary search to find if 61 | the person with the id is in the list. Then it prints that person's name. 62 | 63 | 64 | 2. This exercise is to test your ability to do bubble sort. 65 | write void bubble_sort(char * a[], int n); 66 | also write void read_strings(char *a[], int n); 67 | to read an array of n integers into a[] 68 | This will sort the array a[] of n strings. 69 | The difference is that your comparision is a string comparision. 70 | - use the strcmp() function to do the string comparision. 71 | - see man strcmp for how it works 72 | -------------------------------------------------------------------------------- /pointer_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define TEST_NO 1 3 | 4 | // This file has multiple tests for the way pointers work. 5 | // Select the test by defining the variable test in main() to be in the appropriate range 6 | 7 | void show_value_p(void *p){ // recall that a pointer holds an address value 8 | printf("Inside function p is %p \n", p); 9 | } 10 | 11 | void swap_ints(int x, int y){ 12 | int t; 13 | t = x; 14 | x = y; 15 | y = t; 16 | } 17 | 18 | 19 | void swap_ints_by_ptr( int * x, int * y){ 20 | int t; 21 | t = *x; 22 | *x = *y; 23 | *y = t; 24 | } 25 | 26 | 27 | void main(){ 28 | int test= TEST_NO ; 29 | 30 | printf(" - - - - - - - - Will do test # %d\n",test); 31 | 32 | switch(test){ 33 | case 1: { 34 | // p is unititialized 35 | int *p; 36 | // Lets see the address that p holds - should be junk 37 | printf("p holds the address %p\n", p); 38 | // The location p is looking at change that int's value to 1024 39 | // normally p=something must happen before his, 40 | *p=1024; // This step should result in 'Segmentation fault' 41 | // Lets see what is in the address that p holds - should get here 42 | printf("that above address has this value %d\n",*p); 43 | } 44 | 45 | case 2: { 46 | // p has an invalid address - sort of like unitialized 47 | int *p; 48 | p = (int *) 1024; // Try putting 1024 into p .. not a valid address 49 | // Lets see the address that p holds 50 | printf("p holds the address %p\n", p); 51 | // Lets see what is in the address that p holds 52 | printf("that above address has this value:\n"); 53 | printf(" %d\n",*p); // This step should cause in 'Segmentation fault' 54 | } 55 | 56 | case 3: { 57 | // Now the right way to do things: 58 | int *p; 59 | int i; 60 | p = &i; // This ensures the address in p is a valid integer location 61 | // Note that i is un-initialized, 62 | // which may be a problem if we use it's value 63 | // Lets see the address that p holds 64 | printf("p holds the address %p\n", p); 65 | // Lets see what is in the address that p holds 66 | show_value_p(&i); // The "&" operator results in an address value 67 | printf("that above address has this value:\n"); 68 | printf(" *p is %d\n",*p); 69 | printf(" i is %d\n",i); 70 | break; 71 | } 72 | 73 | case 4: { 74 | // This is to demonstrate address arithmetic 75 | int *p; 76 | p = (int * ) 1024; // careful! *p is invalid :-) 77 | printf("p holds the address %p\n", p); // note "%p" format conversion 78 | printf("sizeof(int) is %ld\n", sizeof(int)); 79 | p ++; // Note that p++ is pointer arithmetic operation: 80 | // it increases p to point to the integer location 81 | // after the current integer address p. 82 | printf("p incremented holds the address %p\n\n", p); 83 | char *pc; 84 | pc = (char *) 1024; 85 | printf("pc holds the address %p\n", pc); 86 | printf("sizeof(char) is %ld\n", sizeof(char)); 87 | pc ++; // Note that p++ is pointer arithmetic: 88 | // it increases p to point to the character location after the current character address p. 89 | printf("pc incremented holds the address %p\n", pc); 90 | 91 | break; // what if we did p = p+2; 92 | } 93 | default: 94 | case 0: { 95 | int i = 100, j = 200 ; 96 | if ( test ) 97 | swap_ints(i,j); 98 | else 99 | swap_ints_by_ptr(&i,&j); 100 | printf("i = %d j = %d\n",i,j); 101 | } 102 | 103 | } // end of the switch 104 | 105 | 106 | } 107 | -------------------------------------------------------------------------------- /input_output.c: -------------------------------------------------------------------------------- 1 | #include 2 | void main(){ 3 | // scanf's *syntax* 4 | // scanf(FORMAT-STRING, arg1, arg2, arg3, ...); 5 | // FORMAT-STRING is a string containing conversion specifiers 6 | // %d, %f, %c, %s are examples of conversion specifiers 7 | // %d - for integers 8 | // %f - for floating point numbers 9 | // %c - for characters 10 | // %s - for strings 11 | // There are more, but the above are most common 12 | // Almost always conversion speifiers are separated by one space 13 | // eg. in the format string: "%d %d %f" we have three 14 | // conversion specifiers, indicating we expect two integers followed 15 | // by a float. 16 | // arg1, arg2, arg3, etc are *addresses* of variables to which 17 | // the read input will be stored. Since it is an address 18 | // it usually is a variable name preceded by an "&" sign 19 | // RULE: 20 | // (1) The conversion specifiers must match the list of variables 21 | // in both number and type 22 | // (2) The space is treated in a special way it matches a sequence 23 | // of newlines, blanks and tabs (also together called whitespaces) 24 | int n,m; 25 | float d; 26 | char ch; 27 | // reading integer integers and floats 28 | printf("Input an integer n :"); 29 | scanf("%d",&n); 30 | // reading two ints and a float not the order and type of &n, &m, &d 31 | printf("Input two integers and a real n,m and d :"); 32 | scanf("%d %d %f", &n, &m, &d); 33 | // common errors include writing the format string with commas 34 | // A paritcularly confusing thing may be reading a character: 35 | // To read characters, DO NOT normally use the following 36 | // scanf("%c",&ch); // Quite often it reads a space or a newline 37 | // unintentionally 38 | // Instead the following is OK to read a non-whitespace character 39 | printf("Input a character >"); 40 | scanf(" %c", &ch); // this reads the next non-newline, non-whitespace character into the variable. The extra space makes sure to neglect whitespaces. 41 | 42 | // printf's *syntax* 43 | // printf(FORMAT_STRING, arg1, arg2, arg3, ....) 44 | // FORMAT_STRING is exactly as in the scanf with exactly the same type 45 | // of conversion specifiers 46 | // arg1, arg2, arg3, ... are a list of *values* to be printed 47 | // RULE: The conversion specifiers must match the list of variables 48 | // in both number and type 49 | 50 | printf("%d", n); 51 | printf("%d%d", n, m); // This doesnt appear good. So uses spaces 52 | // in between, for example: 53 | printf("%f %d %d", d, n, m); // This is good, but we often want to 54 | // go to the next line after we print something so use a '\n' character 55 | // in the end of the format string, like 56 | printf("%f %d %d\n", d, n, m); // This is good usually the right thing 57 | // Note that whatever else we put in the format string is also printed 58 | printf("d=%fn=%dm=%d\n", d, n, m); // may print something like 59 | // d=6.200000n=100m=200, but definitely the following is much better: 60 | printf("d=%f n=%d m=%d\n", d, n, m); 61 | 62 | // Normally we put as many spaces as we want. 63 | // Additionally we can use a width specifier for printf conversions: 64 | printf("d=%8.2f n=%4d m=%8d\n", d, n, m); 65 | // See also Section B.12 and B.13 in the appendix K&R text book 2nd Edition 66 | // for a lot more information than we can teach in a course. 67 | // See also 'man 3 printf' and 'man 3 scanf' commands on your ubuntu terminal 68 | // See also the man page for getchar and putchar to know some other common ways to input and output 69 | 70 | } 71 | -------------------------------------------------------------------------------- /CLASS/in_class_programming_exercise_extra.txt: -------------------------------------------------------------------------------- 1 | ------------------ about files --------------------- 2 | 1.Repeat in_class_exercises_4.txt instead of reading student information from user, read it from a file. 3 | Each line contains information for a student. Eg 4 | Sukanya 1 1500 132 -> Sukanya is the name, 1 indicates scholarship holder, 1500 is the scholaship amount 132 is score 5 | Bharath 0 120 -> Bharath is the name, 0 indicates not a scholarship holder, 120 is the score 6 | 7 | 2. Open a file and read the following information per person Name (a string no spaces) and score (an integer), 8 | into two arrays: an array of strings, and an array of integers. Now open a second file and write the same 9 | information that was read, but in reverse order into the the second file. 10 | After the program exits, view the scond file to see the information in reverse order. 11 | 12 | 3. Open a file for appending (mode "a"). Now write 10 strings one on each line at the end of that file. 13 | After the program exits, view the file to see the 10 new strings are appended. 14 | 15 | ------------------- about strings ---------------- 16 | 17 | 4. write a program to read a string and reverse the characters and place it in a new string. Use printf to see the new 18 | string after this reversal. 19 | 20 | 5. Write your own function to take two strings a[] and b[] and copy character by character the characters of a[] to the end of b[]. Then use printf to see the modified string b[]. 21 | 22 | 6. Write your own function to to take a string and a character and test if the character is in the string. If it is in the string return the index (position) of the character found in the string(nly first). If character doesnt exist in the string return -1. 23 | 24 | --------------------- array of pointers --------------------------- 25 | 26 | 7. Read a positive number n 27 | Then read n strings one by one. Assume no string is more that 10 char long. 28 | For each string use malloc to allocate space to hold the given string. Now copy the read string into this 29 | newly malloced space. Collect all these strings in an array of pointers to strings. 30 | Write a function print_strings(a,n) where a[] is the array of pointers to strings and n is the number of 31 | pointers to strings in a[]. This function simply prints all the strings in a[] one each on a separate line. 32 | 33 | ---------------------- pointer arithmetic --------------------------- 34 | 8. If a[] is an array with n integers already filled what does the following scanf do: 35 | scanf("%d",a+4); 36 | 9. What does the following do with the same array a[] of integers: 37 | 38 | for(i=0;i 28 | #include 29 | #define T 0 30 | #define S 1 31 | #define N 2 32 | 33 | #define Gt 0 34 | #define Gr 1 35 | #define Li 2 36 | 37 | #define N_ITEMS 3 38 | #define LEFT_BANK 0 39 | #define RIGHT_BANK 1 40 | 41 | char * item_to_string(int item){ 42 | if( item == 0 ) 43 | return "Gt"; 44 | if( item == 1 ) 45 | return "Gr"; 46 | if( item == 2 ) 47 | return "Li"; 48 | return "**"; 49 | } 50 | int all_items_on(int bank, int bank_contents[][N_ITEMS]){ 51 | // check if all items or on the given bank 52 | int i; 53 | for(i=0;i 2 | #include 3 | 4 | // define types 5 | typedef struct node Node; 6 | 7 | struct node { 8 | int v; 9 | Node * next; 10 | }; 11 | 12 | // define prototypes 13 | Node * make_node(int v); 14 | void show_ll(Node *head); 15 | void show_last(Node *head); 16 | Node * read_ll(); 17 | Node * rev_ll(Node * head); 18 | Node * delete_last(Node *head); 19 | 20 | // define the functions 21 | Node * make_node(int v){ 22 | Node *new=malloc(sizeof(Node)); 23 | new->next=NULL; 24 | new->v=v; 25 | return new; 26 | } 27 | 28 | int length_ll(Node * head){ 29 | int i=0; 30 | for(;head;head=head->next) 31 | i++; 32 | return i; 33 | } 34 | void show_ll(Node *head){ 35 | printf("head:"); 36 | for(;head;head=head->next) printf("-->%d",head->v); 37 | printf("-->NULL"); 38 | printf("\n"); 39 | } 40 | 41 | // define globals and macros to substitute for scanf 42 | // use myscan(v) in place of scanf("%d",&v) wherever you need to 43 | // macros 44 | #define STOP 100 45 | #define myscan(x) x=Globe[globei=(globei+1)%10] 46 | //#define readin(x) scanf("%d",&x) 47 | #define readin(x) myscan(x) 48 | // global variables 49 | int Globe[10]={0,10,20,30,40,50,STOP,70,80,100}; 50 | int globei=0; 51 | 52 | Node * read_ll(){ 53 | int v; 54 | Node * head, *last; 55 | head=last=NULL; 56 | readin(v); 57 | if( v == STOP) 58 | return NULL; 59 | head=last=make_node(v); 60 | readin(v); 61 | while(v!=STOP) { 62 | Node *new=make_node(v); 63 | last->next=new; 64 | last=new; 65 | readin(v); 66 | } 67 | return head; 68 | } 69 | 70 | Node * rev_ll(Node * head){ 71 | Node * new; //pointer to head of new ll 72 | 73 | // case of empty list or one node only 74 | if (!head || !head->next) return head; 75 | 76 | // the common case 77 | // invariant: 78 | // head:: is never changed - it is always head of the original list 79 | // new:: points to the head of the new list - so to be returned 80 | for(new=head, head=head->next, new->next=NULL // initialization 81 | ;head!=NULL // repeat until head==NULL 82 | ;){ 83 | Node *hn=head; // hn: next candidate to be head of new list 84 | head=head->next; // increment head 85 | hn->next=new; // attach new to hn 86 | new=hn; // this is now head of the new list 87 | } 88 | return new; 89 | } 90 | 91 | Node * delete_last(Node *head){ 92 | if ( head == NULL ) return NULL; // case of empty list case 93 | if ( head->next==NULL) { // case of single node list 94 | free(head); 95 | return NULL; 96 | } 97 | // normal case: at least two nodes 98 | // idea is to make p to point to the previous to the last 99 | // then free p->next and set p->next=NULL 100 | Node *p; 101 | for(p=head;p->next->next!=NULL;p=p->next); 102 | 103 | free(p->next); 104 | p->next=NULL; 105 | 106 | return head; 107 | } 108 | 109 | void show_last(Node *head){ 110 | Node *p; 111 | for(p=head;p!=NULL && p->next!=NULL;p=p->next) // Notice short circuit evaluation 112 | ; 113 | if ( p ) 114 | printf("%d ",p->v); 115 | else 116 | printf("**NN**"); 117 | } 118 | 119 | Node * delete_node(Node *head, int v){ 120 | // NULL list 121 | if(head==NULL) return NULL; 122 | // case head matches 123 | if(head->v==v) { 124 | Node *t=head; 125 | head=head->next; 126 | free(t); 127 | return head; 128 | } 129 | // case match is inside the list (not at head) 130 | // make p point to the node previous to the matching node 131 | Node *p; 132 | for(p=head; p->next!=NULL && p->next->v!=v ; p=p->next) // Notice short circuit evaluation 133 | ; 134 | if (p->next!=NULL) { 135 | Node *t=p->next; 136 | p->next=t->next; 137 | free(t); 138 | } 139 | return head; 140 | } 141 | 142 | // main 143 | int main(){ 144 | Node * head=NULL; 145 | head=read_ll(); 146 | printf("length is %d\n",length_ll(head)); 147 | show_ll(head); 148 | head=rev_ll(head); 149 | show_ll(head); 150 | while(head){ 151 | printf("Last is: "); show_last(head); printf("\n"); 152 | head=delete_last(head); 153 | show_ll(head); 154 | } 155 | show_last(head);printf("\n"); 156 | } 157 | -------------------------------------------------------------------------------- /string_simple.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX 20 6 | 7 | #define main1 main 8 | 9 | // function prototypes 10 | int find_length(char s[]); 11 | void exchange_strings(char s[], char t[]); 12 | int compare_and_exchange(char s[], char t[]); 13 | int find_position(char sorted_arr[][20], int arrsize, char newstr[]); 14 | 15 | // demostrate a string as an array 16 | int find_length(char s[]){ 17 | int i; 18 | // Wonder what is the sizeof(s) here? Hmmm... 19 | for(i=0;s[i]!='\0';i++); 20 | return i; 21 | } 22 | 23 | // 24 | // A function to exchange (swap) two character strings 25 | void exchange_strings(char s[], char t[]){ 26 | // This is very similar to swapping of the contents of two variables 27 | // Note that s and t are pointers... 28 | // Note also that it is making a dangerous assumption 29 | // that there is enough space t do the exchange properly 30 | char d[MAX]; // temporary variable used for swapping. 31 | strcpy(d,s); 32 | strcpy(s,t); 33 | strcpy(t,d); 34 | } 35 | 36 | 37 | // A function to exchange two character strings so that s 38 | // is equal to smaller than t 39 | int compare_and_exchange(char s[], char t[]){ 40 | if (strcmp(s,t) > 0 ) 41 | exchange_strings(s,t); 42 | } 43 | 44 | 45 | // A function to receive as a parameter a 46 | // sorted array of strings in increasing order or their dictionary order 47 | // Another parameter is a new string. 48 | // The Aim is to find the position(index) of the new string in the 49 | // array. 50 | int find_position(char sorted_arr[][20], int arrsize, char newstr[]){ 51 | int i; 52 | for (i=0; i= 0 ) // found the position 54 | break; 55 | return i; // note that i is arrsize if newstr is bigger 56 | // than all items in the array 57 | } 58 | 59 | void main1(){ 60 | // Elaborate example shows how a 2 dimensional array is used 61 | // as strings 62 | char s[100][20]; // s is an array of strings, each of max size 20 63 | char newstr[20]; 64 | int i, pos, size; 65 | FILE * fp; 66 | fp = fopen("stringsfile","r"); 67 | if ( fp == NULL ) { 68 | printf("Error opening file, exiting!\n"); 69 | exit(1); 70 | } 71 | // Blow is a little loop that reads all items until it finds an EOF 72 | i=0; 73 | while ( fscanf(fp,"%s",s[i++]) != EOF); // printf("read\n"); 74 | printf("I have read all stuff from the file\n"); 75 | // Note the real size 76 | size=i-1; 77 | // just to indicate that there is no string at s[size]; 78 | s[size][0]='\0'; // not really needed 79 | 80 | // now read a string and insert it in the array, by doing a replacement 81 | // read a new string from the user - from the keyboard 82 | printf("Now give me a new string to insert\n"); 83 | scanf("%s", newstr); 84 | 85 | // Find where this new string should sit in the array 86 | printf("\n\nFinding the position of \"%s\" in the array\n",newstr); 87 | pos = find_position(s,size,newstr); 88 | 89 | // now exchange the string in position pos and this new string 90 | printf("Replacing the first \"%s\" \n",s[pos]); 91 | exchange_strings(s[pos],newstr); 92 | 93 | // now print the new array of strings 94 | printf("\nPrinting new array :\n"); 95 | for ( i=0; i < size; i++) 96 | printf("%s\n",s[i]); 97 | 98 | // now print the removed string 99 | printf("We replaced \"%s\" \n",newstr); 100 | 101 | } 102 | 103 | 104 | // This is to demonstrate pointer vs character array 105 | void main2(){ 106 | char s[]="Hello how are you?"; // This is an array 107 | char *p="Hello how are you?"; // This is a pointer 108 | printf("length is %d\n",find_length(s)); 109 | printf("length is %d\n",find_length("Hello how are you?")); 110 | printf("length is %d\n",find_length(p)); 111 | printf("Size of s is %d\n",(int) sizeof(s)); 112 | printf("Size of p is %d\n",(int) sizeof(p)); 113 | } 114 | 115 | // This is to demonstrate how a string is different from a character array 116 | void main3(){ 117 | char a[6]={'H','e','l','l','o','x'}; 118 | char b[6]={'F','e','l','l','o','\0'}; 119 | char c[6]="Hello"; 120 | char d[10]={'H','e','l','l','o','\0','R','a','m','\0'}; 121 | printf("%s\n",a); 122 | printf("%s : %s : %s : %s \n",a,b,c,d); 123 | printf("%s :%s: %s \n", &d[2], &d[5], &d[6]); 124 | } 125 | -------------------------------------------------------------------------------- /linked_list.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // Definition of the struct for a node of the linked list 4 | struct node { 5 | int val; 6 | struct node * next; 7 | }; 8 | 9 | struct node * new_node(){ 10 | return (struct node *) malloc (sizeof(struct node)); 11 | } 12 | // 13 | // node_delete 14 | // @function: remove a node from a linked list 15 | // @params: head - the head node of the linked list 16 | // val - the val field of the node which must be removed 17 | // @returns: the head of the list after removing the node 18 | // @description:Return value is different from parameter 'head' only when 19 | // the val field of the head matches the param val 20 | // Only the first node with matching val field is removed 21 | struct node * node_delete(struct node * head, int val){ 22 | // @var l: node to match param 'val' starts from the param 'head' 23 | // @var p: node previous to l, starts with NULL value 24 | struct node * l, * p; 25 | 26 | // @loop traverse l through all nodes in the list 27 | // until matching node found OR end of list. 28 | for(l=head, p=NULL; l != NULL && l->val != val ; l=l->next) 29 | p=l ; // remember the previous value 30 | // Now l is NULL if val not in the list. 31 | // else l points to node to remove and p to l's previous node 32 | if ( l != NULL ) { // Now we have a node to remove 33 | if ( p!= NULL) // if p is not NULL, change it next 34 | p->next=l->next; 35 | if ( l == head) // if l is the first node, change head 36 | head = l->next; 37 | free(l); // free up the node that is delted 38 | } 39 | return head; // returns the head to the modified list 40 | } 41 | 42 | 43 | // node_insert 44 | // @function: insert a new node into the linked list 45 | // @params: head - the head node of the linked list 46 | // newval: the value of the new node to insert 47 | // oldval: the value of the node in the linked list before which 48 | // we wish to insert the new node 49 | // @returns: the head of the modified linked list 50 | // @description: Return value is different from param 'head' when 51 | // the head node points to a node matching 'oldval' 52 | // OR when head is itself NULL 53 | // Only the first node matching oldval is considered 54 | struct node * node_insert(struct node * head, int oldval, int newval){ 55 | // @var l - the node to look for matching oldval 56 | // @var p - the node previous to 'l' 57 | struct node * l, * p; 58 | 59 | // @var new - points to the new node to hold 'newval' 60 | struct node * new= new_node(); 61 | new->val=newval; 62 | 63 | // @loop traverse the list looking for node matching oldval 64 | for(l=head, p=NULL; l!= NULL && l->val != oldval ; l=l->next) 65 | p=l; 66 | if (l != NULL ) { // If oldval is found 67 | if ( p != NULL ) { // If it has a valid previous node 68 | p->next=new; 69 | new->next=l; 70 | } else { // if l is the head node itself 71 | new->next=l; 72 | head=new; 73 | } 74 | return head; 75 | } 76 | else { // If no node with oldval exists 77 | if ( p != NULL ) { // It is a non-empty list 78 | p->next=new; 79 | new->next=NULL; 80 | } else { // It is an empty list 81 | new->next=NULL; 82 | head=new; 83 | } 84 | return head; 85 | } 86 | } 87 | 88 | void print_list(struct node *head){ 89 | if (head == NULL) 90 | printf(" "); 91 | for( ; head != NULL ; head=head->next ) 92 | printf("%d ", head->val); 93 | printf("\n"); 94 | } 95 | 96 | struct node * find_node(struct node *head, int val){ 97 | for( ; head !=NULL && head->val != val ; head=head->next ) 98 | ; 99 | return head; 100 | } 101 | 102 | // A simple test function 103 | void main(){ 104 | // lests create an empty linked list 105 | struct node * head = NULL; 106 | 107 | printf("At start: "); print_list(head); // 108 | // lets add a new value 109 | head = node_insert(head, 0, 0); 110 | printf("After 0 added: "); print_list(head); // 0 111 | // lets add stuff in a loop at the end 112 | for(int i=1;i<3;i++) 113 | head=node_insert(head, i, i ); 114 | 115 | printf("After adding 1 and 2: "); print_list(head); // 0 1 2 116 | // now lets add somewhere in the middle 117 | for(int i=3;i<5;i++) 118 | head=node_insert(head, i%2, i); 119 | printf("After adding 3 and 4: "); print_list(head); // 4 0 3 1 2 120 | // expecting list 4 0 3 1 2 121 | 122 | // now lets do some deleting 123 | for(int i=4; i>2; i--) 124 | head=node_delete(head,i); 125 | printf("After deleting 4 and 3: "); print_list(head); // 0 1 2 126 | 127 | for(int i=2;i>0;i--) 128 | head=node_delete(head, i ); 129 | printf("After deleting 2 and 1: "); print_list(head); // 0 130 | 131 | head=node_delete(head, 0); 132 | printf("After 0 deleted: "); print_list(head); // empty 133 | 134 | head=node_delete(head, 0); 135 | printf("After trying to delete 0 again: "); print_list(head); // empty 136 | } 137 | 138 | // Experiment with gcc -fpreprocessed -E ll.c 139 | -------------------------------------------------------------------------------- /SCRIPT/01_intro_crud_compile.md: -------------------------------------------------------------------------------- 1 | 2 | # Computer Command Familiarity 3 | It is important to be familiar with the basic commands of the 4 | computer system you are using in order to be able to 5 | learning programing by doing! 6 | The text below assumes you are using a Linux system like Ubuntu. 7 | 8 | ## Simple Linux Commands 9 | ### Objective: Student to be able to do the following: 10 | * Basic linux commands echo, exit, 11 | ls, pwd, mkdir, cd, 12 | cat, cp, mv, 13 | rm, rmdir 14 | * Make CRUD changes to files 15 | * Use an editor 16 | * For a C program COMPILE, EDIT, RUN 17 | * A bit of history 18 | 19 | ### Notes: 20 | * First class to be boring to those with programming experience already 21 | * Are the students able to 22 | 23 | ## Commands to Create and Edit Files 24 | ### Objective: CRUD files 25 | * Create: copy, rename files 26 | * Read: cat files 27 | * Update: edit files, 28 | * Delete: delete files 29 | * Windows editor to use C/C++ IDE pre insalled, or Notepad++) 30 | * Linux editor to use vi / vim or gedit or atom... 31 | ### Exercise: 32 | * A bunch of programs we will refer to here are available on github 33 | * Go to https://github.com/rbadrinath/FCP 34 | * Now you can download a file like 3np1.c to your 35 | local computer using the following procedure: 36 | * Click on the name of the file 3np1.c 37 | * Now you right click on "Raw" (just above the first line of the program) 38 | and then select the "Save as" menu item 39 | to save the file on your local computer. 40 | * _An alternate is to click the "Copy" icon (Two overlapping squares) and save to ( ie paste into) a local file using an editor like vim or gedit._ 41 | * You will need to download files often so feel comfortable using this procedure 42 | * Take an existing file and copy it to create a new file. cp f1 f2 43 | * Rename the file using mv mv f2 f3 44 | * View the contents of the file using cat. cat f3 45 | * Edit the file using an editor. gedit f3 46 | * Delete the file using rm rm f3 47 | * Repeat this exercise - The teacher will repeatedly ask people to do things 48 | 49 | ## Compile and Execute Programs 50 | ### Objective: Compile and Execute Programs 51 | * Lets start by taking a 'largish' example. Sieve of eratosthenes. 52 | * Notion of writing a program 53 | * Notion of compiling a program 54 | * Notion of execution 55 | ### Exercise: 56 | * Download sieve of eratosthenes.c, compile, execute 57 | * Make small changes just to the output ie edit. 58 | Again compile and execute. 59 | 60 | ## The Edit Compile Execute Loop 61 | * Objective: Be comfortable making small changes to a program, recompile, etc 62 | * lets also use the opportunity to play with the program statements. 63 | 64 | * EXERICISE: Can you download the same program and do what you saw in class? 65 | * eratosthenes.c 66 | * Can you do it for another program ? 67 | 68 | * Exercise: download, compile and execute each of these: 69 | * fact.c 70 | * 3np1.c 71 | * stats.c 72 | 73 | * Exercise: download, compile and execute: 74 | * hello\_world.c and hello\_world.h : A program can be split over files. 75 | * simple\_timing.c and timeutil.c and timeutil.h 76 | 77 | * End Class Exercise: 78 | Can you download the following C program and compile it and 79 | make it run on your PC: https://www.sanfoundry.com/c-program-find-inverse-matrix/ 80 | Now change it a little bit - perhaps change the printf statements a little. 81 | 82 | 83 | (We will look deeper into what is a statement or expression and all that 84 | later on... the next thing.) 85 | 86 | * End of Class Check: 87 | * ANSWER THE FOLLOWING: 88 | * How to / What is the command on this computer to compile a program? 89 | * How to / Why do you need to recompile when you edit a program? 90 | * Try objdump --disassemble on some program a.out to see what 91 | the final executable looks like. 92 | 93 | # History: 94 | Now to some historical perspective of computing 95 | * What lead to the invention of the computer? 96 | * The stored program model of computation 97 | * What problems were solved by early computers? 98 | * Where did the personal computer come in? 99 | * What enabled the growth of computers ? 100 | * The early days of programming. 101 | * The growth of programming languages as the interface to computation. 102 | * Imperative programming languages and the rest. 103 | * Other branches of computer science 104 | * Formal Languages and Automata 105 | * Computer Arch and operating systems 106 | * Data structures and Algorithms 107 | * Discrete mathematics - combinatorics and graph theory 108 | The notion of algorithms : What it means to computer programming 109 | * all of programming is a certian way to implement algorithms 110 | 111 | * END OF CLASS CHECK: 112 | * How is a computer different from a calculator 113 | * What do you think you will learn in this class 114 | --------------------------------------------------------------------------------