├── src ├── prime.c ├── paper ├── practice │ └── primefactors ├── mycube.h ├── using_printf.c ├── addressOperator.c ├── for.c ├── odd.c ├── person.dat ├── operatorprecd2.c ├── infinitewhile.c ├── fgets.c ├── while.c ├── factorial.h ├── fscanf.c ├── include_preprocessor.c ├── quizwhileloop.c ├── OperatorPrecedence.c ├── break.c ├── fputs.c ├── continue.c ├── Struct.c ├── charnstring2.c ├── fgetc.c ├── assert.c ├── cube.c ├── encryption.h ├── array.c ├── display_input_char.c ├── SecondProgram.c ├── remove.c ├── cube_return.c ├── builtin_functions.c ├── staticvariables.c ├── intarrayinput.c ├── pointerarithmetic.c ├── sscanf.c ├── cube_in_header.c ├── pointerInScanf.c ├── myfirstcprog.c ├── passByReference.c ├── charfunctionsx.c ├── strconcat.c ├── typedef.c ├── charnstring3.c ├── hackerrank_pattern.c ├── using_scanf.c ├── sprintf.c ├── pointer.c ├── strpbrk.c ├── factorial.c ├── cube_with_declare.c ├── cube_without_declare.c ├── command_line_args.c ├── intarray.c ├── strrchr.c ├── switchcase.c ├── factorial2.c ├── ThirdProgram.c ├── cube_with_function.c ├── dec2bin.c ├── strstr.c ├── strtol.c ├── strcspn.c ├── strspn.c ├── strtod.c ├── array_input.c ├── arithmeticAssignmentOperators.c ├── 2DArray_input.c ├── terminalQ1.c ├── ternaryoperator.c ├── function.c ├── trycasting.c ├── areaRect.c ├── fibonacci.c ├── 2DArray.c ├── array_loop.c ├── strtoul.c ├── array1.c ├── floatdatatype.c ├── encrypt.c ├── random.c ├── bitrep.c ├── getchar.c ├── Struct2.c ├── escape_sequence.c ├── paper.c ├── strtok.c ├── union.c ├── arithmeticOperators.c ├── relationalOperators.c ├── sizeof.c ├── charnstring.c ├── strcpy_strncpy.c ├── filesearch.c ├── fputc.c ├── var_args.c ├── billcalculator.c ├── strcmp_strncmp.c ├── numbersystemconv.c ├── cursor_positiong.c ├── fgetsputs.c ├── pattern.c ├── arraysPassByReference.c ├── struct2fileread.c ├── simpleif.c ├── mindreader.c ├── functionArgumentArray.c ├── hackerrank.c ├── strchr.c ├── tokenizefile.c ├── charArray.c ├── calculator.c ├── switch-range.c ├── datatypes.c ├── multiDimensionCharArray.c ├── charfunctions2.c ├── dowhile.c ├── charfunctions.c ├── struct2file.c ├── charDataType.c ├── fileio.c ├── linkedlist.c ├── format_specifiers.c ├── LogicalOperators.c ├── charfunctions3.c ├── operators.c ├── switch.c ├── cards.c ├── malloc.c ├── suggestProfession.c └── array_sizeof.c ├── figs ├── logo.jpg ├── dennis.jpeg ├── bellLabs.jpeg ├── flowchart.png ├── conditionals.png ├── cprogrphases.png ├── linked-list.png ├── von-neumann.jpg ├── JohnvonNeumann.gif ├── Harvard_architecture.png └── Von_Neumann_Architecture.png ├── readings └── Reading1.pdf ├── assignments ├── A1-22-26-2.pdf ├── A1-22-26.pdf ├── Spamdetector.zip ├── spamdetector.pdf ├── characterhandling.pdf ├── fibonacci-loop.txt ├── Spamdetector │ ├── obj │ │ └── Debug │ │ │ └── main.o │ ├── bin │ │ └── Debug │ │ │ └── Spamdetector │ ├── Spamdetector.layout │ ├── email.txt │ ├── blacklist.txt │ ├── Spamdetector.cbp │ └── main.c ├── billcalculator.txt ├── A1-22-26.md ├── strongpwd.c ├── pointers.md ├── characterhandling.md ├── spamdetector.md ├── functions.md └── conditionalstatements.md ├── .gitignore ├── markdown ├── charstring.md ├── source2exe.md ├── dataTypesVariables.md ├── unions.md ├── FOPA2Z.md ├── intro2Algo.md ├── LecturesScript.md ├── instructions.md ├── pointers.md ├── stack.md ├── lists.md ├── multiDlists.md ├── ioconstructs.md ├── functions.md ├── testinclude.md ├── CharNStringSupplement.md ├── memory.md ├── staticvariables.md ├── intro2programming.md ├── intro2ModProg.md ├── repetitiveStatements.md ├── lab-manual.md ├── problemSolving.md ├── operators.md ├── conditionalStatements.md └── von-neumann.md └── README.md /src/prime.c: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/paper: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/src/paper -------------------------------------------------------------------------------- /figs/logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/logo.jpg -------------------------------------------------------------------------------- /figs/dennis.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/dennis.jpeg -------------------------------------------------------------------------------- /figs/bellLabs.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/bellLabs.jpeg -------------------------------------------------------------------------------- /figs/flowchart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/flowchart.png -------------------------------------------------------------------------------- /figs/conditionals.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/conditionals.png -------------------------------------------------------------------------------- /figs/cprogrphases.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/cprogrphases.png -------------------------------------------------------------------------------- /figs/linked-list.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/linked-list.png -------------------------------------------------------------------------------- /figs/von-neumann.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/von-neumann.jpg -------------------------------------------------------------------------------- /readings/Reading1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/readings/Reading1.pdf -------------------------------------------------------------------------------- /figs/JohnvonNeumann.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/JohnvonNeumann.gif -------------------------------------------------------------------------------- /assignments/A1-22-26-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/A1-22-26-2.pdf -------------------------------------------------------------------------------- /assignments/A1-22-26.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/A1-22-26.pdf -------------------------------------------------------------------------------- /src/practice/primefactors: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/src/practice/primefactors -------------------------------------------------------------------------------- /assignments/Spamdetector.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/Spamdetector.zip -------------------------------------------------------------------------------- /assignments/spamdetector.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/spamdetector.pdf -------------------------------------------------------------------------------- /figs/Harvard_architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/Harvard_architecture.png -------------------------------------------------------------------------------- /src/mycube.h: -------------------------------------------------------------------------------- 1 | 2 | int mycube(int num) // function definition 3 | { 4 | 5 | return num * num * num ; 6 | } 7 | -------------------------------------------------------------------------------- /assignments/characterhandling.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/characterhandling.pdf -------------------------------------------------------------------------------- /figs/Von_Neumann_Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/figs/Von_Neumann_Architecture.png -------------------------------------------------------------------------------- /assignments/fibonacci-loop.txt: -------------------------------------------------------------------------------- 1 | write a c program that can print first eight numbers of fibanocci sequence, you have to use loop. 2 | -------------------------------------------------------------------------------- /src/using_printf.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) 4 | { 5 | printf("Welcome to C\n"); 6 | return 0; 7 | } 8 | 9 | -------------------------------------------------------------------------------- /assignments/Spamdetector/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/Spamdetector/obj/Debug/main.o -------------------------------------------------------------------------------- /assignments/Spamdetector/bin/Debug/Spamdetector: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/beyond2013/ProgIntro/HEAD/assignments/Spamdetector/bin/Debug/Spamdetector -------------------------------------------------------------------------------- /src/addressOperator.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | char prov_com[5]="BPSC"; 5 | printf("%c", prov_com[6]); 6 | 7 | return 0; 8 | } 9 | 10 | -------------------------------------------------------------------------------- /src/for.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int count; 5 | for(count=0;count < 10; count+=2) 6 | { 7 | printf("%d\n", count); 8 | } 9 | } 10 | 11 | -------------------------------------------------------------------------------- /src/odd.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int count; 5 | for(count=1;count < 10; count+=2) 6 | { 7 | printf("%d\t", count); 8 | } 9 | } 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/person.dat: -------------------------------------------------------------------------------- 1 | ImranAliAbdulBasitJunaidBaberAsfandYar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /pdfs/ 2 | /src/bin 3 | /courseAdmin/ 4 | /sample/ 5 | /submissions/ 6 | .vscode/ 7 | src/.vscode 8 | markdown/*.pdf 9 | src/practice/ 10 | assignments/*.pdf 11 | pastpapers/ 12 | *.sh -------------------------------------------------------------------------------- /src/operatorprecd2.c: -------------------------------------------------------------------------------- 1 | /* 2 | Operator Precedence 3 | */ 4 | #include 5 | int main(void) 6 | { 7 | int a = 3; 8 | printf("%d", a++); 9 | printf("%d", a--); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /src/infinitewhile.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(int argc, char *argv[]) 3 | { 4 | int count = 1; 5 | while(count < 10); 6 | { 7 | printf("%d", count); 8 | } 9 | 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /src/fgets.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | FILE *fp; 4 | char text[300]; 5 | 6 | fp=fopen("test.txt","r"); 7 | printf("%s",fgets(text,250,fp)); 8 | 9 | fclose(fp); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /src/while.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main (void) 3 | { 4 | int i=0; // initialization 5 | while(i<10) // condition 6 | { 7 | printf("%d \n", i); 8 | i = i + 2 ; //i+=2; // increment 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /src/factorial.h: -------------------------------------------------------------------------------- 1 | void factorial(int num) 2 | { 3 | int result =1, counter; 4 | for(counter=1;counter<=num;counter++) 5 | { 6 | result *= counter; 7 | } 8 | printf("factorial of %d is %d ", num, result); 9 | } 10 | -------------------------------------------------------------------------------- /src/fscanf.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | FILE *fp; 5 | char buff[255]; 6 | 7 | fp = fopen("test.txt", "r"); 8 | fscanf(fp, "%s", buff); 9 | printf("%s", buff ); 10 | 11 | return 0; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/include_preprocessor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num; 7 | printf("\nEnter any number \t "); 8 | scanf("%d", &num); 9 | factorial(num); 10 | 11 | return 0; 12 | } 13 | 14 | -------------------------------------------------------------------------------- /src/quizwhileloop.c: -------------------------------------------------------------------------------- 1 | #include 2 | void f(int x, int y) { 3 | while (x < y) { 4 | printf("%d ", y - x); 5 | x = x + 1; 6 | y = y - 1; 7 | } 8 | } 9 | 10 | int main() 11 | { 12 | f(3,6); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /src/OperatorPrecedence.c: -------------------------------------------------------------------------------- 1 | /* 2 | Operator Precedence 3 | */ 4 | #include 5 | int main(void) 6 | { 7 | // What should be the answer of the expression 2 - 3 * 5 8 | printf("\n %d - %d * %d = %d \n", 2, 3, 5, 2-3*5); 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /src/break.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int count; 5 | for(count=0;count < 10; count++) 6 | { 7 | if(count + 2 > 6) 8 | { 9 | printf("%d\n", count); 10 | } 11 | else 12 | { 13 | break; 14 | } 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/fputs.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | FILE *fp; 5 | fp = fopen("test.txt", "w+"); 6 | fprintf(fp, "This is testing for fprintf...\n"); 7 | fputs("This is testing for fputs...\n", fp); 8 | fclose(fp); 9 | return 0; 10 | } 11 | -------------------------------------------------------------------------------- /src/continue.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int count; 5 | for(count=0;count < 10; count++) 6 | { 7 | if(count % 2 == 0) 8 | { 9 | printf("%d\n", count); 10 | } 11 | else 12 | { 13 | continue; 14 | } 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/Struct.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct Student 3 | { 4 | int RollNo; 5 | char Name[10]; 6 | }; 7 | 8 | int main(void) 9 | { 10 | struct Student s1 = {1, "Imran"}; 11 | 12 | printf("%d", s1.RollNo); 13 | printf("%s", s1.Name); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/charnstring2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | //int grade=65; 7 | char grade; 8 | for(grade=1000; grade < 2000; grade++) 9 | { 10 | printf("\n value of grade is %c, int equivalent %d", grade, grade); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/fgetc.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main( ) 3 | { 4 | FILE *fp ; 5 | char ch ; 6 | fp = fopen("test.txt","r") ; 7 | while ( 1 ) 8 | { 9 | ch = fgetc ( fp ) ; 10 | if ( ch == EOF ) 11 | break ; 12 | printf("%c",ch) ; 13 | } 14 | fclose (fp); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/assert.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int a, b; 6 | 7 | printf("Input two integers to divide\n"); 8 | scanf("%d%d", &a, &b); 9 | 10 | assert(b != 0); 11 | 12 | printf("%d/%d = %.2f\n", a, b, a/(float)b); 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /src/cube.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int number=0; 6 | int cube=0; 7 | printf("Enter numeric value \t "); 8 | scanf("%d", &number); 9 | 10 | cube = number * number * number; 11 | 12 | printf("The cube of %d is %d", number , cube); 13 | 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/encryption.h: -------------------------------------------------------------------------------- 1 | void encrypt(char val[]) 2 | { 3 | //long unsigned size = sizeof(val); 4 | for(int i=0; i < 15; i++) 5 | val[i]+=2; // val[i] = val[i] + 2; 6 | } 7 | 8 | void decrypt(char val[]) 9 | { 10 | 11 | // long unsigned size = sizeof(val); 12 | for(int i=0; i < 15; i++) 13 | val[i]-=2; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/array.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int matrix[2][2]={{1, 3}, {6, 7}}; 5 | 6 | int row, col; 7 | 8 | for(row=0;row<2; row++) 9 | { 10 | for(col=0;col < 2; col++) 11 | { 12 | printf("%d ", matrix[row][col]); 13 | } 14 | } 15 | 16 | printf("%d", matrix[5][5]); 17 | return 0; 18 | } 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/display_input_char.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | char input=' '; 6 | 7 | printf("Enter any character: "); 8 | input = getchar(); 9 | 10 | printf("The character you entered is %c\n", input); 11 | printf("Integer equivalent of %c is %d\n", input, input); 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /src/SecondProgram.c: -------------------------------------------------------------------------------- 1 | #include 2 | // written by Imran Ali 3 | /* 4 | Second program of C 5 | Teaching students 6 | how to write c programs 7 | using code blocks 8 | IDE 9 | */ 10 | 11 | int main(void) 12 | { 13 | printf("Sum of %d and %d is %d", 32, 24, 32+24); 14 | return 0; 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/remove.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main () 3 | { 4 | int ret; 5 | char filename[] = "test1.txt"; 6 | ret = remove(filename); 7 | if(ret == 0) 8 | { 9 | printf("\nFile deleted successfully\n"); 10 | } 11 | else 12 | { 13 | printf("\nError: unable to delete the file\n"); 14 | } 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/cube_return.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mycube.h" 3 | 4 | 5 | int main() 6 | { 7 | int number=0; 8 | int cube=0; 9 | printf("Enter numeric value \t "); 10 | scanf("%d", &number); 11 | 12 | printf("The cube of %d is %d", number , mycube(number)); // function call() 13 | 14 | return 0; 15 | } 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/builtin_functions.c: -------------------------------------------------------------------------------- 1 | //C language provides ready to use library functions 2 | // This program shows how to use ceil function defined in math.h file 3 | 4 | #include 5 | #include 6 | 7 | int main(int argc, char *argv[]) 8 | { 9 | printf("The square root of %lf is %lf \n", 4.0, sqrt(4.0)); 10 | return 0; 11 | } 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/staticvariables.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int callCount() 4 | { 5 | static int count = 0; // Static variable to store call count 6 | count++; 7 | return count; 8 | } 9 | 10 | int main() 11 | { 12 | for (int i = 0; i < 5; i++) 13 | { 14 | printf("Function called %d times\n", callCount()); 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /src/intarrayinput.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int marks[5]={46,55,60,75,85}; //declare initialize 5 | int index=0, sum=0; 6 | for(index=0; index < 5; index++) 7 | { 8 | /* printf("\n%d", marks[index]); */ 9 | sum = sum + marks[index]; 10 | } 11 | 12 | printf("\nThe sum of array marks is %d", sum); 13 | return 0; 14 | } 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/pointerarithmetic.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int arr[] = {10, 20, 30, 40, 50}; 5 | int *ptr = arr; 6 | 7 | for (int i = 0; i < 5; i++) { 8 | *ptr +=10; 9 | printf("Value at address %p: %d\n", ptr, *ptr); 10 | ptr++; // Move pointer to the next element 11 | } 12 | 13 | return 0; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/sscanf.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main( void ) 4 | { 5 | char s[] = "31298 87.375"; // initialize array s 6 | int x; // x value to be input 7 | double y; // y value to be input 8 | sscanf( s, "%d%lf", &x, &y ); 9 | printf( "%s\n%s%6d\n%s%8.3f\n", 10 | "The values stored in character array s are:", 11 | "integer:", x, "double:", y ); 12 | } 13 | -------------------------------------------------------------------------------- /src/cube_in_header.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mycube.h" 3 | 4 | 5 | int main() 6 | { 7 | int number=0; 8 | int cube=0; 9 | printf("Enter numeric value \t "); 10 | scanf("%d", &number); 11 | cube = mycube(number); // function call() 12 | 13 | printf("The cube of %d is %d", number ,cube ); 14 | return 0; 15 | } 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/pointerInScanf.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int age; 6 | int *ptr_age; 7 | const char *format = "%d"; 8 | ptr_age = &age; 9 | 10 | printf("\n Enter your age in years\t"); 11 | scanf(format, ptr_age); 12 | 13 | printf("\n You are %d years old", *ptr_age); 14 | printf("\n You are %d years old", age); 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /src/myfirstcprog.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int age=45; 5 | 6 | printf("Name:\t\tImran.\n\n\a\a" ); 7 | printf("Age:\t %d.\n\n", age + 1); 8 | printf("BPS:\t\t%d .\n\n", 18); 9 | age = age + 1; 10 | printf("The value of age is %d", age); 11 | printf("\n"); 12 | printf("My name is Imran, I am %d, and I have %c students in my class", 45, 65); 13 | return 0; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/passByReference.c: -------------------------------------------------------------------------------- 1 | #include 2 | int cubeByReference(int *nPtr); 3 | 4 | int main(void) 5 | { 6 | int number = 5; 7 | printf("\nThe original value of number is %d", number); 8 | cubeByReference(&number); 9 | printf("\nThe new value of number is %d", number); 10 | return 0; 11 | } 12 | void cubeByReference(int *nPtr) 13 | { 14 | *nPtr = *nPtr * *nPtr * *nPtr; 15 | } 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/charfunctionsx.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | printf( "%s\n%s%s\n%s%s\n\n", "According to isdigit: ", 7 | isdigit('8') ? "8 is a " : "8 is not a ", "digit", 8 | isdigit('#') ? "# is a " : "# is not a ", "digit" ); 9 | 10 | /* int result = isdigit('a'); */ 11 | /* printf("\n returned result = %d", result); */ 12 | 13 | return 0; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/strconcat.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | 7 | char str[100]; 8 | char name[]="Imran"; 9 | char lname[]="Ali"; 10 | 11 | printf("str = %s", str); 12 | strcat(str, name); 13 | printf("str = %s", str); 14 | strcat(str, " "); 15 | strcat(str, lname); 16 | printf("str = %s", str); 17 | 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/typedef.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char const *argv[]) 4 | { 5 | typedef int Length; 6 | typedef int Width; 7 | typedef int Area; 8 | Length lengthOfRectangle = 20; 9 | Width widthOfRectangle = 10; 10 | Area area = 0; 11 | area = lengthOfRectangle * widthOfRectangle; 12 | 13 | printf("Area of Rectangle = %d\n", area); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /src/charnstring3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | char grade; 7 | 8 | printf("\n************ OUTPUT *********************"); 9 | printf("\n\n"); 10 | 11 | for(int i=0;i<=255;i++) 12 | { 13 | grade = i; 14 | printf("\n %d => \t %c", grade, grade); 15 | } 16 | 17 | printf("************ ****** *********************\n"); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/hackerrank_pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int n; 6 | size_t col=1, row=1; 7 | printf("Enter a number: "); 8 | scanf("%d", &n); 9 | int max = 2*n -1; 10 | 11 | while(row <= max) 12 | { 13 | while(col <= max) 14 | { 15 | printf("%d ", n); 16 | col++; 17 | } 18 | printf("\n"); 19 | row++; 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /src/using_scanf.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This program shows how to use scanf() function 3 | * 4 | */ 5 | 6 | #include 7 | int main(int argc, char *argv[]) 8 | { 9 | int birth_year=0; 10 | 11 | printf("\nEnter your year of birth in 4 digits [e.g. 1980]: \t"); 12 | scanf("%d", &birth_year); 13 | 14 | printf("\n In 2021 your age is approximately %d years\n", 2021 - birth_year); 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /src/sprintf.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define SIZE 80 3 | int main( void ) 4 | { 5 | char s[ SIZE ]; // create char array 6 | int x; // x value to be input 7 | double y; // y value to be input 8 | puts( "Enter an integer and a double:" ); 9 | scanf( "%d%lf", &x, &y ); 10 | sprintf( s, "integer:%6d\ndouble:%8.2f", x, y ); 11 | printf( "%s\n%s\n", 12 | "The formatted output stored in array s is:", s ); 13 | } 14 | -------------------------------------------------------------------------------- /src/pointer.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int a; 5 | int *aPtr; 6 | 7 | a = 7; 8 | aPtr = &a; 9 | printf("The address of a is %p ", &a); 10 | printf("\n The same can be achieved using pointer %p", aPtr); 11 | printf("\n we have been accessing variable directly using its name"); 12 | printf("\n Indirectly accessing the value of a %d", *aPtr); 13 | printf("\n"); 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/strpbrk.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | const char *string1 = "This is a test"; // initialize char pointer 6 | const char *string2 = "beware"; // initialize char pointer 7 | printf( "%s\"%s\"\n'%c'%s\n\"%s\"\n", 8 | "Of the characters in ", string2, 9 | *strpbrk( string1, string2 ) , 10 | " appears earliest in ", string1 ); 11 | return 0; 12 | } // end main 13 | -------------------------------------------------------------------------------- /src/factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | void factorial(int num); 3 | void factorial(int num) 4 | { 5 | int result =1, counter; 6 | for(counter=1;counter<=num;counter++) 7 | { 8 | result *= counter; 9 | } 10 | printf("factorial of %d is %d ", num, result); 11 | } 12 | int main() 13 | { 14 | int num; 15 | printf("\nEnter any number \t "); 16 | scanf("%d", &num); 17 | factorial(num); 18 | 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/cube_with_declare.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int mycube(int); 4 | 5 | int main() 6 | { 7 | int number=0; 8 | int cube=0; 9 | printf("Enter numeric value \t "); 10 | scanf("%d", &number); 11 | 12 | printf("The cube of %d is %d", number , mycube(number)); // function call() 13 | 14 | return 0; 15 | } 16 | 17 | 18 | int mycube(int num) // function definition 19 | { 20 | 21 | return num * num * num ; 22 | } 23 | -------------------------------------------------------------------------------- /src/cube_without_declare.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int mycube(int num) // function definition 4 | { 5 | 6 | return num * num * num ; 7 | } 8 | 9 | int main() 10 | { 11 | int number=0; 12 | int cube=0; 13 | printf("Enter numeric value \t "); 14 | scanf("%d", &number); 15 | 16 | printf("The cube of %d is %d", number , mycube(number)); // function call() 17 | 18 | return 0; 19 | } 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /assignments/Spamdetector/Spamdetector.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/command_line_args.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char** argv) 4 | { 5 | // The first argument is always the program executable name 6 | // eg. $> program abc uvw xyz 7 | // argv[0] = "program" 8 | // argv[1] = "abc" 9 | // argv[2] = "uvw" 10 | // argv[3] = "xyz" 11 | // argc = 4 12 | 13 | for (int i = 0; i < argc; ++i) 14 | { 15 | printf("%s\n", argv[i]); 16 | } 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /src/intarray.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int marks[5]; //declare 5 | int index=0, sum=0; 6 | for(index=0; index < 5; index++) 7 | { 8 | printf("\nEnter value for marks[%d]\t ", index); 9 | scanf("%d",&marks[index]); 10 | sum = sum + marks[index]; 11 | } 12 | 13 | printf("\nThe sum of array marks is %d", sum); 14 | printf("\nThe average of array marks is %d", sum/5); 15 | return 0; 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/strrchr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize char pointer 6 | const char *string1 = "A zoo has many animals including zebras"; 7 | int c = 'z'; // character to search for 8 | printf( "%s\n%s'%c'%s\"%s\"\n", 9 | "The remainder of string1 beginning with the", 10 | "last occurrence of character ", c, 11 | " is: ", strrchr( string1, c ) ); 12 | return 0; 13 | } // end main 14 | -------------------------------------------------------------------------------- /src/switchcase.c: -------------------------------------------------------------------------------- 1 | #include 2 | int g (int x, int y) { 3 | switch(x - y) { 4 | case 0: 5 | return x; 6 | case 4: 7 | y = y + 1; 8 | break; 9 | case 7: 10 | x = x - 1; 11 | case 9: 12 | return x*y; 13 | case 3: 14 | y = x + 9; 15 | default: 16 | return y - x; 17 | } 18 | return y; 19 | } 20 | 21 | int main() 22 | { 23 | printf("\n g(3,0) evaluates to %d", g(3,0)); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /src/factorial2.c: -------------------------------------------------------------------------------- 1 | #include 2 | int factorial(int num); 3 | int factorial(int num) 4 | { 5 | int result =1, counter; 6 | for(counter=1;counter<=num;counter++) 7 | { 8 | result *= counter; 9 | } 10 | return result; 11 | } 12 | int main() 13 | { 14 | int num,result; 15 | printf("\nEnter any number \t "); 16 | scanf("%d", &num); 17 | result=factorial(num); 18 | printf("factorial of %d is %d ", num, result); 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /src/ThirdProgram.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void){ 4 | 5 | float numb_one, numb_two, result; 6 | numb_one=12; 7 | numb_two=26; 8 | 9 | printf("\n%f + %f = %f", numb_one, numb_two, numb_one + numb_two); 10 | printf("\n%f - %f = %f", numb_one, numb_two, numb_one - numb_two); 11 | printf("\n%f * %f = %f", numb_one, numb_two, numb_one * numb_two); 12 | printf("\n%f / %f = %.2f", numb_two, numb_one, numb_two / numb_one); 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /src/cube_with_function.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int number=0; // global variable -disadvantage visible to all functions within this file 4 | void mycube(); 5 | 6 | int main() 7 | { 8 | int cube=0; 9 | printf("Enter numeric value \t "); 10 | scanf("%d", &number); 11 | 12 | mycube(); 13 | 14 | return 0; 15 | } 16 | 17 | 18 | void mycube() 19 | { 20 | 21 | 22 | printf("The cube of %d is %d", number , number * number * number ); 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/dec2bin.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | int decnumb; 7 | char bin[17]; 8 | 9 | printf("Enter a number\t"); 10 | scanf("%d", &decnumb); 11 | int count = 16; 12 | while(decnumb > 0) 13 | { 14 | /* printf("%d", decnumb%2); */ 15 | bin[count--]=decnumb%2; 16 | decnumb/=2; 17 | } 18 | 19 | for(count = 0; count < 17; count++) 20 | printf("%d", bin[count]); 21 | printf("\n"); 22 | return 0; 23 | } 24 | 25 | -------------------------------------------------------------------------------- /src/strstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | const char *string1 = "abcdefabcdef"; // string to search 6 | const char *string2 = "def"; // string to search for 7 | printf( "%s%s\n%s%s\n\n%s\n%s%s\n", 8 | "string1 = ", string1, "string2 = ", string2, 9 | "The remainder of string1 beginning with the", 10 | "first occurrence of string2 is: ", 11 | strstr( string1, string2 ) ); 12 | return 0; 13 | } // end main 14 | 15 | -------------------------------------------------------------------------------- /src/strtol.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff"; 6 | char * pEnd; 7 | long int li1, li2, li3, li4; 8 | li1 = strtol (szNumbers,&pEnd,10); 9 | li2 = strtol (pEnd,&pEnd,16); 10 | li3 = strtol (pEnd,&pEnd,2); 11 | li4 = strtol (pEnd,NULL,0); 12 | printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4); 13 | return 0; 14 | } 15 | 16 | -------------------------------------------------------------------------------- /src/strcspn.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize two char pointers 6 | const char *string1 = "The value is 3.14159"; 7 | const char *string2 = "1234567890"; 8 | printf( "%s%s\n%s%s\n\n%s\n%s%u\n", 9 | "string1 = ", string1, "string2 = ", string2, 10 | "The length of the initial segment of string1", 11 | "containing no characters from string2 = ", 12 | strcspn( string1, string2 ) ); 13 | return 0; 14 | } // end main 15 | -------------------------------------------------------------------------------- /src/strspn.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize two char pointers 6 | const char *string1 = "The value is 3.14159"; 7 | const char *string2 = "aehi lsTuv"; 8 | printf( "%s%s\n%s%s\n\n%s\n%s%u\n", 9 | "string1 = ", string1, "string2 = ", string2, 10 | "The length of the initial segment of string1", 11 | "containing only characters from string2 = ", 12 | strspn( string1, string2 ) ); 13 | return 0; 14 | } // end main 15 | -------------------------------------------------------------------------------- /src/strtod.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize string pointer 6 | const char *string = "admitted are 51.2"; // initialize string 7 | double d; // variable to hold converted sequence 8 | char *stringPtr; // create char pointer 9 | d = strtod( string, &stringPtr ); 10 | printf( "The string \"%s\" is converted to the\n", string ); 11 | printf( "double value %.2f and the string \"%s\"\n", d, stringPtr ); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /src/array_input.c: -------------------------------------------------------------------------------- 1 | /* 2 | Array: is a data structure. 3 | It allows to store multiple values 4 | of a single type. 5 | Values are stored in contiguous memory 6 | locations. 7 | */ 8 | 9 | #include 10 | 11 | int main(void) 12 | { 13 | int array[10]; 14 | 15 | int count; 16 | 17 | for(count=0;count<10 ; count++) 18 | scanf("%d", &array[count]); 19 | 20 | for(count=0;count<10 ; count++) 21 | printf("%d\n", array[count]); 22 | 23 | 24 | 25 | 26 | return 0; 27 | } 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/arithmeticAssignmentOperators.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int a = 2; 7 | 8 | printf("\n The value of a is %d",a); 9 | a = a + 2; 10 | 11 | printf("\n The value of a is %d",a); 12 | a += 2; 13 | 14 | printf("\n The value of a is %d",a); 15 | printf("\n The value of a-=2 is %d", a-=2); 16 | printf("\n The value of a*=2 is %d", a*=2); 17 | printf("\n The value of a/=2 is %d", a/=2); 18 | printf("\n The value of a%%=2 is %d", a%=2); 19 | 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/2DArray_input.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int matrix[2][2]; 5 | 6 | int row, col; 7 | 8 | printf("\nEnter value for matrix\n"); 9 | 10 | for(row=0;row<2; row++) 11 | { 12 | for(col=0;col < 2; col++) 13 | { 14 | scanf("%d", &matrix[row][col]); 15 | } 16 | } 17 | 18 | 19 | for(row=0;row<2; row++) 20 | { 21 | for(col=0;col < 2; col++) 22 | { 23 | printf("%d\t ", matrix[row][col]); 24 | } 25 | printf("\n"); 26 | } 27 | 28 | 29 | return 0; 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/terminalQ1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | char convert(char blockletter) 5 | { 6 | char convertedletter[0]; 7 | if(tolower(blockletter)) 8 | { 9 | convertedletter=tolower(blockletter); 10 | } 11 | return convertedletter; 12 | } 13 | 14 | int main() 15 | { 16 | char uppercaseletter[0]; 17 | printf("Enter an uppercase letter"); 18 | scanf("%c", &uppercaseletter); 19 | printf("%c in lower case is %c", uppercaseletter, convert(uppercaseletter)); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /src/ternaryoperator.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) 4 | { 5 | 6 | 7 | printf("\n************ OUTPUT *********************"); 8 | 9 | printf("\n\n"); 10 | 11 | printf(2 > 3 ? "condition 2 > 3 evaluates to true" : "condition 2 > 3 evaluates to false"); 12 | 13 | printf("\n"); 14 | 15 | printf(2 < 3 ? "condition 2 < 3 evaluates to true" : "condition 2 < 3 evaluates to false"); 16 | 17 | printf("\n\n"); 18 | 19 | printf("************ ****** *********************\n"); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /src/function.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char input[25]; // global array - not a good practice 4 | 5 | void toUpper(); // declaration of function 6 | 7 | int main() 8 | { 9 | printf("\nEnter your name in small alphabets\t"); 10 | scanf("%s", input); 11 | 12 | toUpper(); // call to function 13 | printf("\n Input now contains: %s", input); 14 | return 0; 15 | } 16 | 17 | void toUpper() // definition of function 18 | { 19 | for (size_t i = 0; i < 25; i++) 20 | { 21 | input[i] -= 32; 22 | } 23 | } -------------------------------------------------------------------------------- /src/trycasting.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char const *argv[]) 4 | { 5 | float input, after_point = 0.0; 6 | int before_point; 7 | printf("Enter a floating point value\t"); 8 | scanf("%f", &input); 9 | before_point = input; 10 | 11 | after_point = input - before_point; 12 | printf("\nafter_point=%f", after_point); 13 | if (after_point >= 0.5) 14 | { 15 | before_point++; 16 | } 17 | printf("\nafter rounding=%d", before_point); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/areaRect.c: -------------------------------------------------------------------------------- 1 | #include 2 | int area(int h, int w); // function declaration 3 | int area(int h, int w) 4 | { 5 | return h*w; 6 | } 7 | 8 | int main(void) 9 | { 10 | int height, width; 11 | int result; 12 | 13 | printf("Enter value for height"); 14 | scanf("%d", &height); 15 | 16 | printf("Enter value for width"); 17 | scanf("%d", &width); 18 | 19 | result = area(height, width); 20 | 21 | printf("The area of rectangle is %d", result); 22 | 23 | return 0; 24 | } 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/fibonacci.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int calculateFibonacci(int n) 4 | { 5 | static int fibPrev = 0, fibNext = 1; // Static variables for Fibonacci sequence 6 | int temp; 7 | 8 | if (n <= 1) 9 | { 10 | return n; 11 | } 12 | 13 | temp = fibNext; 14 | fibNext = fibPrev + fibNext; 15 | fibPrev = temp; 16 | 17 | return fibNext; 18 | } 19 | int main() 20 | { 21 | for (int i = 0; i < 10; i++) 22 | { 23 | printf("%d ", calculateFibonacci(i)); 24 | } 25 | printf("\n"); 26 | return 0; 27 | } -------------------------------------------------------------------------------- /src/2DArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int matrixA[2][2]={{1, 3}, {6, 7}}; 5 | int matrixB[2][2]={{1, 0}, {0, 1}}; 6 | int matrixC[2][2]; 7 | int row, col; 8 | 9 | for(row=0;row<2; row++) 10 | { 11 | for(col=0;col < 2; col++) 12 | { 13 | matrixC[row][col] = matrixA[row][col] + matrixB[row][col]; 14 | } 15 | printf("\n"); 16 | } 17 | 18 | 19 | for(row=0;row<2; row++) 20 | { 21 | for(col=0;col < 2; col++) 22 | { 23 | printf("%d\t ", matrixC[row][col]); 24 | } 25 | printf("\n"); 26 | } 27 | 28 | 29 | return 0; 30 | } 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/array_loop.c: -------------------------------------------------------------------------------- 1 | /* 2 | Array: is a data structure. 3 | It allows to store multiple values 4 | of a single type. 5 | Values are stored in contiguous memory 6 | locations. 7 | */ 8 | 9 | #include 10 | 11 | int main(void) 12 | { 13 | int array[]={12, 5, 7, 9, 13}; 14 | 15 | int sum; 16 | 17 | printf("%d \n", array[0]); 18 | 19 | array[1] = array[1] + 1; 20 | 21 | printf("%d \n", array[1]); 22 | 23 | array[3]= -2; 24 | 25 | 26 | array[0]++; // array[0] += 3; 27 | 28 | array[0] + 3; 29 | 30 | printf("%d\n", array[0]); 31 | 32 | 33 | return 0; 34 | } 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/strtoul.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | const char *string = "1234567abc"; // initialize string pointer 6 | unsigned long int x; // variable to hold converted sequence 7 | char *remainderPtr; // create char pointer 8 | x = strtoul( string, &remainderPtr, 0 ); 9 | printf( "%s\"%s\"\n%s%lu\n%s\"%s\"\n%s%lu\n", 10 | "The original string is ", string, 11 | "The converted value is ", x, 12 | "The remainder of the original string is ", 13 | remainderPtr, 14 | "The converted value minus 567 is ", x - 567 ); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/array1.c: -------------------------------------------------------------------------------- 1 | /* 2 | Array: is a data structure. 3 | It allows to store multiple values 4 | of a single type. 5 | Values are stored in contiguous memory 6 | locations. 7 | */ 8 | 9 | #include 10 | 11 | int main(void) 12 | { 13 | int array[] = {12, 5, 7, 9, 13}; 14 | 15 | int sum; 16 | 17 | printf("%d \n", array[0]); 18 | 19 | array[1] = array[1] + 1; 20 | 21 | printf("%d \n", array[1]); 22 | 23 | printf("Enter a value to replace first element in array: "); 24 | scanf("%d", &array[0]); 25 | printf("\n First element after replacement is %d", array[0]); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /src/floatdatatype.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void){ 4 | 5 | float numb_one, numb_two, result; 6 | 7 | printf("\n Enter value for first number"); 8 | scanf("%f", &numb_one); 9 | 10 | printf("\n Enter value for second number"); 11 | scanf("%f", &numb_two); 12 | 13 | printf("\n%f + %f = %f", numb_one, numb_two, numb_one + numb_two); 14 | printf("\n%f - %f = %f", numb_one, numb_two, numb_one - numb_two); 15 | printf("\n%f * %f = %f", numb_one, numb_two, numb_one * numb_two); 16 | printf("\n%f / %f = %.2f", numb_two, numb_one, numb_two / numb_one); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/encrypt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "encryption.h" 3 | 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | char message[] = "No class today"; 8 | 9 | // int length= 15; 10 | // printf("\n sizeof message = %lu", sizeof(message)); 11 | 12 | printf("\n message before encrypt()"); 13 | printf("\n %s", message); 14 | 15 | 16 | 17 | printf("\n message after encrypt()"); 18 | encrypt(message); 19 | printf("\n %s", message); 20 | 21 | printf("\n message after decrypt()"); 22 | decrypt(message); 23 | printf("\n %s", message); 24 | 25 | 26 | printf("\n"); 27 | 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /src/random.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int main(int argc, char const *argv[]) 5 | { 6 | int randomNumber = 0; 7 | int low = 1, high = 47; // low is inclusive and high is exclusive 8 | srand(time(NULL)); // Seed with current time, used to generate different sequence of random numbers at every execution 9 | for (size_t i = 0; i < 9; i++) 10 | { 11 | randomNumber = low + rand() % (high - low + 1); // generate a random number between 1 and 46 12 | printf("Random number: %d\n", randomNumber); 13 | } 14 | 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/bitrep.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int x; 6 | 7 | printf("\nEnter a number to convert to binary:\t"); 8 | scanf("%d", &x); 9 | 10 | while((x / 2) != 1) // keep printing the remainder of the number with two 11 | { // loop exits when the number becomes exactly equal to 2 12 | printf("%d ", x % 2); 13 | x /= 2; 14 | } 15 | printf("%d ", x % 2); // since the number can still be divided once with 2 16 | printf("%d ", 1); // the bit string output by this method is the reverse binary bit representation 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/getchar.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define SIZE 80 3 | int main( void ) 4 | { 5 | int c; // variable to hold character input by user 6 | char sentence[ SIZE ]; // create char array 7 | int i = 0; // initialize counter i 8 | // prompt user to enter line of text 9 | puts( "Enter a line of text:" ); 10 | // use getchar to read each character 11 | while ( i < SIZE - 1 && ( c = getchar() ) != '\n' ) { 12 | sentence[ i++ ] = c; 13 | } // end while 14 | sentence[ i ] = '\0'; // terminate string 15 | // use puts to display sentence 16 | puts( "\nThe line entered was:" ); 17 | puts( sentence ); 18 | } // end main 19 | -------------------------------------------------------------------------------- /src/Struct2.c: -------------------------------------------------------------------------------- 1 | #include 2 | struct Student 3 | { 4 | int RollNo; 5 | char Name[10]; 6 | }; 7 | 8 | int main (void) 9 | { 10 | 11 | struct Student s[2]; 12 | int counter; 13 | 14 | for(counter=0;counter<2;counter++) 15 | { 16 | printf("\n Enter Value for RollNo\t"); 17 | scanf("%d", &s[counter].RollNo); 18 | printf("\n Enter Value for Name \t"); 19 | scanf("%s", s[counter].Name); 20 | } 21 | 22 | for(counter=0;counter<2;counter++) 23 | { 24 | printf("\n RollNo = %d \t", s[counter].RollNo); 25 | printf("\n Name = %s \t", s[counter].Name); 26 | } 27 | 28 | 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/escape_sequence.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * This program displays a table of escape sequence 5 | * using escape sequences. 6 | */ 7 | 8 | int main(int argc, char *argv[]) 9 | { 10 | printf("\n============================================="); 11 | printf("\n Escape Sequence | \t Description \n"); 12 | printf("=============================================\n"); 13 | printf(" \\n \t\t | \t New line \n"); 14 | printf(" \\r \t\t | \t Carriage return \n"); 15 | printf(" \\t \t\t | \t tab \n"); 16 | printf("=============================================\n"); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/paper.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | float calculate_gpa(int[2][5], int); 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | int scores[2][5] = {{60, 70, 75, 80, 55}, {3, 3, 3, 3, 4}}; 8 | 9 | float result = calculate_gpa(scores, 5); 10 | printf("result = %f", result); 11 | 12 | return 0; 13 | } 14 | 15 | float calculate_gpa(int array[2][5], int size) 16 | { 17 | float result = 0.0; 18 | int quotient = 0; 19 | for (int i = 0; i < size; i++) 20 | { 21 | result += array[0][i] * array[1][i]; 22 | quotient += array[1][i]; 23 | } 24 | return result / quotient; 25 | } -------------------------------------------------------------------------------- /src/strtok.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize array string 6 | char string[] = "This is a sentence with 7 tokens"; 7 | char *tokenPtr; // create char pointer 8 | printf( "%s\n%s\n\n%s\n", 9 | "The string to be tokenized is:", string, 10 | "The tokens are:" ); 11 | tokenPtr = strtok( string, " " ); // begin tokenizing sentence 12 | // continue tokenizing sentence until tokenPtr becomes NULL 13 | while ( tokenPtr != NULL ) { 14 | printf( "%s\n", tokenPtr ); 15 | tokenPtr = strtok( NULL, " " ); // get next token 16 | } // end while 17 | return 0; 18 | } // end main 19 | -------------------------------------------------------------------------------- /assignments/Spamdetector/email.txt: -------------------------------------------------------------------------------- 1 | Data recovery, password recovery, video conversion, and PDF conversion spam. Has various other names such as SmartKey. The scale of the spam and the fact that multiple malware programs have been found on these IP addresses suggest that the conduct originates from a criminal organization. 2 | 3 | IP addresses: 4 | 5 | 54.201.153.20 6 | 184.168.229.155 7 | 54.69.177.37 8 | 67.20.74.163 9 | 50.87.141.154 10 | 11 | Domains: 12 | 13 | advancedpdfconverter.com www.tenorshare.com 14 | androiddatarecoverypro.com any-data-recovery.com 15 | card-data-recovery.com excel-password-recovery.net 16 | fix-computer.net 17 | -------------------------------------------------------------------------------- /src/union.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | union number 4 | { 5 | int x; 6 | double y; 7 | }; 8 | 9 | int main(int argc, char const *argv[]) 10 | { 11 | union number value; 12 | printf("\nsize of value = % lu", sizeof(value)); 13 | value.x = 100; 14 | printf("\n Integer member has the value:%d and \n double member has the value:%f ", 15 | value.x, value.y); 16 | printf("\nsize of value = % lu", sizeof(value)); 17 | value.y = 100.0; 18 | 19 | printf("\n Integer member has the value:%d and \n double member has the value:%f ", 20 | value.x, value.y); 21 | printf("\nsize of value = % lu", sizeof(value)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /src/arithmeticOperators.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int num1, num2; // variable declaration 7 | num1 = 20, num2 = 3; // initialization 8 | 9 | printf("\n %d + %d = %d and %d + %d = %d",num1,num2,num1 + num2 ,num2,num1,num2 + num1); 10 | printf("\n %d - %d = %d and %d - %d = %d",num1,num2,num1 - num2 ,num2,num1,num2 - num1); 11 | printf("\n %d * %d = %d and %d * %d = %d",num1,num2,num1 * num2 ,num2,num1,num2 * num1); 12 | printf("\n %d / %d = %d and %d / %d = %d",num1,num2,num1 / num2 ,num2,num1,num2 / num1); 13 | printf("\n %d %% %d = %d and %d %% %d = %d",num1,num2,num1 % num2 ,num2,num1,num2 % num1); 14 | } 15 | -------------------------------------------------------------------------------- /src/relationalOperators.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int a = 3, b=2; 7 | 8 | printf("\n If a = 3 then: "); 9 | printf(" \n The expression a == 3 will result in %d", a == 3); 10 | printf(" \n The expression a < 3 will result in %d", a < 3); 11 | printf(" \n The expression a > 3 will result in %d", a > 3); 12 | printf(" \n The expression a <= 3 will result in %d", a <= 3); 13 | printf(" \n The expression a >= 3 will result in %d", a >= 3); 14 | 15 | printf(" \n The expression a - 1 >= b will result in %d", a - 1 >= b); 16 | printf(" \n The expression a == b + 1 will result in %d", a == b+1); 17 | } 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/sizeof.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | printf("sizeof char = %u bytes\n", sizeof(char)); 7 | printf("sizeof short = %u bytes\n", sizeof(short)); 8 | printf("sizeof int = %u bytes\n", sizeof(int)); 9 | printf("sizeof long = %u bytes\n", sizeof(long)); 10 | printf("sizeof long long = %u bytes\n", sizeof(long long)); 11 | printf("sizeof float = %u bytes\n", sizeof(float)); 12 | printf("sizeof double = %u bytes\n", sizeof(double)); 13 | printf("sizeof long double = %u bytes\n", sizeof(long double)); 14 | printf("sizeof int[20] = %u bytes\n", sizeof(int[20])); 15 | printf("sizeof int* = %u bytes\n", sizeof(int*)); 16 | system("PAUSE"); 17 | } 18 | -------------------------------------------------------------------------------- /src/charnstring.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | char grade = 'A'; 7 | 8 | printf("\n************ OUTPUT *********************"); 9 | printf("\n\n"); 10 | 11 | printf("\n Character stored in grade variable is \t %c", grade); 12 | 13 | printf("\n int value represented by char variable grade is \t %d", grade); 14 | 15 | grade = 66; 16 | 17 | printf("\n new Character value of grade variable is \t %c", grade); 18 | 19 | grade++; 20 | 21 | 22 | printf("\n Character value of grade variable after increment \t %c", grade); 23 | 24 | printf("\n\n"); 25 | 26 | printf("************ ****** *********************\n"); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /src/strcpy_strncpy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define SIZE1 25 4 | #define SIZE2 15 5 | int main( void ) 6 | { 7 | char x[] = "Happy Birthday to You"; // initialize char array x 8 | char y[ SIZE1 ]; // create char array y 9 | char z[ SIZE2 ]; // create char array z 10 | // copy 11 | printf( 12 | "The 13 | "The 14 | contents of x into y 15 | "%s%s\n%s%s\n", 16 | string in array x is: ", x, 17 | string in array y is: ", strcpy( y, x ) ); 18 | // copy first 14 characters of x into z. Does not copy null 19 | // character 20 | strncpy( z, x, SIZE2 - 1 ); 21 | z[ SIZE2 - 1 ] = '\0'; // terminate string in z 22 | printf( "The string in array z is: %s\n", z ); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /assignments/Spamdetector/blacklist.txt: -------------------------------------------------------------------------------- 1 | tenorshare.com 2 | advancedpdfconverter.com 3 | androiddatarecoverypro.com 4 | any-data-recovery.com 5 | card-data-recovery.com 6 | excel-password-recovery.net 7 | fix-computer.net 8 | lost-password.net 9 | lostwindowspassword.com 10 | macvideoconverterpro.com 11 | password-master.net 12 | photorecovery-formac.com 13 | powerpointpasswordrecovery.net 14 | rarpasswordunlocker.net 15 | recover-windows-password.net 16 | recoverlostpassword.com 17 | sqlpassword-recovery.com 18 | windows7-password-reset.net 19 | windowspasswordcracker.com 20 | windowspasswordrecovery.net 21 | windowspasswordreset.net 22 | windowspasswordsrecovery.com 23 | wordpassword-recovery.com 24 | youtubedownloaderconverter.net 25 | -------------------------------------------------------------------------------- /src/filesearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | 6 | FILE *fp; 7 | int line_num = 1; 8 | int find_result = 0; 9 | char temp[512]; 10 | char str[]="tenorshare.com" ; 11 | 12 | if((fp = fopen("email.txt", "r")) == NULL) 13 | { 14 | return(-1); 15 | } 16 | 17 | while(fgets(temp, 512, fp) != NULL) { 18 | if((strstr(temp, str)) != NULL) { 19 | printf("A match found on line: %d\n", line_num); 20 | printf("\n%s\n", temp); 21 | find_result++; 22 | } 23 | line_num++; 24 | } 25 | 26 | if(find_result == 0) { 27 | printf("\nSorry, couldn't find a match.\n"); 28 | } 29 | 30 | //Close the file if still open. 31 | if(fp) { 32 | fclose(fp); 33 | } 34 | } // end main 35 | -------------------------------------------------------------------------------- /src/fputc.c: -------------------------------------------------------------------------------- 1 | // C program to illustate fputc() function 2 | #include 3 | int main() 4 | { 5 | int i = 0; 6 | char filename[]="output.txt"; 7 | char filemode[]="w"; 8 | 9 | FILE *fp = fopen(filename,filemode); 10 | 11 | // Return if could not open file 12 | if (fp == NULL) 13 | return 0; 14 | 15 | char string[] = "Department of Computer Science & Information Technology "; 16 | 17 | for (i = 0; string[i]!='\0'; i++) 18 | 19 | // Input string into the file 20 | // single character at a time 21 | fputc(string[i], fp); 22 | 23 | fclose(fp); 24 | 25 | printf("\n string successfully written to file %s \n", filename); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /markdown/charstring.md: -------------------------------------------------------------------------------- 1 | ```{#char .c .numberLines} 2 | #include 3 | #include 4 | 5 | int main(void) 6 | { 7 | char grade = 'A'; 8 | 9 | printf("\n************ OUTPUT *********************"); 10 | printf("\n\n"); 11 | 12 | printf("\n Character stored in grade variable is \t %c", grade); 13 | 14 | printf("\n int value represented by char variable grade is \t %d", grade); 15 | 16 | grade = 66; 17 | 18 | printf("\n new Character value of grade variable is \t %c", grade); 19 | 20 | grade++; 21 | 22 | 23 | printf("\n Character value of grade variable after increment \t %c", grade); 24 | 25 | printf("\n\n"); 26 | 27 | printf("************ ****** *********************\n"); 28 | 29 | return 0; 30 | } 31 | ``` 32 | -------------------------------------------------------------------------------- /src/var_args.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for system() 4 | 5 | int add_nums(int count, ...) 6 | { 7 | int result = 0; 8 | va_list args; // list of the args passed to ... 9 | va_start(args, count); // start the list for args after the count argument 10 | for (int i = 0; i < count; ++i) { 11 | int value = va_arg(args, int); // get the next argument as an int (the datatype can be anything eg. char, float) 12 | result += value; 13 | } 14 | va_end(args); // clear the list of args 15 | return result; 16 | } 17 | 18 | int main() 19 | { 20 | int sum = add_nums(4, 25, 25, 50, 50); 21 | printf("%d\n", sum); 22 | system("PAUSE"); 23 | return 0; 24 | } -------------------------------------------------------------------------------- /src/billcalculator.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int amount = 0, units_consumed = 0; 6 | 7 | printf("Enter amount of units consumed\t"); 8 | scanf("%d", &units_consumed); 9 | 10 | if (units_consumed > 0 && units_consumed <= 100) 11 | { 12 | amount = 3 * units_consumed; 13 | } 14 | else if (units_consumed > 100 && units_consumed <= 200) 15 | { 16 | amount = 3 * 100 + 4 * (units_consumed - 100); 17 | } 18 | else if (units_consumed > 200 && units_consumed <= 300) 19 | { 20 | units_consumed -= 100; 21 | amount += 3 * 100; 22 | units_consumed -= 100; 23 | amount += 4 * 100; 24 | amount += units_consumed * 5; 25 | } 26 | 27 | printf("\nYou have to pay %d Rupees\n", amount); 28 | return 1; 29 | } 30 | -------------------------------------------------------------------------------- /src/strcmp_strncmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | const char *s1 = "Happy New Year"; // initialize char pointer 6 | const char *s2 = "Happy New Year"; // initialize char pointer 7 | const char *s3 = "Happy Holidays"; // initialize char pointer 8 | printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n", 9 | "s1 = ", s1, "s2 = ", s2, "s3 = ", s3, 10 | "strcmp(s1, s2) = ", strcmp( s1, s2 ) , 11 | "strcmp(s1, s3) = ", strcmp( s1, s3 ) , 12 | "strcmp(s3, s1) = ", strcmp( s3, s1 ) ); 13 | printf("%s%2d\n%s%2d\n%s%2d\n", 14 | "strncmp(s1, s3, 6) = ", strncmp( s1, s3, 6 ) , 15 | "strncmp(s1, s3, 7) = ", strncmp( s1, s3, 7 ) , 16 | "strncmp(s3, s1, 7) = ", strncmp( s3, s1, 7 ) ); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/numbersystemconv.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int input,number,remainder; 6 | int binarynum=0, i = 1, octalnum=0; 7 | printf("\n Enter a number to convert to binary\t"); 8 | scanf("%d", &input); 9 | 10 | 11 | number = input; 12 | while(number > 0) 13 | { 14 | remainder = number % 2; 15 | number/=2; 16 | binarynum += remainder * i; 17 | i*=10; 18 | } 19 | 20 | printf("\n Binary Equivalent of %d is %d\n", input, binarynum); 21 | 22 | i = 1; 23 | number = input; 24 | while(number > 0) 25 | { 26 | remainder = number % 8; 27 | number/=8; 28 | octalnum += remainder * i; 29 | i*=10; 30 | } 31 | 32 | printf("\n Octal Equivalent of %d is %d\n", input, octalnum); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/cursor_positiong.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define clear() printf("\033[H\033[J") 4 | #define gotoxy(x,y) printf("\033[%d;%dH", (y), (x)) 5 | #define moveup() printf("\033[1A"); // Move up 1 lines; 6 | #define movedown() printf("\033[1B"); // Move down 1 lines; 7 | #define moveright() printf("\033[1C"); // Move right 1 column; 8 | #define moveleft() printf("\033[1D"); // Move left X column; 9 | // 10 | int main(void) 11 | { 12 | int number; 13 | 14 | clear(); 15 | printf( 16 | "Enter your number in the box below\n" 17 | "+-----------------+\n" 18 | "| |\n" 19 | "+-----------------+\n" 20 | ); 21 | gotoxy(10, 3); 22 | scanf("%d", &number); 23 | printf("\n"); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /src/fgetsputs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define SIZE 80 3 | void reverse( const char * const sPtr ); // prototype 4 | int main( void ) 5 | { 6 | char sentence[ SIZE ]; // create char array 7 | puts( "Enter a line of text:" ); 8 | // use fgets to read line of text 9 | fgets( sentence, SIZE, stdin ); 10 | puts( "\nThe line printed backward is:" ); 11 | reverse( sentence ); 12 | } // end main 13 | 14 | // recursively outputs characters in string in reverse order 15 | void reverse( const char * const sPtr ) 16 | { 17 | // if end of the string 18 | if ( '\0' == sPtr[ 0 ] ) { // base case 19 | return; 20 | } // end if 21 | else { // if not end of the string 22 | reverse( &sPtr[ 1 ] ); // recursion step 23 | putchar( sPtr[ 0 ] ); // use putchar to display character 24 | } // end else 25 | } 26 | -------------------------------------------------------------------------------- /src/pattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int n, oldn; 6 | int lower=0, upper=0; 7 | int col=1, row=1; 8 | printf("Enter a number: "); 9 | scanf("%d", &n); 10 | int max = 2*n -1; 11 | 12 | for(row=1;row <= max; row++) 13 | { 14 | lower = row + 1; 15 | upper = max - row; 16 | if(lower <= max -1) 17 | { 18 | if(lower <= upper) 19 | { 20 | // printf("lower = %d, upper = %d: ", lower, upper); 21 | for(int k = lower; k <= upper; k++) 22 | { 23 | printf("%d ", n-1); 24 | } 25 | n--; 26 | } 27 | else if(lower > upper) 28 | { 29 | for(int k = lower; k >= upper; k--) 30 | { 31 | printf("%d ", n+1); 32 | } 33 | n++; 34 | } 35 | } 36 | printf("\n"); 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /assignments/billcalculator.txt: -------------------------------------------------------------------------------- 1 | Consuming more utility such as Gas and Electricity in developing countries results in higher bills. 2 | 3 | Suppose a utility provider charges a consumer with the following rates: 4 | 1. 3 Rupees per unit if the consumption is between 0 to 100 units 5 | 2. 4 Rupees for every unit consumed between 101 to 200 units 6 | 3. 5 Rupees for every units consumed between 201 to 300 units. 7 | 8 | Write a c program which asks the consumer to enter the number of units consumed. and calculate the amount of bill. 9 | 10 | e.g. 11 | 12 | 1. 13 | Enter the amount of units consumed 100 14 | You have to pay 300 Rupees 15 | 16 | 2. 17 | Enter the amount of units consumed 150 18 | You have to pay 500 Rupees 19 | 20 | 3. 21 | Enter the amount of units consumed 250 22 | You have to pay 950 Rupees 23 | -------------------------------------------------------------------------------- /src/arraysPassByReference.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Function to modify the array 4 | void modifyArray(int arr[], int size) 5 | { 6 | for (int i = 0; i < size; i++) 7 | { 8 | arr[i] = arr[i] * 2; // Double each element in the array 9 | } 10 | } 11 | 12 | int main() 13 | { 14 | int myArray[] = {1, 2, 3, 4, 5}; 15 | int size = sizeof(myArray) / sizeof(myArray[0]); 16 | 17 | printf("Original array: "); 18 | for (int i = 0; i < size; i++) 19 | { 20 | printf("%d ", myArray[i]); 21 | } 22 | printf("\n"); 23 | 24 | // Passing the array to the function 25 | modifyArray(myArray, size); 26 | 27 | printf("Modified array: "); 28 | for (int i = 0; i < size; i++) 29 | { 30 | printf("%d ", myArray[i]); 31 | } 32 | printf("\n"); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /src/struct2fileread.c: -------------------------------------------------------------------------------- 1 | // C program for reading 2 | // struct from a file 3 | #include 4 | #include 5 | 6 | // struct person with 3 fields 7 | struct person 8 | { 9 | int id; 10 | char fname[20]; 11 | char lname[20]; 12 | }; 13 | 14 | // Driver program 15 | int main () 16 | { 17 | FILE *infile; 18 | struct person input; 19 | 20 | // Open person.dat for reading 21 | infile = fopen ("person.dat", "r"); 22 | if (infile == NULL) 23 | { 24 | fprintf(stderr, "\nError opening file\n"); 25 | exit (1); 26 | } 27 | 28 | // read file contents till end of file 29 | while(fread(&input, sizeof(struct person), 1, infile)) 30 | printf ("id = %d name = %s %s\n", input.id, 31 | input.fname, input.lname); 32 | 33 | // close file 34 | fclose (infile); 35 | 36 | return 0; 37 | } 38 | 39 | -------------------------------------------------------------------------------- /src/simpleif.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | int num1, num2; 6 | 7 | puts("Enter 2 numbers to find relationship between them"); 8 | scanf("%d%d", &num1, &num2); 9 | 10 | if(num1 == num2) 11 | { 12 | printf("\n %d is equal to %d", num1, num2); 13 | } 14 | 15 | if(num1 != num2) 16 | { 17 | printf("\n %d is not equal to %d", num1, num2); 18 | } 19 | 20 | if(num1 < num2) 21 | { 22 | printf("\n %d is less than %d", num1, num2); 23 | } 24 | 25 | if(num1 > num2) 26 | { 27 | printf("\n %d is greater than %d", num1, num2); 28 | } 29 | 30 | if(num1 <= num2) 31 | { 32 | printf("\n %d is less than OR equal to %d", num1, num2); 33 | } 34 | 35 | if(num1 >= num2) 36 | { 37 | printf("\n %d is greater than OR equal to %d", num1, num2); 38 | } 39 | 40 | printf("\n"); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /src/mindreader.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | setlocale(LC_ALL, ""); 8 | 9 | wchar_t symbols[] = { 10 | L'\u2660', L'\u2663', L'\u2665', L'\u2666', L'\u2667', // Suits 11 | L'\u2605', L'\u260E', L'\u2714', L'\u2716', L'\u2718', // Stars and Checkmarks 12 | L'\u263A', L'\u263B', L'\u25BC', L'\u25B2', L'\u25E6', // Arrows 13 | L'\u2691', L'\u269C', L'\u26A1', L'\u26BD', L'\u26C4' // Musical symbols 14 | }; 15 | 16 | for (int i = 0; i < sizeof(symbols) / sizeof(symbols[0]); i++) { 17 | wprintf(L"Symbol %d: %lc\n", i + 1, symbols[i]); 18 | } 19 | 20 | 21 | /* char symbol[100]; 22 | 23 | for(int i=32; i<=126; i++) 24 | { 25 | printf("%c\t",i); 26 | if(i%10==0) printf("\n"); 27 | } 28 | */ 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /src/functionArgumentArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Passing several values to a function can be efficiently achieved using arrays 4 | 5 | int sumArray(int, int[]); 6 | 7 | int main(int argc, char *argv[]) 8 | { 9 | int array[6]; //= {23, 32, 12, 44, 45, 67}; 10 | 11 | printf("Enter 6 values \t "); 12 | for (size_t count = 0; count <= 5; count++) 13 | scanf("%d", &array[count]); 14 | 15 | printf("The sum of array :\t"); 16 | 17 | for (size_t count = 0; count <= 5; count++) 18 | printf("%d \t", array[count]); 19 | 20 | printf(" is %d \n", sumArray(6, array)); 21 | 22 | return 0; 23 | } 24 | 25 | int sumArray(int size, int inputarray[]) 26 | { 27 | int sum = 0; 28 | 29 | for (size_t count = 0; count < size; count++) 30 | ++inputarray[count]; 31 | 32 | for (size_t count = 0; count < size; count++) 33 | sum += inputarray[count]; 34 | return sum; 35 | } 36 | -------------------------------------------------------------------------------- /src/hackerrank.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | //Complete the following function. 6 | 7 | 8 | void calculate_the_maximum(int n, int k) { 9 | //Write your code here. 10 | int _and=0, _or=0, _xor=0; 11 | int m_and=0, m_or=0, m_xor=0; 12 | for(int i=1; i < n;i++){ 13 | for(int j=i+1; j <= n; j++) 14 | { 15 | 16 | _and = i & j; 17 | _or = i | j; 18 | _xor = i ^ j; 19 | if(_and < k && _and > m_and) m_and = _and; 20 | if(_or < k && _or > m_or) m_or = _or; 21 | if(_xor < k && _xor > m_xor) m_xor = _xor; 22 | //printf("i=%d j=%d\t i & j = %d \t i | j = %d \t i ^ j = %d \n", i,j, m_and, m_or, m_xor); 23 | } 24 | } 25 | printf("%d\n%d\n%d", m_and,m_or,m_xor); 26 | } 27 | 28 | int main() { 29 | int n, k; 30 | 31 | scanf("%d %d", &n, &k); 32 | calculate_the_maximum(n, k); 33 | 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/strchr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | const char *string = "This is a test"; // initialize char pointer 6 | char character1 = 'a'; // initialize character1 7 | char character2 = 'z'; // initialize character2 8 | // if character1 was found in string 9 | if ( strchr( string, character1 ) != NULL ) { 10 | printf( "\'%c\' was found in \"%s\".\n", 11 | character1, string ); 12 | } // end if 13 | else { // if character1 was not found 14 | printf( "\'%c\' was not found in \"%s\".\n", 15 | character1, string ); 16 | } // end else 17 | // if character2 was found in string 18 | if ( strchr( string, character2 ) != NULL ) { 19 | printf( "\'%c\' was found in \"%s\".\n", 20 | character2, string ); 21 | } // end if 22 | else { // if character2 was not found 23 | printf( "\'%c\' was not found in \"%s\".\n", 24 | character2, string ); 25 | } // end else 26 | return 0; 27 | } // end main 28 | -------------------------------------------------------------------------------- /src/tokenizefile.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | // initialize array string 6 | //char string[] = "This is a sentence with 7 tokens"; 7 | FILE *fp; 8 | 9 | //char *tokenPtr; // create char pointer 10 | char word[60]; 11 | char *ret; 12 | fp = fopen("sample.txt", "r"); 13 | 14 | if(fp!=NULL) 15 | { 16 | puts("Successfully opened file for reading"); 17 | ret = fgets(word, 60,fp); 18 | 19 | if(ret!= NULL){ 20 | puts(word); 21 | } 22 | 23 | } 24 | 25 | /* 26 | printf( "%s\n%s\n\n%s\n", 27 | "The string to be tokenized is:", string, 28 | "The tokens are:" ); 29 | tokenPtr = strtok( string, " " ); // begin tokenizing sentence 30 | // continue tokenizing sentence until tokenPtr becomes NULL 31 | while ( tokenPtr != NULL ) { 32 | printf( "%s\n", tokenPtr ); 33 | tokenPtr = strtok( NULL, " " ); // get next token 34 | } // end while 35 | */ 36 | 37 | fclose(fp); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /src/charArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | char vowels[] = {'a', 'e', 'i', 'o', 'u'}; 5 | const char *cname = "BSIT-2020-2024"; 6 | char myname[5] = {'I', 'M', 'R', 'A', 'N'}; 7 | 8 | // char student[15]; 9 | // printf("%s\n", vowels); 10 | // printf("vowel[6]= %c\n", vowels[6]); // 'I' 11 | 12 | for (int i = 0; i < 5; i++) 13 | { 14 | printf("%c\t", ++vowels[i]); 15 | } 16 | 17 | // printf("%s\n", cname); 18 | // printf("%s\n", myname); 19 | // printf("\n Enter name of your student: "); 20 | // scanf("%s", student); 21 | // printf("\nThe name of your student is %s", student); 22 | // printf("\nYour student's name starts with %c", student[0]); 23 | printf("\n"); 24 | 25 | // char name_in_small[25]; 26 | // name_in_small[0] = name_in_small[0] - 32; 27 | // name_in_small[1] = name_in_small[1] - 32; 28 | // name_in_small[2] = name_in_small[2] - 32; 29 | 30 | /*for (size_t i = 0; i < 25; i++) 31 | { 32 | 33 | name_in_small[i] -= 32; 34 | } 35 | */ 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /src/calculator.c: -------------------------------------------------------------------------------- 1 | Write a c program which can perform currency coversion 2 | 3 | Input in PKR, 4 | Convert into USD, POUND, UAE 5 | 6 | 1 usd = 278.43 PKR 1 Pound = 354.18 PKR 1 UAE = 75.82 PKR 7 | 8 | #include // pre-processor directive 9 | 10 | int 11 | main() 12 | { 13 | 14 | int number1, number2; 15 | 16 | printf("\n Enter a number\t"); // \n and \t are escape sequence 17 | // user input 18 | scanf("%d", &number1); // %d is format specifier for integers, & is address operator 19 | 20 | printf("\n Enter another number\t"); 21 | scanf("%d", &number2); 22 | 23 | printf("%d + %d = %d\n", number1, number2, number1 + number2); 24 | printf("%d * %d = %d\n", number1, number2, number1 * number2); 25 | printf("%d - %d = %d\n", number1, number2, number1 - number2); 26 | printf("%d / %d = %d\n", number1, number2, number1 / number2); 27 | printf("%d %% %d = %d\n", number1, number2, number1 % number2); 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /src/switch-range.c: -------------------------------------------------------------------------------- 1 | /* 2 | * In this example, the ... (range operator) is used to create ranges within case statements. However, note that this syntax is available in C99 and later versions. If you are using an older C version, you might need to use individual case statements for each value in the range. 3 | */ 4 | 5 | #include 6 | 7 | int main() { 8 | int score; 9 | 10 | printf("Enter your score: "); 11 | scanf("%d", &score); 12 | 13 | switch(score) { 14 | case 90 ... 100: 15 | printf("Excellent!\n"); 16 | break; 17 | case 80 ... 89: 18 | printf("Good job!\n"); 19 | break; 20 | case 70 ... 79: 21 | printf("Average.\n"); 22 | break; 23 | case 60 ... 69: 24 | printf("Needs improvement.\n"); 25 | break; 26 | case 0 ... 59: 27 | printf("Failed. Work harder.\n"); 28 | break; 29 | default: 30 | printf("Invalid score. Please enter a valid score.\n"); 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/datatypes.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | printf("char ranges from %d to %d \n", CHAR_MIN, CHAR_MAX); 9 | printf("unsigned char ranges from %d to %u \n\n", 0, UCHAR_MAX); 10 | 11 | printf("short ranges from %d to %d \n", SHRT_MIN, SHRT_MAX); 12 | printf("unsigned short ranges from %d to %u \n\n", 0, USHRT_MAX); 13 | 14 | printf("int ranges from %d to %d \n", INT_MIN, INT_MAX); 15 | printf("unsigned int ranges from %d to %u \n\n", 0, UINT_MAX); 16 | 17 | printf("long ranges from %ld to %ld \n", LONG_MIN, LONG_MAX); 18 | printf("unsigned long ranges from %d to %lu \n\n", 0, ULONG_MAX); 19 | 20 | printf("long long ranges from %lld to %lld \n", LLONG_MIN, LLONG_MAX); 21 | printf("unsigned long long ranges from %d to %llu \n\n", 0, ULLONG_MAX); 22 | 23 | printf("\n\tFloating Point Types\n"); 24 | printf("float ranges from %.10e to %.10e \n", FLT_MIN, FLT_MAX); 25 | printf("double ranges from %.10e to %.10e \n", DBL_MIN, DBL_MAX); 26 | printf("long double ranges from %.10e to %.10e \n\n\n\n", LDBL_MIN, LDBL_MAX); 27 | system("PAUSE"); 28 | return 0; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /assignments/A1-22-26.md: -------------------------------------------------------------------------------- 1 | # Fundamentals of Programming 2 | 3 | ## BSCS - 2022-2026 (Morning) 4 | 5 | ## Checking if a number is prime or not 6 | 7 | **Due date: 16 July 2023** 8 | 9 | Write a program in c language. The behavior of the program should be as described below: 10 | 11 | - asks the user to input a number between 2 and 100. 12 | - If the user inputs a number out of this range the program should display "number out of range, press 1 to try again". 13 | - If the user presses 1 the program should again ask the user to input a number between 2 and 100 14 | - if the user enters a number between 2 and 100, the program should call a function `isprime()` 15 | - the function `isprime()` should return 1 if the number is prime, otherwise 0 16 | 17 | **After you have written and tested your program. Mention your complete name, father's name and roll number as comments in c program.** 18 | 19 | **Guidelines for submitting assignment** 20 | 21 | - create your github account 22 | - create a repo `assignment` 23 | - upload your c program to github repo `assignment` 24 | - email the link to your github repo to me [my official email](imranali@um.uob.edu.pk) 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/multiDimensionCharArray.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | // Understanding dimesions in char array 6 | // char grade='A'; 7 | 8 | char name[] = "Furqan"; 9 | /*printf("%c", name[0]); 10 | printf("\n"); 11 | printf("%s", name); 12 | */ 13 | char student[][7] = {"Furqan", "Sami", "Khizar", "Abid"}; 14 | for (size_t i = 0; i < 4; i++) 15 | printf("%s\n", student[i]); 16 | 17 | // char studInfo[5][10][20]= {{"Furqan", "Info of Furqran"}, 18 | 19 | /*const char Info[5][10][30] = {{"Quetta", "Capital of Balochistan"}, 20 | {"Karachi", "Capital of Sindh"}, 21 | {"Peshawar", "Capital of KPK"}, 22 | {"Lahore", "Capital of Punjab"}, 23 | {"Islamabad", "Capital of Pakistan"}}; 24 | printf("%-10s|%-30s", "City", "Info"); 25 | printf("\n"); 26 | printf("%-10s|%-30s\n", "==========", "======================="); 27 | for (size_t i = 0; i < 5; i++) 28 | { 29 | printf("%-10s|%-30s\n", Info[i][0], Info[i][1]); 30 | } 31 | */ 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /src/charfunctions2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main( void ) 5 | { 6 | printf( "%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", 7 | "According to islower:", 8 | islower( 'p' ) ? "p is a " : "p is not a ", 9 | "lowercase letter", 10 | islower( 'P' ) ? "P is a " : "P is not a ", 11 | "lowercase letter", 12 | islower( '5' ) ? "5 is a " : "5 is not a ", 13 | "lowercase letter", 14 | islower( '!' ) ? "! is a " : "! is not a ", 15 | "lowercase letter" ); 16 | 17 | printf( "%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", 18 | "According to isupper:", 19 | isupper( 'D' ) ? "D is an " : "D is not an ", 20 | "uppercase letter", 21 | isupper( 'd' ) ? "d is an " : "d is not an ", 22 | "uppercase letter", 23 | isupper( '8' ) ? "8 is an " : "8 is not an ", 24 | "uppercase letter", 25 | isupper( '$' ) ? "$ is an " : "$ is not an ", 26 | "uppercase letter" ); 27 | printf( "%s%c\n%s%c\n%s%c\n%s%c\n", 28 | "u converted to uppercase is ", toupper('u') , 29 | "7 converted to uppercase is ", toupper('7') , 30 | "$ converted to uppercase is ", toupper('$') , 31 | "L converted to lowercase is ", tolower('L') ); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /markdown/source2exe.md: -------------------------------------------------------------------------------- 1 | # Phases a c program passes through 2 | 3 | - Modern Integrated Development Environments(IDEs) e.g. CodeBlocks allow us to do many things in one place, e.g. example it allows all the functionalities of an editor such as notepad 4 | - When we click the Build and Run button or press an equivalent shortcut from the keyboard our program called the source code passes through many stages and is finally transformed into executable form 5 | 6 | 7 | ## Preprocessor 8 | 9 | The preprocessor takes the preprocessor directive and interprets it. For example, if `#include` directive is present in the program, then the preprocessor interprets the directive and replace this directive with the content of the `stdio.h` file. 10 | 11 | ## Compiler 12 | Compiler creates the object code. 13 | 14 | ## Linker 15 | Linker links the object code with the libraries and creates an executable file. 16 | 17 | ## Loader 18 | Loader puts the program in memory 19 | 20 | ## Execution 21 | CPU takes each instruction and executes it. 22 | 23 | 24 | ![Typical C Development environment](../figs/cprogrphases.png "Typical c development environment") 25 | 26 | **Note: the image above has been taken from the book C how to program by deitel and deitel 5th edition** 27 | 28 | -------------------------------------------------------------------------------- /markdown/dataTypesVariables.md: -------------------------------------------------------------------------------- 1 | # Basic Data types and variables 2 | 3 | - computer programs usually store data items, e.g. values representing age, height or weight of a student, temperature of a place, length of a wire, area of a land, volume of a water tank. 4 | - variables are used in programs to store such values 5 | - each variable has a type 6 | - e.g. age is usually recorded as a discrete number i.e. 24, grade may be represented as a single character 7 | - to use a variable it should be declared first 8 | - variable declaration is a statement of the following format 9 | 10 | ``` 11 | data_type name_of_variable; 12 | ``` 13 | 14 | - For example a variable of type integer having name age can be declared as 15 | 16 | ``` 17 | int age; 18 | ``` 19 | 20 | - variables may be given an initial value when they are declared e.g. 21 | 22 | ``` 23 | int weight=60; 24 | ``` 25 | 26 | Following table displays basic data types available in c, and the amount of memory they reserve 27 | 28 | | Type | size in bytes | 29 | |------|--------------| 30 | | char | 1 | 31 | | short| 2 | 32 | | int | 4 | 33 | | long | 8 | 34 | | float | 4 | 35 | | double | 8 | 36 | 37 | - the above table may be verified by executing [this program](../src/sizeof.c) which uses `sizeof` operator 38 | -------------------------------------------------------------------------------- /assignments/Spamdetector/Spamdetector.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 40 | 41 | -------------------------------------------------------------------------------- /markdown/unions.md: -------------------------------------------------------------------------------- 1 | # Unions 2 | 3 | - A union is a derived data type (like a structure) 4 | - members of union share the same storage space 5 | - for different situations in a program, some variables may not be relevant, but other variables are 6 | - A union shares the space instead of wasting storage on variables that are not being used 7 | - Members of a union can be of any data type 8 | - The number of bytes used to store a union must be at least enough to hold the largest member 9 | - In most cases, unions contain 2 or more data types 10 | - Only one member, and thus one data type, can be referenced at a time. 11 | - It is the responsibility of the programmer to ensure that the data in a union is referenced with the proper data type 12 | 13 | ## Union Declarations 14 | 15 | - A union defintion has the same format as a structure definition 16 | 17 | ```c 18 | union number { 19 | int x; 20 | double y; 21 | }; 22 | ``` 23 | - Union definition is normally placed in a header 24 | 25 | ## Operations that can be performed on unions 26 | 27 | - Assigning a union to another union of the same type 28 | - taking the address(&) of a union variable 29 | - accessing union members using the arrow or dot operator 30 | - unions may not be compared using == and != 31 | 32 | 33 | -------------------------------------------------------------------------------- /markdown/FOPA2Z.md: -------------------------------------------------------------------------------- 1 | # Fundamentals of Programming A to Z 2 | 3 | - The idea behind A to Z of a computing course is to provide bite size information in alphabetic order. 4 | - Since many terms describing a concept can start with a letter e.g. Data types starts with D, Dynamic memory allocation also starts with a D, only one of the terms will be covered in a series 5 | - Such bite size information is key in starting to understand a topic, writing one liners to answer short questions or even interview questions, and revising a course after a long break to prepare for a comprehensive exam. 6 | 7 | A for Algorithm, Arguments, Arrays 8 | B for Branching Statements (break, continue, return, goto), Boolean 9 | C for Compiling, Constants, Comments, Conditionals(if, if-else, switch) 10 | D for Data type, Dynamic Memory Allocation 11 | E for Expressions (Mathematical, Logical, Relational) 12 | F for Functions, Files 13 | G for 14 | H for 15 | I for IDEs 16 | J for 17 | K for 18 | L for Linker, Loader , Loops(Repetition), Literals 19 | M for 20 | N for Nesting 21 | O for Operators(their precedence) 22 | P for Pseudocode, Preprocessor, Pointers, Parameters 23 | Q for 24 | R for 25 | S for Strings, Static, Structures, Streams(input/output) 26 | T for Ternary Operator, Testing 27 | U for Unions 28 | V for Variables 29 | W for 30 | X for 31 | Y for 32 | Z for 33 | -------------------------------------------------------------------------------- /src/dowhile.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int num1, num2, result=0; 6 | int operation; // to store one of + , - , * or / 7 | int loop; 8 | char op; 9 | 10 | puts("New program"); 11 | do{ 12 | printf("\n Enter a number\t"); 13 | scanf("%d", &num1); 14 | printf("\n Enter another number\t"); 15 | scanf("%d", &num2); 16 | 17 | printf("\n Enter operator [1: +, 2: -, 3: *, 4:/]"); 18 | scanf(" %c", &op); 19 | 20 | switch(op) 21 | { 22 | 23 | //case 2: 24 | case '-': 25 | result = num1 - num2; 26 | printf("\n The result is %d", result); 27 | break; 28 | 29 | //case 1: 30 | case '+': 31 | result = num1 + num2; 32 | printf("\n The result is %d", result); 33 | break; 34 | 35 | //case 3: 36 | case '*': 37 | result = num1 * num2; 38 | printf("\n The result is %d", result); 39 | break; 40 | 41 | //case 4: 42 | case '/': 43 | result = num1 / num2; 44 | printf("\n The result is %d", result); 45 | break; 46 | 47 | default: 48 | printf("\n %c not in menu",op); 49 | } 50 | 51 | printf("\n Press 1 to continue"); 52 | scanf("%d", &loop); 53 | } 54 | while(loop == 1); 55 | return 0; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /src/charfunctions.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | printf( "%s\n%s%s\n%s%s\n\n", "According to isdigit: ", 7 | isdigit('8') ? "8 is a " : "8 is not a ", "digit", 8 | isdigit('#') ? "# is a " : "# is not a ", "digit" ); 9 | 10 | printf( "%s\n%s%s\n%s%s\n%s%s\n%s%s\n\n", 11 | "According to isalpha:", 12 | isalpha( 'A' ) ? "A is a " : "A is not a ", "letter", 13 | isalpha( 'b' ) ? "b is a " : "b is not a ", "letter", 14 | isalpha( '&' ) ? "& is a " : "& is not a ", "letter", 15 | isalpha( '4' ) ? "4 is a " : "4 is not a ", "letter" ); 16 | 17 | printf( "%s\n%s%s\n%s%s\n%s%s\n\n", 18 | "According to isalnum:", 19 | isalnum( 'A' ) ? "A is a " : "A is not a ", 20 | "digit or a letter", 21 | isalnum( '8' ) ? "8 is a " : "8 is not a ", 22 | "digit or a letter", 23 | isalnum( '#' ) ? "# is a " : "# is not a ", 24 | "digit or a letter" ); 25 | 26 | printf( "%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n", 27 | "According to isxdigit:", 28 | isxdigit( 'F' ) ? "F is a " : "F is not a ", 29 | "hexadecimal digit", 30 | isxdigit( 'J' ) ? "J is a " : "J is not a ", 31 | "hexadecimal digit", 32 | isxdigit( '7' ) ? "7 is a " : "7 is not a ", 33 | "hexadecimal digit", 34 | isxdigit( '$' ) ? "$ is a " : "$ is not a ", 35 | "hexadecimal digit", 36 | isxdigit( 'f' ) ? "f is a " : "f is not a ", 37 | "hexadecimal digit" ); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /src/struct2file.c: -------------------------------------------------------------------------------- 1 | // C program for writing 2 | // struct to file 3 | #include 4 | #include 5 | #include 6 | 7 | // a struct to read and write 8 | struct person 9 | { 10 | int id; 11 | char fname[20]; 12 | char lname[20]; 13 | }; 14 | 15 | int main () 16 | { 17 | FILE *outfile; 18 | size_t result; 19 | // open file for writing 20 | outfile = fopen ("person.dat", "a"); 21 | if (outfile == NULL) 22 | { 23 | fprintf(stderr, "\nError opening file\n"); 24 | exit (1); 25 | } 26 | 27 | // struct person p1 = {1, "Imran", "Ali"}; 28 | // struct person p2 = {2, "Abdul", "Basit"}; 29 | struct person p3 = {3, "Junaid", "Baber"}; 30 | struct person p4 = {4, "Asfand", "Yar"}; 31 | 32 | printf("\n The size of struct person = %ld", sizeof(struct person)); 33 | /* printf("\n fwrite before call = %ld", fwrite); */ 34 | // write struct to file 35 | fwrite (&p3, sizeof(struct person), 1, outfile); 36 | /* printf("\n fwrite after 1st call = %ld", fwrite); */ 37 | result = fwrite (&p4, sizeof(struct person), 1, outfile); 38 | /* printf("\n fwrite after 2nd call = %ld", fwrite); */ 39 | 40 | if(result == 1) 41 | printf("contents written to file successfully !\n"); 42 | else 43 | printf("error writing file !\n"); 44 | 45 | // close file 46 | fclose (outfile); 47 | 48 | return 0; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/charDataType.c: -------------------------------------------------------------------------------- 1 | /* 2 | * In this program we will 3 | * learn to declare char variable 4 | * and write different statements 5 | * which will help us understand 6 | * char data type 7 | */ 8 | 9 | #include 10 | 11 | int main() 12 | { 13 | 14 | char alphabet = 'Z'; 15 | /* 16 | char alphabet; 17 | alphabet='A'; 18 | */ 19 | 20 | // let us try to print the value using %d 21 | printf("\nvalue of alphabet is %c\n", alphabet); 22 | printf("\nvalue of alphabet in integer is %d\n", alphabet); 23 | printf("\nvalue of alphabet + 2 is %d\n", alphabet + 2); 24 | printf("\nchar alphabet + 2 is %c\n", alphabet + 2); 25 | // printf("\nvalue of alphabet + 2 as character is %c\n", alphabet + 2); 26 | 27 | // what will happen if we write the following lines 28 | 29 | alphabet = -1; 30 | printf("\n current value of alphabet is %c", alphabet); 31 | 32 | // try to guess without compile and run 33 | // check your answer after running the program 34 | // did you get the right answer?? 35 | 36 | // to find out how many bytes are alloted to char variable 37 | // printf("\n Memory alloted to char variable alphabet is %lu byte\n", sizeof(alphabet)); 38 | 39 | // list of all valid integer values and their corresponding characters 40 | 41 | /*for (int i = -128; i <= 127; i++) 42 | printf("\n %d is mapped to %c ", i, i); 43 | 44 | printf("\n"); 45 | */ 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /src/fileio.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int chkArguments(char *email, char *blacklist); 4 | int chkSpam(char *email, char *blacklist); 5 | int main(int argc, char *argv[]) 6 | { 7 | int chkArg = 0; 8 | int chkMail = 0; 9 | switch(argc) 10 | { 11 | case 1: 12 | case 2: 13 | printf("\n This programs expects two arguments \n "); 14 | break; 15 | 16 | case 3: 17 | printf("\n arguments supplied %s and %s \n", argv[1], argv[2]); 18 | chkArg = chkArguments(argv[1], argv[2]); 19 | if(chkArg == 1) 20 | { 21 | printf("\n Ready to detect spam \n"); 22 | chkMail= chkSpam(argv[1], argv[2]); 23 | if(chkMail==0) 24 | { 25 | printf("\n email is a spam"); 26 | } 27 | else 28 | { 29 | printf("\n email is not a spam"); 30 | } 31 | } 32 | 33 | break; 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | int chkArguments(char *email, char *blacklist) 40 | { 41 | int returnValue =1; 42 | FILE *fp, *fp2; 43 | fp = fopen(blacklist, "r"); 44 | fp2 = fopen(email, "r"); 45 | if( fp == NULL || fp2 == NULL ) 46 | { 47 | printf("\n Cannot open one of the files %s %s \n", blacklist, email); 48 | returnValue =0; 49 | if(fp != NULL) fclose(fp); 50 | if(fp2 != NULL) fclose(fp2); 51 | } 52 | return returnValue; 53 | } 54 | 55 | int chkSpam(char *email, char *blacklist) 56 | { 57 | 58 | 59 | // 60 | // place your logic to check spam here 61 | // 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /src/linkedlist.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Define a node structure 5 | typedef struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | } Node; 10 | 11 | // Function prototypes 12 | Node *createNode(int data); 13 | void insertAtBeginning(Node **head, int data); 14 | void printList(Node *head); 15 | 16 | int main() 17 | { 18 | // Initialize head to NULL for an empty list 19 | Node *head = NULL; 20 | 21 | // Insert elements at beginning 22 | insertAtBeginning(&head, 5); 23 | insertAtBeginning(&head, 3); 24 | insertAtBeginning(&head, 1); 25 | 26 | // Print the list 27 | printf("Linked list: "); 28 | printList(head); 29 | 30 | return 0; 31 | } 32 | 33 | // Create a new node with the given data 34 | Node *createNode(int data) 35 | { 36 | Node *newNode = (Node *)malloc(sizeof(Node)); 37 | newNode->data = data; 38 | newNode->next = NULL; 39 | return newNode; 40 | } 41 | 42 | // Insert a new node at the beginning of the list 43 | void insertAtBeginning(Node **head, int data) 44 | { 45 | Node *newNode = createNode(data); 46 | newNode->next = *head; 47 | *head = newNode; 48 | } 49 | 50 | // Print the data of each node in the list 51 | void printList(Node *head) 52 | { 53 | while (head != NULL) 54 | { 55 | printf("%d ", head->data); 56 | head = head->next; 57 | } 58 | printf("\n"); 59 | } 60 | -------------------------------------------------------------------------------- /assignments/Spamdetector/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int chkArguments(char *email, char *blacklist); 4 | int chkSpam(char *email, char *blacklist); 5 | int main(int argc, char *argv[]) 6 | { 7 | int chkArg = 0; 8 | int chkMail = 0; 9 | switch(argc) 10 | { 11 | case 1: 12 | case 2: 13 | printf("\n This programs expects two arguments \n "); 14 | break; 15 | 16 | case 3: 17 | printf("\n arguments supplied %s and %s \n", argv[1], argv[2]); 18 | chkArg = chkArguments(argv[1], argv[2]); 19 | if(chkArg == 1) 20 | { 21 | printf("\n Ready to detect spam \n"); 22 | chkMail= chkSpam(argv[1], argv[2]); 23 | if(chkMail==0) 24 | { 25 | printf("\n email is a spam"); 26 | } 27 | else 28 | { 29 | printf("\n email is not a spam"); 30 | } 31 | } 32 | 33 | break; 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | int chkArguments(char *email, char *blacklist) 40 | { 41 | int returnValue =1; 42 | FILE *fp, *fp2; 43 | fp = fopen(blacklist, "r"); 44 | fp2 = fopen(email, "r"); 45 | if( fp == NULL || fp2 == NULL ) 46 | { 47 | printf("\n Cannot open one of the files %s %s \n", blacklist, email); 48 | returnValue =0; 49 | if(fp != NULL) fclose(fp); 50 | if(fp2 != NULL) fclose(fp2); 51 | } 52 | 53 | return returnValue; 54 | } 55 | 56 | int chkSpam(char *email, char *blacklist) 57 | { 58 | 59 | 60 | // 61 | // place your logic to check spam here 62 | // 63 | return 0; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/format_specifiers.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* 4 | * This program shows how to use format specifiers in printf function 5 | * Information contained related to Quetta has been taken from Wikipedia 6 | * https://en.wikipedia.org/wiki/Quetta 7 | */ 8 | 9 | /* 10 | %c Character 11 | %d Signed integer 12 | %e or %E Scientific notation of floats 13 | %f Float values 14 | %g or %G Similar as %e or %E 15 | %hi Signed integer (short) 16 | %hu Unsigned Integer (short) 17 | %i Unsigned integer 18 | %l Long 19 | %lf Double 20 | %Lf Long double 21 | %lu Unsigned int or unsigned long 22 | %lld Long long 23 | %llu Unsigned long long 24 | %o Octal representation 25 | %p Pointer 26 | %s String 27 | %u Unsigned int 28 | %x or %X Hexadecimal representation 29 | %n Prints nothing 30 | %% Prints % character 31 | */ 32 | 33 | int main(int argc, char *argv[]) 34 | { 35 | printf("\n %s is the provincial capital of %s ","Quetta", "Balochistan"); 36 | printf("\n It was largely destroyed in %d earthquake", 1935); 37 | printf("\n Highest rainfall during 24 hours in Quetta is %f inches which was recroded in 17 December 2000",4.4); 38 | printf("\n Lowest temperature in Quetta is %.2f %c which was recroded on 8 January %d", -18.3, 'C', 1970); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /src/LogicalOperators.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(void) 3 | { 4 | int day, working; 5 | 6 | printf("\n Enter a number \n 1. \t Monday "); 7 | printf("\n 2. \t Tuesday \n 3. \t Wednesday "); 8 | printf("\n 4. \t Thursday \n 5. \t Friday "); 9 | 10 | scanf("%d", &day); 11 | //printf("\n Value of day is %d", day); 12 | printf("Enter 1 or 0, Working=1 or Holiday=0"); 13 | scanf("%d", &working); 14 | if(day==1 && working==1) 15 | { 16 | printf("\n Value of day is %d and value of working is %d", day, working); 17 | printf("\nEnglish Class"); 18 | } 19 | else 20 | { 21 | printf("\nNow on line 19"); 22 | if(day==2 && working==1) 23 | { 24 | printf("\n Value of day is %d and value of working is %d", day, working); 25 | printf("\nICT Class"); 26 | } 27 | else 28 | { 29 | printf("\nNow on line 25"); 30 | if(day==3 && working==1) 31 | { 32 | printf("\n Value of day is %d and value of working is %d", day, working); 33 | printf("\n Fundamentals of Programming"); 34 | } 35 | printf("\nNow on line 31"); 36 | if(day==4 && working==1) 37 | { 38 | printf("\n Value of day is %d and value of working is %d", day, working); 39 | printf("\n Applied Physics"); 40 | } 41 | printf("\nNow on line 37"); 42 | if(day==5 && working==1) 43 | { 44 | printf("\n Value of day is %d and value of working is %d", day, working); 45 | printf("\nMathematics"); 46 | } 47 | } 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /src/charfunctions3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main( void ) 4 | { 5 | printf( "%s\n%s%s%s\n%s%s%s\n%s%s\n\n", 6 | "According to isspace:", 7 | "Newline", isspace( '\n' ) ? " is a " : " is not a ", 8 | "whitespace character", "Horizontal tab", 9 | isspace( '\t' ) ? " is a " : " is not a ", 10 | "whitespace character", 11 | isspace( '%' ) ? "% is a " : "% is not a ", 12 | "whitespace character" ); 13 | printf( "%s\n%s%s%s\n%s%s\n\n", "According to iscntrl:", 14 | "Newline", iscntrl( '\n' ) ? " is a " : " is not a ", 15 | "control character", iscntrl( '$' ) ? "$ is a " : 16 | "$ is not a ", "control character" ); 17 | printf( "%s\n%s%s\n%s%s\n%s%s\n\n", 18 | "According to ispunct:", 19 | ispunct( ';' ) ? "; is a " : "; is not a ", 20 | "punctuation character", 21 | ispunct( 'Y' ) ? "Y is a " : "Y is not a ", 22 | "punctuation character", 23 | ispunct( '#' ) ? "# is a " : "# is not a ", 24 | "punctuation character" ); 25 | printf( "%s\n%s%s\n%s%s%s\n\n", "According to isprint:", 26 | isprint( '$' ) ? "$ is a " : "$ is not a ", 27 | "printing character", 28 | "Alert", isprint( '\a' ) ? " is a " : " is not a ", 29 | "printing character" ); 30 | printf( "%s\n%s%s\n%s%s%s\n", "According to isgraph:", 31 | isgraph( 'Q' ) ? "Q is a " : "Q is not a ", 32 | "printing character other than a space", 33 | "Space", isgraph( ' ' ) ? " is a " : " is not a ", 34 | "printing character other than a space" ); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /assignments/strongpwd.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int length(char array[]); 5 | int strongpwd(char array[]); 6 | 7 | int main() 8 | { 9 | 10 | char password[]="123456"; 11 | char password2[]="qwerty"; 12 | char password3[]="qwerty123"; 13 | char password4[]="14July_2020!"; 14 | 15 | printf("\n1. Length of password:\t %s is %d", password, length(password)); 16 | printf("\n2. Length of password2:\t %s is %d", password2, length(password2)); 17 | printf("\n3. Length of password3:\t %s is %d", password3, length(password3)); 18 | printf("\n4. Length of password4:\t %s is %d", password4, length(password4)); 19 | 20 | 21 | printf("\n1. Strength of password:\t %s is %d", password, strongpwd(password)); 22 | printf("\n2. Strength of password2:\t %s is %d", password2, strongpwd(password2)); 23 | printf("\n3. Strength of password3:\t %s is %d", password3, strongpwd(password3)); 24 | printf("\n4. Strength of password4:\t %s is %d", password4, strongpwd(password4)); 25 | 26 | 27 | 28 | printf("\n"); 29 | return 0; 30 | } 31 | 32 | int length(char array[]) 33 | { 34 | int length=0; 35 | int count=0; 36 | 37 | while(array[count] != '\0') 38 | { 39 | length++; 40 | count++; 41 | } 42 | 43 | return length; 44 | } 45 | 46 | 47 | int strongpwd(char array[]) 48 | { 49 | int strong=0; 50 | 51 | /* complete the program by 52 | * writing this function 53 | * you may use the character handling 54 | * functions taught in the class 55 | */ 56 | 57 | return strong; 58 | } 59 | -------------------------------------------------------------------------------- /markdown/intro2Algo.md: -------------------------------------------------------------------------------- 1 | **NOTE: Following content has been taken from the book C How to Program by Paul Deitel and Harvey Deitel** 2 | 3 | # Introduction to Algorithms 4 | 5 | - The solution to any computing problem involves executing a series of actions in a specific order. A procedure for solving a problem in terms of 6 | 1. the actions to be executed, and 7 | 2. the order in which these actions are to be executed 8 | is called an algorithm. 9 | 10 | - Specifying the order in which statements are to be executed in a computer program is called **program control** 11 | 12 | - **Pseudocode** is an artificial and informal language that helps you develop algorithms. 13 | 14 | ## Flowcharts 15 | 16 | - A flowchart is a graphical representation of an algorithm or of a portion of an algorithm. 17 | - Flowcharts are drawn using certain special-purpose symbols such as: 18 | - rectangles 19 | - diamonds 20 | - rounded rectangles, and 21 | - small circles 22 | - these symbols are connected by arrows called flowlines. 23 | 24 | - Like pseudocode, flowcharts are useful for developing and representing algorithms, although pseudocode is preferred by most programmers. 25 | - Flowcharts clearly show how control structures operate. 26 | 27 | - When drawing a flowchart that represents a complete algorithm, a rounded rectangle symbol containing the word **Begin** is the first symbol used in the flowchart; 28 | - a rounded rectangle symbol containing the word **End** is the last symbol used. 29 | 30 | ![flow chart](../figs/flowchart.png "Flow chart") 31 | 32 | - When drawing only a portion of an algorithm as in Figure above, the rounded rectangle symbols are omitted in favor of using small circle symbols, also called connector symbols. 33 | - Perhaps the most important flowcharting symbol is the diamond symbol, also called the decision symbol, which indicates that a decision is to be made. 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /src/operators.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int a = 2; 7 | int num1, num2; // variable declaration 8 | num1 = 20, num2 = 3; // initialization 9 | // printf(" %f + %f = %f", 3.5, 5.5, 3.5 + 5.5); 10 | // printf("\nMy name starts with the alphabet %c", 'I'); 11 | // printf("\n and my name is %s", "Imran"); 12 | 13 | // arithmetic operators 14 | 15 | printf("\n %d + %d = %d and %d + %d = %d",num1,num2,num1 + num2 ,num2,num1,num2 + num1); 16 | printf("\n %d - %d = %d and %d - %d = %d",num1,num2,num1 - num2 ,num2,num1,num2 - num1); 17 | printf("\n %d * %d = %d and %d * %d = %d",num1,num2,num1 * num2 ,num2,num1,num2 * num1); 18 | printf("\n %d / %d = %d and %d / %d = %d",num1,num2,num1 / num2 ,num2,num1,num2 / num1); 19 | printf("\n %d %% %d = %d and %d %% %d = %d",num1,num2,num1 % num2 ,num2,num1,num2 % num1); 20 | 21 | printf("\n %d - %d = %d and %d - %d = %d",3,5,3-5,5,3,5-3); 22 | printf("\n %d * %d = %d and %d * %d = %d",3,5,3*5,5,3,5*3); 23 | printf("\n %d / %d = %d and %d / %d = %d",3,5,3/5,5,3,5/3); 24 | printf("\n %d %% %d = %d and %d %% %d = %d",3,5,3%5,5,3,5%3); 25 | 26 | // arithmetic assignment operators 27 | 28 | printf("\n The value of a is %d",a); 29 | a = a + 2; 30 | printf("\n The value of a is %d",a); 31 | a += 2; 32 | printf("\n The value of a is %d",a); 33 | printf("\n The value of a+=2 is %d", a+=2); 34 | 35 | printf("\n The value of a%%=5 is %d", a%=5); 36 | 37 | //Relational Operators 38 | 39 | printf("\nThe result of a<2 is %d", a<2); 40 | printf("\nThe result of a>2 is %d", a>2); 41 | printf("\nThe result of a==2 is %d", a==2); 42 | printf("\nThe result of a<=2 is %d", a<=2); 43 | printf("\nThe result of a>=2 is %d", a>=2); 44 | printf("\nThe result of a!=2 is %d", a!=2); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /markdown/LecturesScript.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Introduction to C Programming" 3 | author: "Imran Ali" 4 | 5 | --- 6 | 7 | 8 | 9 | ## Introduction 10 | 11 | - Hi everyone, and welcome to our series on C programming! 12 | - In this video, we'll dive into the basics of C programming language. 13 | 14 | 15 | ## What is C? 16 | 17 | - C is a powerful and popular programming language known for its efficiency and flexibility. 18 | - Developed in the early 1970s by Dennis Ritchie at Bell Labs, C has since become one of the most widely used programming languages. 19 | ![](figs/dennis.jpeg "Dennis Ritche")\ 20 | ![](figs/bellLabs.jpeg "Bell Labs")\ 21 | 22 | 23 | 24 | ## Importance of C 25 | 26 | - C is widely used in system programming, operating systems, embedded systems, and more. 27 | - Its speed and ability to directly manipulate hardware make it indispensable in many areas of computing. 28 | 29 | 30 | ## Series Overview 31 | - Throughout this series, we'll cover everything you need to know to become proficient in C programming. 32 | - From basic syntax to advanced topics, we'll walk you through each concept step by step. 33 | 34 | 35 | ## What You'll Learn 36 | - Basic structure of a C program 37 | - Data types and variables 38 | - Operators and expressions 39 | - Input and output operations 40 | - Control flow statements 41 | - Functions and modular programming 42 | - Debugging techniques 43 | - And much more! 44 | 45 | ## Conclusion 46 | - By the end of this series, you'll have a solid understanding of C programming and be ready to tackle more complex projects. 47 | - So let's get started with the fundamentals of C programming! 48 | 49 | ## Thank you 50 | 51 | - If you liked the video give it a thumbs up 52 | - subscribe and share it with your friends 53 | - see you in the next video 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int marks; 6 | float GP; 7 | 8 | printf("\n Enter marks"); 9 | scanf("%d", &marks); 10 | 11 | switch(marks) 12 | { 13 | case 50: 14 | GP=1.00; 15 | break; 16 | 17 | case 51: 18 | GP=1.10; 19 | break; 20 | 21 | case 52: 22 | GP=1.20; 23 | break; 24 | 25 | case 53: 26 | GP=1.30; 27 | break; 28 | 29 | case 54: 30 | GP=1.40; 31 | break; 32 | 33 | case 55: 34 | GP=1.50; 35 | break; 36 | 37 | case 56: 38 | GP=1.60; 39 | break; 40 | 41 | case 57: 42 | GP=1.70; 43 | break; 44 | 45 | case 58: 46 | GP=1.80; 47 | break; 48 | 49 | case 59: 50 | GP=1.90; 51 | break; 52 | 53 | case 60: 54 | GP=2.00; 55 | break; 56 | 57 | case 61: 58 | GP=2.10; 59 | break; 60 | 61 | case 62: 62 | GP=2.20; 63 | break; 64 | 65 | case 63: 66 | GP=2.30; 67 | break; 68 | 69 | case 64: 70 | GP=2.40; 71 | break; 72 | 73 | case 65: 74 | GP=2.50; 75 | break; 76 | 77 | case 66: 78 | GP=2.50; 79 | break; 80 | 81 | case 67: 82 | GP=2.50; 83 | break; 84 | 85 | case 68: 86 | GP=2.50; 87 | break; 88 | 89 | case 69: 90 | GP=2.50; 91 | break; 92 | 93 | case 69: 94 | GP=2.50; 95 | break; 96 | 97 | case 70: 98 | GP=2.50; 99 | break; 100 | 101 | case 71: 102 | GP=2.50; 103 | break; 104 | 105 | case 72: 106 | GP=2.50; 107 | break; 108 | 109 | case 73: 110 | GP=2.50; 111 | break; 112 | 113 | case 74: 114 | GP=2.50; 115 | break; 116 | 117 | case 75: 118 | GP=2.50; 119 | break; 120 | 121 | case 76: 122 | GP=2.50; 123 | break; 124 | 125 | case 77: 126 | GP=2.50; 127 | break; 128 | 129 | case 78: 130 | GP=2.50; 131 | break; 132 | 133 | case 79: 134 | GP=2.50; 135 | break; 136 | 137 | case 80: 138 | GP=2.50; 139 | break; 140 | } 141 | return 0; 142 | } 143 | -------------------------------------------------------------------------------- /assignments/pointers.md: -------------------------------------------------------------------------------- 1 | **Credit: The following challenge has bee taken from hackerrank.com** 2 | 3 | # Objective 4 | 5 | In this challenge, you will learn to implement the basic functionalities of pointers in C. A pointer in C is a way to share a memory address among different contexts (primarily functions). They are primarily used whenever a function needs to modify the content of a variable that it does not own. 6 | 7 | In order to access the memory address of a variable, `val`, prepend it with `&` sign. For example, `&val` returns the memory address of `val`. 8 | 9 | This memory address is assigned to a pointer and can be shared among various functions. For example `int *p = &val`, will assign the memory address of `val` to pointer `p`. To access the content of the memory to which the pointer points, prepend it with a `*`. For example, `*p` will return the value reflected by `val` and any modification to it will be reflected at the source (`val`). 10 | 11 | ```C 12 | void increment(int *v) { 13 | (*v)++; 14 | } 15 | int main() { 16 | int a; 17 | scanf("%d", &a); 18 | increment(&a); 19 | printf("%d", a); 20 | return 0; 21 | } 22 | ``` 23 | 24 | # Task 25 | 26 | Complete the function `void update(int *a,int *b)`. It receives two integer pointers, `int* a` and `int* b`. Set the value of `a` to their sum, and `b` to their absolute difference. There is no return value, and no return statement is needed. 27 | 28 | ```C 29 | #include 30 | 31 | void update(int *a,int *b) { 32 | // Complete this function 33 | } 34 | 35 | int main() { 36 | int a, b; 37 | int *pa = &a, *pb = &b; 38 | scanf("%d %d", &a, &b); 39 | update(pa, pb); 40 | printf("%d\n%d", a, b); 41 | 42 | return 0; 43 | } 44 | ``` 45 | 46 | # Input Format 47 | 48 | The input will contain two integers, `a` and `b` , separated by a newline. 49 | 50 | # Output Format 51 | 52 | Modify the two values in place and the code stub main() will print their values. 53 | 54 | 55 | # Sample Input 56 | 57 | 4 58 | 5 59 | 60 | # Sample Output 61 | 62 | 9 63 | 1 64 | -------------------------------------------------------------------------------- /markdown/instructions.md: -------------------------------------------------------------------------------- 1 | # Task temperature conversion program 2 | 3 | You will be writing step by step statements by following the instructions listed below. Upon completion the result program will convert given temperature in required units, Celsius or Fahrenheit. 4 | 5 | Formulas for conversion are as under: 6 | 7 | 1. F = (C * 9 / 5) + 32 8 | 2. C = (F - 32) * 5 / 9 9 | 10 | ## Sample interaction of the desired program 11 | 12 | 13 | Temperature Conversion Menu 14 | =========================== 15 | 1. Fahrenheit 16 | 2. Celsius 17 | Convert from **1** 18 | Convert to **2** 19 | temperature **32** 20 | Converting **32** Fahrenheit to Celsius results in **0** 21 | 22 | 23 | ## Instructions 24 | 25 | 1. Include header file for standard input output 26 | 2. Write main function 27 | 3. declare 2 variables of type int with the name **from** and **to** and initialize with value **0** 28 | 4. declare 2 variables of type float with the name **temperature** and **result** and initialize with value **0.0** 29 | 5. Write 3 **printf** statements to display the menu of the program 30 | 6. Display the message **Convert from** using **printf** 31 | 7. Use **scanf** to take input in **from** variable 32 | 8. Display the message **Convert to** using **printf** 33 | 9. Use **scanf** to take input in **to** variable 34 | 10. Display the message **temperature** using **printf** 35 | 11. Use **scanf** to take input in **temperature** variable 36 | 12. Write **if condition**, if value of **from is 1** and **to is 2**, then use formula 2 and store the answer in **result** 37 | 13. Write **if condition**, if value of **from is 2** and **to is 1**, then use formula 1 and store the answer in **result** 38 | 39 | 14. Write **printf** statement to display the last line as shown in the sample interaction above. 40 | 41 | 42 | ## Class Work 43 | 44 | Extend your program and include 3rd Option **Kelvin** in the **temperature conversion menu** 45 | 46 | Formulas for conversion are as under: 47 | 48 | 1. K = C + 273.15 49 | 2. K = (F - 32) * 5 / 9 + 273.15 50 | 51 | Modify the above formulas to so that you may convert from **Celsius and Fahrenheit to Kelvin** 52 | -------------------------------------------------------------------------------- /src/cards.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define CARDS 52 6 | #define FACES 13 7 | 8 | struct card 9 | { 10 | const char *face; // define pointer face 11 | const char *suit; // define pointer suit 12 | }; // end struct card 13 | 14 | typedef struct card Card; // new type name for struct card 15 | 16 | // prototypes 17 | void fillDeck(Card *const wDeck, const char *wFace[], const char *wSuit[]); 18 | 19 | void shuffle(Card *const wDeck); 20 | void deal(const Card *const wDeck); 21 | 22 | int main(void) 23 | { 24 | Card deck[CARDS]; // define array of Cards 25 | 26 | // initialize array of pointers 27 | const char *face[] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; 28 | 29 | // initialize array of pointers 30 | const char *suit[] = {"Hearts", "Diamonds", "Clubs", "Spades"}; 31 | 32 | srand(time(NULL)); // randomize 33 | 34 | fillDeck(deck, face, suit); // load the deck with Cards 35 | shuffle(deck); // put Cards in random order 36 | deal(deck); // deal all 52 Cards 37 | } 38 | 39 | // place strings into Card Structures 40 | void fillDeck(Card *const wDeck, const char *wFace[], const char *wSuit[]) 41 | { 42 | size_t i; // counter 43 | 44 | // loop through wDeck 45 | for (i = 0; i < CARDS; ++i) 46 | { 47 | wDeck[i].face = wFace[i % FACES]; 48 | wDeck[i].suit = wSuit[i / FACES]; 49 | } // end for 50 | } // end function fillDeck 51 | 52 | // shuffle cards 53 | 54 | void shuffle(Card *const wDeck) 55 | { 56 | size_t i, j; 57 | Card temp; // define temporary structure for swapping cards 58 | 59 | for (i = 0; i < CARDS; ++i) 60 | { 61 | j = rand() % CARDS; 62 | temp = wDeck[i]; 63 | wDeck[i] = wDeck[j]; 64 | wDeck[j] = temp; 65 | } // end for 66 | } // end function shuffle 67 | 68 | void deal(const Card *const wDeck) 69 | { 70 | size_t i; 71 | 72 | // loop through wDeck 73 | for (i = 0; i < CARDS; i++) 74 | { 75 | printf("%5s of %-8s%s", wDeck[i].face, wDeck[i].suit, (i + 1) % 4 ? " " : "\n"); 76 | } // end for 77 | } // end function deal 78 | -------------------------------------------------------------------------------- /src/malloc.c: -------------------------------------------------------------------------------- 1 | // Dynamic memory allocation using malloc function 2 | #include 3 | #include 4 | 5 | int main() { 6 | int *arr; 7 | int size; 8 | 9 | // Get the size of the array from the user 10 | printf("Enter the size of the array: "); 11 | scanf("%d", &size); 12 | 13 | // Allocate memory for the array based on user input 14 | arr = (int *)malloc(size * sizeof(int)); 15 | 16 | // Check if memory allocation was successful 17 | if (arr == NULL) { 18 | printf("Memory allocation failed.\n"); 19 | return 1; // Exit the program with an error code 20 | } 21 | 22 | // Input values into the array 23 | printf("Enter %d integer values:\n", size); 24 | for (int i = 0; i < size; ++i) { 25 | scanf("%d", &arr[i]); 26 | } 27 | 28 | // Display the values in the array 29 | printf("Entered values in the array:\n"); 30 | for (int i = 0; i < size; ++i) { 31 | printf("%d ", arr[i]); 32 | } 33 | printf("\n"); 34 | 35 | // Deallocate the allocated memory when done 36 | free(arr); 37 | 38 | return 0; // Exit the program successfully 39 | } 40 | 41 | /* Explaination of the code containing call to malloc 42 | * Certainly! Let's break down the line of code that contains `malloc` in the provided example: 43 | 44 | ```c 45 | arr = (int *)malloc(size * sizeof(int)); 46 | ``` 47 | 48 | 1. **`malloc(size * sizeof(int))`:** 49 | - `malloc` is a function in C that stands for memory allocation. It dynamically allocates a block of memory of a specified size during program execution. 50 | - `size * sizeof(int)` calculates the total number of bytes needed for the array. `sizeof(int)` gives the size of one integer in bytes, and multiplying it by `size` gives the total size needed for the array. 51 | 52 | 2. **`(int *)`:** 53 | - The result of `malloc` is a void pointer (`void *`). In C, it's a good practice to cast this pointer to the appropriate type. Here, it's cast to `(int *)`, indicating that the allocated memory is expected to be used as an array of integers. 54 | 55 | 3. **`arr = ...`:** 56 | - The result of the `malloc` operation is assigned to the pointer variable `arr`. This means that `arr` now points to the beginning of the dynamically allocated memory block. 57 | 58 | So, in summary, this line of code dynamically allocates memory for an array of integers and assigns the address of the allocated memory to the pointer variable `arr`. The size of the allocated memory is determined by the user input (`size`). 59 | */ 60 | 61 | -------------------------------------------------------------------------------- /markdown/pointers.md: -------------------------------------------------------------------------------- 1 | # Pointers 2 | 3 | ## Introduction 4 | - A pointer in C is a way to share a memory address among different contexts (primarily functions). 5 | - They are primarily used whenever a function needs to modify the content of a variable that it does not own. 6 | - Pointer is one of the most powerful features of the C programming language. 7 | - Pointers enable programs to:- 8 | i- simulate call-by-reference and 9 | ii- to create and manipulate dynamic data structures (i.e. data structures that can grow and shrink at execution time, such as linked lists, queues, stacks and trees). 10 | 11 | ## Pointer Variable Definitions and Initialization 12 | - Pointers are variables whose values are memory addresses. 13 | - Normally a variable directly contains a specific value. A pointer, contains an address of a variable that contains a specific value. 14 | - In this sense, a variable name directly references a value, and a pointer indirectly references a value. 15 | - Referencing a value through a pointer is called indirection. 16 | - Pointers must be defined before they can be used. 17 | 18 | ```c 19 | int *countPtr, count; 20 | ``` 21 | - The definition above specifies that variable countPtr is of type int * and is read "countPtr is a pointer to int" or "countPtr points to an object of type int" 22 | . 23 | - Note that the variable count is defined to be an int, not a pointer to an int. 24 | - The * only applies to countPtr in the definition. 25 | - Pointers can be defined to point to objects of any type. 26 | - Pointers should be initialized when they are defined or in an assignment statement. 27 | - A pointer may be initialized to 0, NULL or an address. 28 | - A pointer with the value NULL points to nothing. 29 | - NULL is a symbolic constant defined in the header and several other headers, such as 30 | - Initializing a pointer to 0 is equivalent to initializing with NULL. 31 | 32 | ## Pointer Operators 33 | 34 | The & or address operator is a unary operator that returns the address of its operand. For example 35 | 36 | ```c 37 | int y =5 38 | int *yPtr; 39 | 40 | yPtr = &y 41 | ``` 42 | The third statement assigns the address of the variable y to pointer variable yPtr. 43 | 44 | ```c 45 | 46 | #include 47 | int main (void) 48 | { 49 | int a; 50 | int *aPtr; 51 | 52 | a = 7; 53 | aPtr = &a; 54 | printf("The address of a is %p \nThe value of aPtr is %p", &a, aPtr); 55 | printf("The value of a is %d \nThe value of *aPtr is %d", a, *aPtr); 56 | printf("\n\nShowing that * and & are compelements of each other\n&*aPtr = %p\n*&aPtr = %p\n", &*aPtr, *&aPtr); 57 | 58 | return 0; 59 | } 60 | 61 | ``` 62 | 63 | 64 | -------------------------------------------------------------------------------- /assignments/characterhandling.md: -------------------------------------------------------------------------------- 1 | # Checking for strength of a password 2 | 3 | ## Due date: 22 July, 2020. 4 | 5 | ### After completing the assignment email your code to me at [imranali@um.uob.edu.pk](mailto:imranali@um.uob.edu.pk). 6 | 7 | Strong Password allow users to prevent attackers from guessing passwords or brute-force attacks. See this wiki article on [password strength](https://en.wikipedia.org/wiki/Password_strength) for details. 8 | 9 | Your assignment is to complete the following program, by completing the function **strongpwd** which returns 1 if the password array passed to it contains a strong password, and returns 0 otherwise. 10 | 11 | ```{.c .numberLines} 12 | #include 13 | #include 14 | 15 | int length(char array[]); 16 | int strongpwd(char array[]); 17 | 18 | int main() 19 | { 20 | 21 | char password[]="123456"; 22 | char password2[]="qwerty"; 23 | char password3[]="qwerty123"; 24 | char password4[]="14July_2020!"; 25 | 26 | printf("\n1. Length of password:\t %s is %d", password, length(password)); 27 | printf("\n2. Length of password2:\t %s is %d", password2, length(password2)); 28 | printf("\n3. Length of password3:\t %s is %d", password3, length(password3)); 29 | printf("\n4. Length of password4:\t %s is %d", password4, length(password4)); 30 | 31 | 32 | printf("\n1. Strength of password:\t %s is %d", password, strongpwd(password)); 33 | printf("\n2. Strength of password2:\t %s is %d", password2, strongpwd(password2)); 34 | printf("\n3. Strength of password3:\t %s is %d", password3, strongpwd(password3)); 35 | printf("\n4. Strength of password4:\t %s is %d", password4, strongpwd(password4)); 36 | 37 | 38 | 39 | printf("\n"); 40 | return 0; 41 | } 42 | 43 | int length(char array[]) 44 | { 45 | int length=0; 46 | int count=0; 47 | 48 | while(array[count] != '\0') 49 | { 50 | length++; 51 | count++; 52 | } 53 | 54 | return length; 55 | } 56 | 57 | 58 | int strongpwd(char array[]) 59 | { 60 | int strong=0; 61 | 62 | /* complete the program by 63 | * writing this function 64 | * you may use the character handling 65 | * functions taught in the class 66 | */ 67 | 68 | return strong; 69 | } 70 | ``` 71 | 72 | To save time download the above program from [github](https://github.com/beyond2013/ProgIntro/blob/master/assignments/strongpwd.c). 73 | 74 | Following are the rules for a valid strong password: 75 | 76 | 1. It should be at least 8 characters in length, and 77 | 2. It should contain a combination of alphabets [a-z], numerics[0-9], and a special symbol e.g. (\_, @, !) 78 | 79 | 80 | You may take help from the function length which I have already provided. 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /markdown/stack.md: -------------------------------------------------------------------------------- 1 | # Stack rolling and unrolling 2 | 3 | **Note: Following content is generated using ChatGPT** 4 | 5 | In the context of C programming, "stack rolling" and "stack unrolling" usually refer to the process of managing the function call stack during program execution, particularly in relation to function calls and returns. 6 | 7 | 1. **Stack Rolling (Pushing onto the Stack):** 8 | - When a function is called in C, space is allocated on the call stack to store information related to the function call, such as local variables, parameters, return addresses, and sometimes the state of the calling function (such as the value of the stack pointer). 9 | - This process of pushing information onto the stack for the current function call is often referred to as "stack rolling". It involves adjusting the stack pointer to make room for the new function's stack frame and storing the necessary information in that frame. 10 | 11 | 2. **Stack Unrolling (Popping from the Stack):** 12 | - Once a function completes its execution and returns a value (if it's not a void function), the information related to that function call is removed from the stack to free up space. 13 | - This process of removing information from the stack after a function call completes is known as "stack unrolling". It involves adjusting the stack pointer to release the memory occupied by the function's stack frame, restoring the state of the calling function (such as the stack pointer), and returning control to the caller. 14 | 15 | The sequence of stack rolling and unrolling occurs automatically as functions are called and return in C programs, managed by the compiler and runtime environment. This process ensures that the program's execution flow is correctly maintained and that memory is efficiently utilized. 16 | 17 | Here's a simple example to illustrate the concept: 18 | 19 | ```c 20 | #include 21 | 22 | // Function declaration 23 | int add(int a, int b); 24 | 25 | int main() { 26 | int result; 27 | // Function call 28 | result = add(3, 5); 29 | printf("Result: %d\n", result); 30 | return 0; 31 | } 32 | 33 | // Function definition 34 | int add(int a, int b) { 35 | // Stack rolling: allocating space for function call 36 | // Local variables a and b are stored on the stack 37 | int sum = a + b; 38 | // Stack unrolling: releasing space after function call completes 39 | return sum; 40 | } 41 | ``` 42 | 43 | In this example, when the `add()` function is called from `main()`, space is allocated on the stack for the function's local variables (`a` and `b`). After the function completes execution and returns the sum, the space allocated for `add()`'s stack frame is released (stack unrolling). 44 | -------------------------------------------------------------------------------- /markdown/lists.md: -------------------------------------------------------------------------------- 1 | # Lists and their memory organization 2 | 3 | **Note: following content is generated using ChatGPT** 4 | 5 | In C language, lists are typically implemented using arrays or linked lists. Let's explore both approaches and how memory is organized for each: 6 | 7 | 1. **Arrays-based Lists:** 8 | - In an array-based list, elements are stored sequentially in memory, occupying contiguous locations. 9 | - Each element in the array represents a node in the list, containing the data and optionally pointers to the next or previous nodes (in the case of doubly linked lists). 10 | - The memory organization for an array-based list is straightforward. Suppose you have an array `arr` to store elements of the list. Each element in the array corresponds to a node in the list. 11 | - For example, if each node contains an integer value, the array might look like this: 12 | ``` 13 | Index: 0 1 2 3 4 14 | Array: [10, 20, 30, 40, 50] 15 | ``` 16 | - Accessing elements in an array-based list is efficient, as it allows direct indexing (`arr[i]`) to access elements. However, resizing the list can be costly as it may require allocating a new array and copying elements. 17 | 18 | 2. **Linked Lists:** 19 | - Linked lists are composed of nodes where each node contains data and a reference (pointer) to the next node in the sequence. 20 | - In a singly linked list, each node has a pointer to the next node, while in a doubly linked list, each node has pointers to both the next and previous nodes. 21 | - Memory for nodes in a linked list is dynamically allocated using `malloc()` or `calloc()` in C, and the nodes may not be stored contiguously in memory. 22 | - The memory organization for a linked list involves allocating memory for each node dynamically. Each node contains the data and a pointer to the next node (and in a doubly linked list, a pointer to the previous node as well). 23 | - For example, in a singly linked list: 24 | ``` 25 | Node 1: [Data: 10, Next: 0x1234] 26 | Node 2: [Data: 20, Next: 0x5678] 27 | Node 3: [Data: 30, Next: NULL] 28 | ``` 29 | Here, `0x1234`, `0x5678`, etc., are memory addresses pointing to the next nodes. 30 | - Linked lists allow for efficient insertion and deletion operations, especially when done at the beginning or end of the list. However, accessing elements in a linked list requires traversing the list sequentially, which can be less efficient than direct indexing in arrays. 31 | 32 | In summary, lists in C can be implemented using arrays or linked lists, each with its own memory organization and trade-offs in terms of access efficiency, insertion/deletion performance, and memory overhead. The choice between them depends on the specific requirements of the application. 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming Fundamentals 2 | 3 | ### Course Code : CMC 601 4 | 5 | ### Credit Hours : 4 (3,1) 6 | 7 | ## Course Content 8 | 9 | - [Introduction to problem solving](markdown/problemSolving.md) 10 | - [a brief review of Von-Neumann architecture](markdown/von-neumann.md) 11 | - [Introduction to programming](markdown/intro2programming.md) 12 | - [role of compiler and linker](markdown/source2exe.md) 13 | - [introduction to algorithms](markdown/intro2Algo.md) 14 | - [basic data types and variables](markdown/dataTypesVariables.md) 15 | - [input/output constructs](markdown/ioconstructs.md) 16 | - [arithmetic, comparison and logical operators](markdown/operators.md) 17 | - [conditional statements and execution flow for conditional statements](markdown/conditionalStatements.md) 18 | - [repetitive statements and execution flow for repetitive statements](markdown/repetitiveStatements.md) 19 | - [lists and their memory organization](markdown/lists.md) 20 | - [multi-dimensional lists](markdown/multiDlists.md) 21 | - [introduction to modular programming](markdown/intro2ModProg.md) 22 | - [function definition and calling](markdown/functions.md) 23 | - [stack rolling and unrolling](markdown/stack.md) 24 | - [string and string operations](markdown/gfmCCharNString.md) 25 | - [pointers/references](markdown/pointers.md) 26 | - [static and dynamic memory allocation](markdown/memory.md) 27 | - [File I/O operations](markdown/fileio.md) 28 | 29 | 30 | ## Reference Material 31 | - [Starting out with Python, 4th Edition, Tony Gaddis.](https://amzn.to/4kvT7D4) 32 | - [Starting out with Programming Logic & Designs, 4th Edition, Tony Gaddis](https://amzn.to/43f7l5P) 33 | - [The C Programming Language, 2nd Edition by Brian W. Kernighan, Dennis M. Ritchie](https://amzn.to/4dzz84v) 34 | - [Object Oriented Programming in C++ by Robert Lafore](https://amzn.to/3H807rH) 35 | - [Introduction to Computation and Programming Using Python: With Application to Understanding Data, 2nd Edition by Guttag, John](https://amzn.to/43a9n78) 36 | - [Practice of Computing Using Python, 3rd Edition by William Punch & Richard Enbody](https://amzn.to/43aHRXa) 37 | - [C How to Program, 7th Edition by Paul Deitel & Harvey Deitel](https://amzn.to/3SWD7OJ) 38 | - [Problem Solving and Program Design in C, 7th Edition by Jeri R. Hanly & Elliot B. Koffman](https://amzn.to/4kDnGHo) 39 | 40 | ## Useful Online Resources 41 | - [HackerRank c language](https://www.hackerrank.com/domains/c) 42 | - [Stack Overflow ](https://stackoverflow.com/) 43 | - [Introduction to Computer Science and Programming in Python](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/) 44 | - [SourceForge Download link Code blocks IDE for windows](https://sourceforge.net/projects/codeblocks/files/Binaries/20.03/Windows/codeblocks-20.03mingw-setup.exe) 45 | 46 | -------------------------------------------------------------------------------- /markdown/multiDlists.md: -------------------------------------------------------------------------------- 1 | # Multi Dimensional lists 2 | 3 | **Note: Following content is generated using ChatGPT** 4 | 5 | In C language, multi-dimensional lists are often implemented using arrays of arrays (or nested arrays). These multi-dimensional arrays can represent data structures such as matrices, grids, or tables. Let's explore how multi-dimensional lists are organized in memory and how they are accessed: 6 | 7 | 1. **Memory Organization:** 8 | - In a two-dimensional array, elements are arranged in rows and columns. 9 | - Memory for multi-dimensional arrays is contiguous, meaning that elements are stored in a single block of memory. 10 | - Each element in the array corresponds to a specific row and column combination. 11 | - For example, consider a 2D array `arr` representing a 3x3 matrix: 12 | ``` 13 | Index: 0 1 2 3 4 5 6 7 8 14 | Array: [10, 20, 30, 40, 50, 60, 70, 80, 90] 15 | ``` 16 | In this array, element `arr[0][0]` corresponds to the first row and first column, `arr[0][1]` corresponds to the first row and second column, and so on. 17 | 18 | 2. **Accessing Elements:** 19 | - To access an element in a multi-dimensional array, you use multiple indices. 20 | - For a two-dimensional array, you specify the row index followed by the column index. 21 | - For example, to access the element at row `i` and column `j` of the array `arr`, you would use `arr[i][j]`. 22 | - This access method is generalized for arrays with more than two dimensions. For example, for a three-dimensional array, you would use `arr[i][j][k]`. 23 | 24 | 3. **Declaration and Initialization:** 25 | - Multi-dimensional arrays are declared by specifying the dimensions of each dimension. 26 | - For example, to declare a 2D array `arr` with dimensions 3x3: 27 | ```c 28 | int arr[3][3]; 29 | ``` 30 | - Initialization of multi-dimensional arrays can be done using nested initializer lists: 31 | ```c 32 | int arr[3][3] = { 33 | {1, 2, 3}, 34 | {4, 5, 6}, 35 | {7, 8, 9} 36 | }; 37 | ``` 38 | 39 | 4. **Dynamic Memory Allocation:** 40 | - You can dynamically allocate memory for multi-dimensional arrays using pointers and dynamic memory allocation functions like `malloc()` or `calloc()`. 41 | - For example, to dynamically allocate memory for a 2D array: 42 | ```c 43 | int **arr; 44 | arr = (int **)malloc(rows * sizeof(int *)); 45 | for (int i = 0; i < rows; i++) { 46 | arr[i] = (int *)malloc(columns * sizeof(int)); 47 | } 48 | ``` 49 | 50 | Multi-dimensional lists in C offer a convenient way to represent and manipulate data structures with multiple dimensions. Whether statically declared or dynamically allocated, understanding how memory is organized and accessed is essential for effectively working with multi-dimensional arrays. 51 | -------------------------------------------------------------------------------- /markdown/ioconstructs.md: -------------------------------------------------------------------------------- 1 | # Input Output Constructs 2 | 3 | - For displaying data/information on the standard output (i.e. display screen) `printf()` function is used. 4 | - [See this program on how to use printf](../src/using_printf.c) is a program that shows how to `printf()` is used. 5 | 6 | - For taking input from standard input (i.e. keyboard) `scanf()` function is used. 7 | - [See this program on how to use scanf](../src/using_scanf.c) is a program that shows how to `scanf()` is used. 8 | - both `printf()` and `scanf()` functions are provided by the **standard input/output header** `` 9 | - `printf()` function usually involves using **escape sequences** and **format specifiers** 10 | 11 | 12 | ## Escape Sequences 13 | 14 | - The backslash in `\n` is called the escape character. 15 | - When the compiler sees a backslash in a string, it combines backslash with the next character to form an **escape sequence** 16 | - The escape sequence `\n` means newline 17 | 18 | Following table lists escape sequences and their description: 19 | 20 | 21 | | Escape Sequence | Description | Escape Sequence | Description | Escape Sequence | Description | 22 | |:---------------:|-----------------|:---------------:|--------------|:---------------:|--------------------| 23 | | \a | Alarm | \t | tab | \? | question mark | 24 | | \b | backspace | \v | vertical tab | \000 | octal number | 25 | | \f | Form feed | \\ | backslash | \xhh | hexadecimal number | 26 | | \n | new line | \' | single quote | \0 | Null | 27 | | \r | carriage return | \" | double quote | | | 28 | 29 | - [See this program to understand how to use escape sequences](../src/escape_sequence.c) 30 | 31 | ## Format specifiers 32 | 33 | - are used during the input or output 34 | - `scanf()` function accepts 2 arguments 35 | - 1st argument is a format control string, which indicates what type of data should be entered 36 | - e.g. in `scanf("%d", &numb)` `%d` indicates that the data should be an integer 37 | 38 | Following table lists the format specifiers and their description: 39 | 40 | 41 | | Format Specifier | Description | 42 | |:----------------:|-----------------------------------| 43 | | %d | Integer Format Specifier | 44 | | %f | Float Format Specifier | 45 | | %c | Character Format Specifier | 46 | | %s | String Format Specifier | 47 | | %u | Unsigned Integer Format Specifier | 48 | | %ld | Long Int Format Specifier | 49 | 50 | - [See this program to understand how to use format specifiers](../src/format_specifiers.c) 51 | 52 | 53 | -------------------------------------------------------------------------------- /markdown/functions.md: -------------------------------------------------------------------------------- 1 | # Functions 2 | 3 | **Note: Following content is generated using ChatGPT** 4 | 5 | In C language, functions play a vital role in modularizing code and promoting code reuse. Here's a detailed explanation of how functions are declared, defined, and called: 6 | 7 | 1. **Function Declaration:** 8 | - A function declaration specifies the name, return type, parameters, and sometimes storage class of a function. 9 | - It tells the compiler about the existence of a function before its actual implementation, allowing the compiler to perform type checking. 10 | - Function declarations typically appear in header files (.h files) or at the beginning of source files (.c files) before their first use. 11 | - The syntax for function declaration is: 12 | ```c 13 | return_type function_name(parameter_type parameter1, parameter_type parameter2, ...); 14 | ``` 15 | 16 | 2. **Function Definition:** 17 | - A function definition provides the actual implementation of the function. 18 | - It includes the function header (name, return type, and parameters) followed by the function body enclosed in curly braces `{}`. 19 | - The function body contains the statements that define the behavior of the function. 20 | - Function definitions typically appear in source files (.c files). 21 | - The syntax for function definition is: 22 | ```c 23 | return_type function_name(parameter_type parameter1, parameter_type parameter2, ...) { 24 | // Function body 25 | // Statements defining the behavior of the function 26 | } 27 | ``` 28 | 29 | 3. **Function Call:** 30 | - Function calls are used to execute the code inside a function from other parts of the program. 31 | - To call a function, you specify its name followed by parentheses `()` containing arguments (if any). 32 | - If the function has a return value, you can assign it to a variable or use it in an expression. 33 | - The syntax for function call is: 34 | ```c 35 | return_value = function_name(argument1, argument2, ...); 36 | ``` 37 | - Example: 38 | ```c 39 | int result; 40 | result = add(3, 5); // Calling the function add with arguments 3 and 5 41 | ``` 42 | 43 | 4. **Example:** 44 | ```c 45 | // Function declaration 46 | int add(int num1, int num2); 47 | 48 | int main() { 49 | int result; 50 | // Function call 51 | result = add(3, 5); // Calling the function add with arguments 3 and 5 52 | return 0; 53 | } 54 | 55 | // Function definition 56 | int add(int num1, int num2) { 57 | return num1 + num2; // Function body: returning the sum of num1 and num2 58 | } 59 | ``` 60 | 61 | In summary, function declaration provides information about the function to the compiler, function definition contains the actual implementation, and function calls execute the code inside the function. Understanding how to declare, define, and call functions is fundamental in C programming for building modular and reusable code. 62 | 63 | -------------------------------------------------------------------------------- /assignments/spamdetector.md: -------------------------------------------------------------------------------- 1 | # Assignment 2 | 3 | ## Background 4 | Have you ever seen Junk or Spam link in your inbox? These are emails sent in bulk, and most of them are not only annoying but may also contain links that lead to phishing websites or site that are hosting malware, or include malware as file attachments. (see [Spamming](https://en.wikipedia.org/wiki/Spamming) for details) 5 | 6 | Most of the email services provide a mechanism to automatically detect spam email, and for doing this various techniques are used (see [Anti-Spam techniques](https://en.wikipedia.org/wiki/Anti-spam_techniques) for details). 7 | 8 | 9 | ## Objective 10 | 11 | In this assignment you will create a very simple spam detection program which will check the email contents against a list of blacklisted domains. Both the email and the black list will be placed in separate files and will be passed to the program as command line arguments. 12 | 13 | Following is the incomplete C program you are required to complete by writing the code for **chkSpam** function. The function should return 0 if the email file does not contain any of the domain names present in the blacklist file, otherwise it should return 1. 14 | 15 | ```{.c .numberLines} 16 | #include 17 | int chkArguments(char *email, char *blacklist); 18 | int chkSpam(char *email, char *blacklist); 19 | int main(int argc, char *argv[]) 20 | { 21 | int chkArg = 0; 22 | int chkMail = 0; 23 | switch(argc) 24 | { 25 | case 1: 26 | case 2: 27 | printf("\n This programs expects two arguments \n "); 28 | break; 29 | case 3: 30 | printf("\n arguments supplied %s and %s \n", argv[1], argv[2]); 31 | chkArg = chkArguments(argv[1], argv[2]); 32 | if(chkArg == 1) 33 | { 34 | printf("\n Ready to detect spam \n"); 35 | chkMail= chkSpam(argv[1], argv[2]); 36 | if(chkMail==0) 37 | { 38 | printf("\n email is a spam"); 39 | } 40 | else 41 | { 42 | printf("\n email is not a spam"); 43 | } 44 | } 45 | break; 46 | } 47 | return 0; 48 | } 49 | int chkArguments(char *email, char *blacklist) 50 | { 51 | int returnValue =1; 52 | FILE *fp, *fp2; 53 | fp = fopen(blacklist, "r"); 54 | fp2 = fopen(email, "r"); 55 | if( fp == NULL || fp2 == NULL ) 56 | { 57 | printf("\n Cannot open one of the files %s %s \n", blacklist, email); 58 | returnValue =0; 59 | if(fp != NULL) fclose(fp); 60 | if(fp2 != NULL) fclose(fp2); 61 | } 62 | return returnValue; 63 | } 64 | int chkSpam(char *email, char *blacklist) 65 | { 66 | // place your logic to check spam here 67 | return 0; 68 | } 69 | ``` 70 | 71 | 72 | ## Instructions 73 | 74 | 1. Do not re-write the entire program from scratch. 75 | 2. For completing **chkSpam** function read the file blacklist and load the domain names in an array. 76 | 3. Loop through the array and return 1 if any domain name is found in the email file. 77 | 4. Hint: You can use **strstr** function to search for a domain name. 78 | 5. After completing assignment only upload the **C** file on LMS. 79 | 80 | 81 | ## Due date: 16th August 2020 82 | -------------------------------------------------------------------------------- /assignments/functions.md: -------------------------------------------------------------------------------- 1 | # Writing user defined functions 2 | 3 | This assignment asks the programmers to write a function to calculate check bit of ISBN-13. 4 | 5 | ## What is ISBN-13 6 | 7 | The ISBN-13 (International Standard Book Number) method is a system for uniquely identifying books and other published materials. It's an expansion of the original ISBN system, which used 10 digits. Here's how the ISBN-13 method works: 8 | 9 | 1. **Prefix**: The ISBN-13 begins with a three-digit prefix known as the "Bookland" or "country code." This prefix identifies the language or geographic area of the publisher. 10 | 11 | 2. **Group Identifier**: Following the prefix, there is a group identifier of variable length. This identifies the specific publisher or imprint. 12 | 13 | 3. **Title Identifier**: The title identifier, also known as the item number, comes after the group identifier. It specifies the particular edition, format, or version of the publication. 14 | 15 | 4. **Check Digit**: The last digit of the ISBN-13 is a "check digit," which is calculated based on the preceding digits. It's used to detect errors in the ISBN and ensure its accuracy. 16 | 17 | ## The formula for calculating the check digit is as follows: 18 | 19 | - Take each digit of the ISBN-13, starting from the left. 20 | - Multiply the first digit by 1, the second digit by 3, the third digit by 1, the fourth digit by 3, and so on, alternating between 1 and 3. 21 | - Add up all the products. 22 | - Find the remainder when dividing the sum by 10. 23 | - Subtract the remainder from 10 to get the check digit. 24 | 25 | ## For example: 26 | 27 | Let's consider the ISBN-13 "978-0-306-40615-7": 28 | 29 | 1. Sum of products: $(9*1) + (7*3) + (8*1) + (0*3) + (3*1) + (0*3) + (6*1) + (4*3) + (0*1) + (6*3) + (1*1) + (5*3) = 143$. 30 | 2. Remainder when divided by 10: 143 % 10 = 3. 31 | 3. Check digit: 10 - 3 = 7. 32 | 33 | So, the complete ISBN-13 is "978-0-306-40615-7". 34 | 35 | The ISBN-13 method improves upon the older ISBN-10 system by providing more digits for increased capacity and by incorporating a check digit for enhanced accuracy. It's widely used in the publishing industry for cataloging and identifying books and other printed materials. 36 | 37 | ## Assignment - 1 38 | 39 | - Create a function `calculateCheckDigit()`. 40 | - The function should take 1 argument 41 | - The function should check if the number contains 12 digits 42 | - The function should calculate the 13th digit(Check digit) according to the formula mentioned in the example above. 43 | - The function should append the 13th digit to the end of number passed as argument. 44 | - Finally the function should return the 13 digit number 45 | 46 | ## Assignment - 2 47 | 48 | - Create another function `isValidISBN()` 49 | - The function should take 1 argument 50 | - The function should check if the number contains 13 digits 51 | - The function should return 1 if the check digit is correct 52 | - otherwise it should return 0 53 | 54 | After completing your assignment check whether your code works with the following ISBN 55 | 56 | 1. 9781108951562 57 | 2. 9789812593174 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /markdown/testinclude.md: -------------------------------------------------------------------------------- 1 | # Supplementary programs for understanding character and string handling in C Language 2 | 3 | This document contains three programs that will help you to understand the example code in the document C Characters and Strings. 4 | 5 | 1. Following program intends to show how char variables can be manipulated: 6 | 7 | ```{#char .c .numberLines} 8 | #include 9 | #include 10 | 11 | int main(void) 12 | { 13 | char grade = 'A'; 14 | 15 | printf("\n************ OUTPUT *********************"); 16 | printf("\n\n"); 17 | 18 | printf("\n Character stored in grade variable is \t %c", grade); 19 | 20 | printf("\n int value represented by char variable grade is \t %d", grade); 21 | 22 | grade = 66; 23 | 24 | printf("\n new Character value of grade variable is \t %c", grade); 25 | 26 | grade++; 27 | 28 | 29 | printf("\n Character value of grade variable after increment \t %c", grade); 30 | 31 | printf("\n\n"); 32 | 33 | printf("************ ****** *********************\n"); 34 | 35 | return 0; 36 | } 37 | ``` 38 | 39 | ```shell 40 | ************ OUTPUT ********************* 41 | 42 | Character stored in grade variable is A 43 | int value represented by char variable grade is 65 44 | new Character value of grade variable is B 45 | Character value of grade variable after increment C 46 | 47 | ************ ****** ********************* 48 | ``` 49 | 50 | 2. Character Arrays, and pointer to char 51 | 52 | ```{#charArray .c .numberLines} 53 | #include 54 | #include 55 | 56 | int main(void) 57 | { 58 | char course[] = "Programming Fundamentals"; 59 | 60 | char course2[] = {'D', 'B', 'M', 'S', '\0'}; 61 | 62 | const char *instructor = "Imran Ali"; 63 | 64 | printf("\n************ OUTPUT *********************"); 65 | 66 | printf("\n\n"); 67 | 68 | printf("\n value stored in course character Array %s ", course); 69 | 70 | printf("\n value stored in course2 character Array %s ", course2); 71 | 72 | printf("\n value stored in pointer variable %s ", instructor); 73 | 74 | printf("\n\n"); 75 | 76 | printf("************ ****** *********************\n"); 77 | 78 | return 0; 79 | } 80 | ``` 81 | 82 | ```shell 83 | ************ OUTPUT ********************* 84 | 85 | value stored in course character Array Programming Fundamentals 86 | value stored in course2 character Array DBMS 87 | value stored in pointer variable Imran Ali 88 | 89 | ************ ****** ********************* 90 | ``` 91 | 92 | \newpage 93 | 94 | 3. Use of Ternary Operator 95 | 96 | ```{#ternaryOperator .c .numberLines} 97 | #include 98 | #include 99 | 100 | int main(void) 101 | { 102 | 103 | 104 | printf("\n************ OUTPUT *********************"); 105 | 106 | printf("\n\n"); 107 | 108 | printf((2 > 3) ? "true" : "false"); 109 | 110 | printf("\n"); 111 | 112 | printf((2 < 3) ? "true" : "false"); 113 | 114 | printf("\n\n"); 115 | 116 | printf("************ ****** *********************\n"); 117 | 118 | return 0; 119 | } 120 | ``` 121 | 122 | ```shell 123 | ************ OUTPUT ********************* 124 | 125 | false 126 | true 127 | 128 | ************ ****** ********************* 129 | ``` 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /markdown/CharNStringSupplement.md: -------------------------------------------------------------------------------- 1 | # Supplementary programs for understanding character and string handling in C Language 2 | 3 | This document contains three programs that will help you to understand the example code in the document C Characters and Strings. 4 | 5 | 1. Following program intends to show how char variables can be manipulated: 6 | 7 | ```{#char .c .numberLines} 8 | #include 9 | #include 10 | 11 | int main(void) 12 | { 13 | char grade = 'A'; 14 | 15 | printf("\n************ OUTPUT *********************"); 16 | printf("\n\n"); 17 | 18 | printf("\n Character stored in grade variable is \t %c", grade); 19 | 20 | printf("\n int value represented by char variable grade is \t %d", grade); 21 | 22 | grade = 66; 23 | 24 | printf("\n new Character value of grade variable is \t %c", grade); 25 | 26 | grade++; 27 | 28 | 29 | printf("\n Character value of grade variable after increment \t %c", grade); 30 | 31 | printf("\n\n"); 32 | 33 | printf("************ ****** *********************\n"); 34 | 35 | return 0; 36 | } 37 | ``` 38 | 39 | ```shell 40 | ************ OUTPUT ********************* 41 | 42 | Character stored in grade variable is A 43 | int value represented by char variable grade is 65 44 | new Character value of grade variable is B 45 | Character value of grade variable after increment C 46 | 47 | ************ ****** ********************* 48 | ``` 49 | 50 | 2. Character Arrays, and pointer to char 51 | 52 | ```{#charArray .c .numberLines} 53 | #include 54 | #include 55 | 56 | int main(void) 57 | { 58 | char course[] = "Programming Fundamentals"; 59 | 60 | char course2[] = {'D', 'B', 'M', 'S', '\0'}; 61 | 62 | const char *instructor = "Imran Ali"; 63 | 64 | printf("\n************ OUTPUT *********************"); 65 | 66 | printf("\n\n"); 67 | 68 | printf("\n value stored in course character Array %s ", course); 69 | 70 | printf("\n value stored in course2 character Array %s ", course2); 71 | 72 | printf("\n value stored in pointer variable %s ", instructor); 73 | 74 | printf("\n\n"); 75 | 76 | printf("************ ****** *********************\n"); 77 | 78 | return 0; 79 | } 80 | ``` 81 | 82 | ```shell 83 | ************ OUTPUT ********************* 84 | 85 | value stored in course character Array Programming Fundamentals 86 | value stored in course2 character Array DBMS 87 | value stored in pointer variable Imran Ali 88 | 89 | ************ ****** ********************* 90 | ``` 91 | 92 | \newpage 93 | 94 | 3. Use of Ternary Operator 95 | 96 | ```{#ternaryOperator .c .numberLines} 97 | #include 98 | #include 99 | 100 | int main(void) 101 | { 102 | 103 | 104 | printf("\n************ OUTPUT *********************"); 105 | 106 | printf("\n\n"); 107 | 108 | printf((2 > 3) ? "true" : "false"); 109 | 110 | printf("\n"); 111 | 112 | printf((2 < 3) ? "true" : "false"); 113 | 114 | printf("\n\n"); 115 | 116 | printf("************ ****** *********************\n"); 117 | 118 | return 0; 119 | } 120 | ``` 121 | 122 | ```shell 123 | ************ OUTPUT ********************* 124 | 125 | false 126 | true 127 | 128 | ************ ****** ********************* 129 | ``` 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /markdown/memory.md: -------------------------------------------------------------------------------- 1 | # Static and Dynamic Memory Allocation 2 | 3 | **Note: Following explanation is generated using ChatGPT** 4 | 5 | Let's start with a brief explanation of static and dynamic memory allocation in C. 6 | 7 | Static Memory Allocation: 8 | - Static memory allocation refers to the allocation of memory at compile time. 9 | - Memory for variables declared with static storage class (using the `static` keyword) and global variables is allocated statically. 10 | - Memory for these variables is allocated once, and it persists throughout the program's execution. 11 | - The size of statically allocated memory is fixed and cannot be changed during runtime. 12 | 13 | Dynamic Memory Allocation: 14 | - Dynamic memory allocation refers to the allocation of memory at runtime. 15 | - In C, dynamic memory allocation is done using functions like `malloc()`, `calloc()`, `realloc()`, and `free()` from the `` library. 16 | - Memory allocated dynamically resides in the heap memory area. 17 | - It allows for more flexible memory management as the size of memory can be adjusted during runtime. 18 | - However, it's the responsibility of the programmer to deallocate dynamically allocated memory using the `free()` function to avoid memory leaks. 19 | 20 | Now, let's look at sample programs to illustrate both concepts: 21 | 22 | 1. Static Memory Allocation: 23 | 24 | ```c 25 | #include 26 | 27 | // Static allocation of array 28 | void staticArrayExample() { 29 | // Static array declaration 30 | int staticArray[5]; 31 | 32 | // Assigning values to the array elements 33 | for (int i = 0; i < 5; i++) { 34 | staticArray[i] = i * 2; 35 | } 36 | 37 | // Accessing and printing array elements 38 | for (int i = 0; i < 5; i++) { 39 | printf("%d ", staticArray[i]); 40 | } 41 | printf("\n"); 42 | } 43 | 44 | // Static allocation of global variable 45 | int globalVar = 10; 46 | 47 | int main() { 48 | staticArrayExample(); 49 | printf("Global variable: %d\n", globalVar); 50 | return 0; 51 | } 52 | ``` 53 | 54 | In this program, `staticArray` is statically allocated memory, and `globalVar` is also an example of static memory allocation. 55 | 56 | 2. Dynamic Memory Allocation: 57 | 58 | ```c 59 | #include 60 | #include 61 | 62 | // Dynamic allocation of array 63 | void dynamicArrayExample() { 64 | // Pointer to int to hold base address of dynamically allocated memory 65 | int *dynamicArray; 66 | int size = 5; 67 | 68 | // Dynamically allocating memory for array 69 | dynamicArray = (int *)malloc(size * sizeof(int)); 70 | 71 | // Check if memory allocation is successful 72 | if (dynamicArray == NULL) { 73 | printf("Memory allocation failed\n"); 74 | return; 75 | } 76 | 77 | // Assigning values to the dynamically allocated array 78 | for (int i = 0; i < size; i++) { 79 | dynamicArray[i] = i * 2; 80 | } 81 | 82 | // Accessing and printing array elements 83 | for (int i = 0; i < size; i++) { 84 | printf("%d ", dynamicArray[i]); 85 | } 86 | printf("\n"); 87 | 88 | // Freeing dynamically allocated memory 89 | free(dynamicArray); 90 | } 91 | 92 | int main() { 93 | dynamicArrayExample(); 94 | return 0; 95 | } 96 | ``` 97 | 98 | In this program, `dynamicArray` is dynamically allocated memory using the `malloc()` function. We allocate memory for an array of integers, assign values to it, and then free the memory using the `free()` function to prevent memory leaks. 99 | 100 | These examples should provide a basic understanding of static and dynamic memory allocation in C. 101 | -------------------------------------------------------------------------------- /markdown/staticvariables.md: -------------------------------------------------------------------------------- 1 | # Static Variables in C: Preserving Values Across Function Calls 2 | 3 | In C programming, a static variable is a special type of variable that retains its value between function calls. This is achieved by declaring the variable with the `static` keyword within a function's scope. Unlike automatic (local) variables that are destroyed upon function exit, static variables have a lifetime that extends throughout the entire program execution. 4 | 5 | ## Key Characteristics and Benefits: 6 | 7 | - **Value Persistence:** Static variables hold their value even after the function that declared them has returned. This allows them to "remember" information across multiple function calls. 8 | - **Initialization:** Static variables are initialized only once, either explicitly during declaration or with a default value (0 for numeric types). Subsequent function calls won't re-initialize them. 9 | - **Scope:** Static variables declared within a function have local scope, meaning they are accessible only within that function. However, their lifetime persists beyond the function's scope. 10 | 11 | ## Common Use Cases: 12 | 13 | 1. **Function Call Counting:** A static variable can be used to keep track of the number of times a function has been called. This can be useful for debugging, profiling, or implementing algorithms that require counting function invocations. 14 | 15 | ```c 16 | #include 17 | 18 | int callCount() { 19 | static int count = 0; // Static variable to store call count 20 | count++; 21 | return count; 22 | } 23 | 24 | int main() { 25 | for (int i = 0; i < 5; i++) { 26 | printf("Function called %d times\n", callCount()); 27 | } 28 | return 0; 29 | } 30 | ``` 31 | 32 | This code will output: 33 | 34 | ``` 35 | Function called 1 times 36 | Function called 2 times 37 | Function called 3 times 38 | Function called 4 times 39 | Function called 5 times 40 | ``` 41 | 42 | 2. **Preserving State Between Calls:** If a function needs to maintain some state information that should be preserved between calls, a static variable can be a good choice. This can be useful for implementing stateful calculations or tracking progress within a function. 43 | 44 | ```c 45 | #include 46 | 47 | int calculateFibonacci(int n) { 48 | static int fibPrev = 0, fibNext = 1; // Static variables for Fibonacci sequence 49 | int temp; 50 | 51 | if (n <= 1) { 52 | return n; 53 | } 54 | 55 | temp = fibNext; 56 | fibNext = fibPrev + fibNext; 57 | fibPrev = temp; 58 | 59 | return fibNext; 60 | } 61 | 62 | int main() { 63 | for (int i = 0; i < 10; i++) { 64 | printf("%d ", calculateFibonacci(i)); 65 | } 66 | printf("\n"); 67 | return 0; 68 | } 69 | ``` 70 | 71 | This code will output the first 10 Fibonacci numbers: 72 | 73 | ``` 74 | 0 1 1 2 3 5 8 13 21 34 75 | ``` 76 | 77 | 3. **Private Data Within Functions:** While global variables are generally discouraged due to potential naming conflicts and unintended side effects, static variables can provide a way to create private data within functions without the drawbacks of global variables. 78 | 79 | ## Cautions and Considerations: 80 | 81 | - **Overuse and Misuse:** While static variables can be helpful in certain scenarios, overuse can lead to code that is harder to understand and maintain. Use them judiciously when value persistence across function calls is truly necessary. 82 | - **Global Variable Lookalike:** Be mindful that static variables within functions aren't globally accessible. Avoid using them as a substitute for global variables, as this can still lead to naming conflicts and unintended side effects if used across multiple files. 83 | 84 | By effectively employing static variables, you can enhance the functionality and maintainability of your C programs. -------------------------------------------------------------------------------- /markdown/intro2programming.md: -------------------------------------------------------------------------------- 1 | # Introduction to programming 2 | 3 | Following suggestions can help you in learning the science and art of programming: 4 | 5 | 1. Writing your programs by hand on a piece of paper may sound like an outdated practice but it is very important especially for beginners. Being able to write a correct program on a paper is more important because our examination system currently allows taking exams on papers, not on computer. 6 | 7 | 2. It is equally important to be able to type the program on computer and check if it works. Many skills such as typing, indentation, debugging etc can only be learned by typing your program on computer. 8 | 9 | 3. Although you can type your program online by visiting online c compilers using your smartphone, I would advise you not to do so. 10 | 11 | 4. Install the [recommended software](https://sourceforge.net/projects/codeblocks/files/Binaries/20.03/Windows/codeblocks-20.03mingw-setup.exe) on your own computer. 12 | 13 | 5. Practice is the key, which means repeat, many students take pictures of the white board instead of taking notes, this is the modern trend but believe me when I say it will not help you in learning. 14 | 15 | 6. Just as writing code is a skill you will learn over time, reading code whether it is written by you or by your teacher is another skill. Many students cannot correctly compile a program because they could not read what the instructor wrote on the whiteboard e.g. when the instructor wrote semicolon ; you for some reason read comma , 16 | 17 | 7. When your program does not compile it will tell you in shape of warning or errors. Try to learn which type of errors are related to what kind of problems. e.g. "11. Statement missing ;" is telling you that you forgot to type a ; near line number 10 or 11. 18 | 19 | ## Introduction to C programming language 20 | 21 | Few basic but important things to keep in mind: 22 | 23 | - c language is case sensitive, which means if you write age and AGE in the same program they are two different things. 24 | - 99 percent of the programs we write will be written in small alphabets. 25 | - file extension of c programs is **.c** not **.cpp** 26 | - most of the programs we will write will be console programs, which means you will interact with your program in command window. 27 | - every time you make a change to your program you will need to save it and compile it. 28 | 29 | ### Reserved words / Keywords 30 | 31 | - when we write programs in c we give names to variables and functions, following is a **list of words that cannot be used as names** because they already reserved by c. 32 | 33 | 34 | | auto | break | case | char | 35 | |----------|-----------|------------|----------| 36 | | const | continue | default | do | 37 | | double | else | enum | extern | 38 | | float | for | goto | if | 39 | | int | long | register | return | 40 | | short | signed | sizeof | static | 41 | | struct | switch | typedef | union | 42 | | unsigned | void | volatile | while | 43 | 44 | - Keywords added in C99 standard 45 | `_Bool _Complex _Imaginary inline restrict` 46 | 47 | - Keywords added in C11 draft standard 48 | `_Alignas _Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local` 49 | 50 | ### Basic use of keyword- 51 | 1. int, float, char, double, long, short – These are the data types. Each data type has a different meaning. 52 | 2. if, else, switch, case, default – These are the types of control statements. 53 | 3. for, while, do – These are the types of loops. 54 | 4. return – used for returning a value. 55 | 5. void – One of the return type. 56 | 6. auto, extern, const, extern, register, signed, unsigned – These are used to defines variables. 57 | 7. break, continue – This keyword is used with a loop. 58 | 8. goto – Used for redirecting the flow of execution. 59 | 9. enum – It is a data type which contains set of constants. 60 | 10. sizeof – sizeof keyword is used to know the size. 61 | 11. struct, typeof – keywords used in the structure. 62 | 12. union – It is a collation of variables. 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /markdown/intro2ModProg.md: -------------------------------------------------------------------------------- 1 | # Introduction to Modular Programming 2 | 3 | **Note: Following contents are generated using ChatGPT** 4 | 5 | Modular programming is a software design technique that emphasizes breaking down a program into separate, interchangeable modules or components, each responsible for a specific functionality or feature. These modules are designed to be independent, self-contained units that can be developed, tested, and maintained separately, which promotes code re-usability, readability, and maintainability. 6 | 7 | Each module typically encapsulates a specific aspect of the overall functionality, such as handling input/output, performing calculations, or implementing a particular algorithm. These modules communicate with each other through well-defined interfaces, allowing them to interact without needing to know the internal details of one another. 8 | 9 | By organizing code into modular components, developers can: 10 | 11 | 1. **Facilitate teamwork**: Different team members can work on separate modules concurrently without interfering with each other's work. 12 | 13 | 2. **Promote code reuse**: Modules can be reused in different parts of the application or even in other projects, saving time and effort. 14 | 15 | 3. **Enhance maintainability**: Changes or updates to one module can be made independently without affecting other parts of the program, making maintenance easier. 16 | 17 | 4. **Improve readability**: Breaking down a program into smaller, focused modules can make the codebase easier to understand and navigate. 18 | 19 | Overall, modular programming helps in managing complexity, reducing errors, and increasing the overall efficiency of the software development process. 20 | 21 | ## C features that facilitate modular programming 22 | 23 | C language provides several features that facilitate modular programming: 24 | 25 | 1. **Functions**: C allows developers to encapsulate specific tasks or functionalities within functions. Functions help break down a program into smaller, manageable units, promoting modularity. Each function can focus on a specific task, making the code easier to understand, test, and maintain. 26 | 27 | 2. **Header files**: Header files (.h files) in C contain function prototypes and declarations of data types, constants, and macros. They allow developers to declare the interface of modules, enabling other modules to use their functionality without needing to know the implementation details. This promotes information hiding and encapsulation, key principles of modular programming. 28 | 29 | 3. **Separate compilation**: C supports separate compilation, allowing each module to be compiled independently into object files (.o files). This feature enables faster compilation times and facilitates incremental builds. Developers can compile and link modules separately, reducing the time needed to rebuild the entire program when making changes to a single module. 30 | 31 | 4. **Static and dynamic linking**: C supports both static and dynamic linking. Static linking combines object files into a single executable, while dynamic linking links libraries at runtime. These linking mechanisms enable developers to create modular programs by incorporating reusable libraries and modules into their applications, promoting code reuse and modularity. 32 | 33 | 5. **Structures and enums**: C provides structures and enums, which allow developers to organize related data elements into a single entity. Structures can be used to represent complex data structures, while enums can define sets of named integer constants. These features aid in organizing and encapsulating data within modules, contributing to modular programming. 34 | 35 | 6. **Preprocessor directives**: C preprocessor directives, such as #define and #include, enable conditional compilation and inclusion of header files, respectively. They allow developers to configure and customize compilation options and include necessary header files, promoting modular development by managing dependencies and modularizing code. 36 | 37 | By leveraging these features, developers can effectively implement modular programming principles in C, resulting in code that is easier to understand, maintain, and extend. 38 | -------------------------------------------------------------------------------- /assignments/conditionalstatements.md: -------------------------------------------------------------------------------- 1 | **Credit: The following challenge has bee taken from hackerrank.com** 2 | 3 | # Objective 4 | 5 | `if` and `else` are two of the most frequently used conditionals in C/C++, and they enable you to execute zero or one conditional statement among many such dependent conditional statements. We use them in the following ways: 6 | 7 | 1. **if :** This executes the body of bracketed code starting with **statement1** if **condition** evaluates to true. 8 | 9 | ```C 10 | if (condition) { 11 | statement1; 12 | ... 13 | } 14 | ``` 15 | 16 | 2. **if - else :** This executes the body of bracketed code starting with **statement1** if **condition** evaluates to true, or it executes the body of code starting with **statement2** if **condition** evaluates to false. Note that only one of the bracketed code sections will ever be executed. 17 | 18 | ```C 19 | if (condition) { 20 | statement1; 21 | ... 22 | } 23 | else { 24 | statement2; 25 | ... 26 | } 27 | ``` 28 | 29 | 3. **if - else if - else :** In this structure, dependent statements are chained together and the **condition** for each statement is only checked if all prior conditions in the chain are evaluated to false. Once a **condition** evaluates to true, the bracketed code associated with that statement is executed and the program then skips to the end of the chain of statements and continues executing. If each **condition** in the chain evaluates to false, then the body of bracketed code in the else block at the end is executed. 30 | 31 | ```C 32 | if(first condition) { 33 | ... 34 | } 35 | else if(second condition) { 36 | ... 37 | } 38 | . 39 | . 40 | . 41 | else if((n-1)'th condition) { 42 | .... 43 | } 44 | else { 45 | ... 46 | } 47 | ``` 48 | 49 | # Task 50 | Given a positive integer denoting `n` , do the following: 51 | 52 | - If `1 <= n <= 9` , print the lowercase English word corresponding to the number (e.g., one for 1 , two for 2 , etc.). 53 | - If `n > 9` , print Greater than 9. 54 | 55 | # Input Format 56 | 57 | The first line contains a single integer, `n`. 58 | 59 | # Constraints 60 | 61 | `1 <= n <= 9` 62 | 63 | # Output Format 64 | 65 | If `1 <=n <=9`, then print the lowercase English word corresponding to the number (e.g., one for 1 , two for 2 , etc.); otherwise, print Greater than 9 instead. 66 | 67 | # Sample Input 68 | 69 | 5 70 | 71 | # Sample Output 72 | 73 | five 74 | 75 | # Sample Input 01 76 | 77 | 8 78 | 79 | # Sample Output 01 80 | 81 | eight 82 | 83 | # Sample Input 02 84 | 85 | 44 86 | 87 | # Sample Output 02 88 | 89 | Greater than 9 90 | 91 | ```c 92 | #include 93 | #include 94 | #include 95 | #include 96 | #include 97 | #include 98 | #include 99 | #include 100 | #include 101 | 102 | char* readline(); 103 | 104 | 105 | 106 | int main() 107 | { 108 | char* n_endptr; 109 | char* n_str = readline(); 110 | int n = strtol(n_str, &n_endptr, 10); 111 | 112 | if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } 113 | 114 | // Write Your Code Here 115 | 116 | return 0; 117 | } 118 | 119 | char* readline() { 120 | size_t alloc_length = 1024; 121 | size_t data_length = 0; 122 | char* data = malloc(alloc_length); 123 | 124 | while (true) { 125 | char* cursor = data + data_length; 126 | char* line = fgets(cursor, alloc_length - data_length, stdin); 127 | 128 | if (!line) { break; } 129 | 130 | data_length += strlen(cursor); 131 | 132 | if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } 133 | 134 | size_t new_length = alloc_length << 1; 135 | data = realloc(data, new_length); 136 | 137 | if (!data) { break; } 138 | 139 | alloc_length = new_length; 140 | } 141 | 142 | if (data[data_length - 1] == '\n') { 143 | data[data_length - 1] = '\0'; 144 | } 145 | 146 | data = realloc(data, data_length); 147 | 148 | return data; 149 | } 150 | ``` 151 | -------------------------------------------------------------------------------- /src/suggestProfession.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char *suggestProfession(char name[]) 7 | { 8 | srand(time(NULL)); 9 | int choice = rand() % 5; 10 | 11 | static char professions[10][30] = {"Teacher", "Doctor", "Software Engineer", "Programmer", "Web developer", "Nursing", "Graphic Designer", "Entrepreneur"}; 12 | 13 | return professions[choice]; 14 | } 15 | char *suggestlanguage(char name) 16 | { 17 | srand(time(NULL)); 18 | int choice = rand() % 5; 19 | static char language[10][30] = {"Punjabi", "Pashto", "Balochi", "Urdu", "Balti", "Seraiki", "Sindhi", "Farsi", "English", "German"}; 20 | 21 | return language[choice]; 22 | } 23 | char suggestethnicities(char name) 24 | { 25 | srand(time(NULL)); 26 | int choice = rand() % 5; 27 | 28 | static char ethnicities[10][30] = {"Punjabi", "Pathan", "Baltistani", "Persian", "Hindustani", "Baloch", "Sindhi", "Seraiki"}; 29 | 30 | return ethnicities[choice]; 31 | } 32 | char suggestdiet(char name) 33 | { 34 | srand(time(NULL)); 35 | int choice = rand() % 5; 36 | 37 | static char diet[10][30] = {"Mediterranean", "Vegetarian", "Dash", "Flexitarian", "Ornish", "Pescatarian", "Dubrow"}; 38 | 39 | return diet[choice]; 40 | } 41 | char suggestdresscodes(char name) 42 | { 43 | srand(time(NULL)); 44 | int choice = rand() % 5; 45 | 46 | static char dresscodes[10][30] = {"Casual", "Smart casual", "Business casual", "Formal", "Festive", "Informal wear", "Suit", "Cocktail", "White tie", "Black tie"}; 47 | 48 | return dresscodes[choice]; 49 | } 50 | int suggestluckynumber(char name[]) 51 | 52 | { 53 | int hash = 0; 54 | 55 | for (int i = 0; name[i] != '\0'; i++) 56 | { 57 | hash += name[i]; 58 | } 59 | srand(hash); 60 | return (rand() % 19) + 1; 61 | } 62 | int main() 63 | { 64 | char name[50], fathername[50]; 65 | int age; 66 | 67 | printf("Enter your name: "); 68 | fgets(name, sizeof(name), stdin); 69 | name[strcspn(name, "\n")] = '\0'; 70 | 71 | printf("Enter your father name: "); 72 | fgets(fathername, sizeof(fathername), stdin); 73 | fathername[strcspn(fathername, "\n")] = '\0'; 74 | 75 | printf("Enter your age: "); 76 | scanf("%d", &age); 77 | 78 | srand(time(NULL)); 79 | 80 | char firstletter = name[0]; 81 | char personalitytraits; 82 | switch (toupper(firstletter)) 83 | { 84 | case 'A': 85 | case 'E': 86 | case 'I': 87 | case 'O': 88 | case 'U': 89 | personalitytraits = "outgoing", "optimistics", "creative"; 90 | break; 91 | case 'B': 92 | case 'F': 93 | case 'M': 94 | case 'K': 95 | case 'V': 96 | personalitytraits = "Practical", "reliable", "loyal"; 97 | break; 98 | case 'C': 99 | case 'P': 100 | case 'G': 101 | case 'S': 102 | case 'Q': 103 | personalitytraits = "Conscientiou", "analytical", "detailed-oriented"; 104 | break; 105 | case 'D': 106 | case 'H': 107 | case 'L': 108 | case 'R': 109 | case 'T': 110 | personalitytraits = "Decisive", "independent", "ambitious"; 111 | break; 112 | case 'N': 113 | case 'W': 114 | case 'Z': 115 | case 'J': 116 | case 'Y': 117 | personalitytraits = "Cooperative", "adaptable", "empathetic"; 118 | break; 119 | 120 | default: 121 | personalitytraits = "Unique and multifaceted"; 122 | } 123 | 124 | printf("-Profession: %s\n", suggestprofession(name)); 125 | printf("-Language: %s\n", suggestlanguage(name)); 126 | printf("-Diet: %s\n", suggestdiet(name)); 127 | printf("-Dresscodes: %s\n", suggestdresscodes(name)); 128 | printf("-Lucky Number: %d\n", suggestluckynumber(name)); 129 | 130 | char password[10]; 131 | for (int i = 0; i < sizeof(password) - 1; i++) 132 | { 133 | password[i] = rand() % 26 + 'a'; 134 | } 135 | password[sizeof(password) - 1] = '\0'; 136 | printf("Generated password: %s\n", password); 137 | 138 | return 0; 139 | } -------------------------------------------------------------------------------- /markdown/repetitiveStatements.md: -------------------------------------------------------------------------------- 1 | # Repetitive statements and execution flow for repetitive statements 2 | 3 | **Explanation of the topic below was generated using openai in response to the question: how to explain the need of repetitive statements in programming language to a beginner** 4 | 5 | Imagine you have a task that you need to repeat over and over again, like counting from 1 to 10. In programming, repetitive statements, often called loops, help us automate such tasks. Instead of writing the same code multiple times, we can use loops to execute a set of instructions repeatedly without having to duplicate the code. 6 | 7 | Loops allow us to save time and effort by letting the computer do the repetitive work for us. They are like a super helpful assistant that follows our instructions and performs the same action multiple times. 8 | 9 | For example, let's say you want to print the numbers from 1 to 10. Instead of writing ten separate print statements, you can use a loop to achieve the same result with just a few lines of code. The loop will iterate over a range of numbers, and each time it goes through the loop, it will execute the same set of instructions. 10 | 11 | By using loops, we can also process large amounts of data more efficiently. For instance, if we have a list of 100 names and we want to perform an action on each name, we can use a loop to iterate through the list and execute the action for each item. 12 | 13 | Loops come in different forms, but they all serve the purpose of repeating code. The two most common types of loops are the 'for' loop and the 'while' loop. The 'for' loop is typically used when we know the number of iterations in advance, while the 'while' loop is useful when we want to repeat a block of code until a certain condition is met. 14 | 15 | So, in summary, repetitive statements or loops in programming are essential because they allow us to automate tasks, save time, and process large amounts of data efficiently. They enable us to avoid writing duplicate code and make our programs more concise and powerful." 16 | 17 | Sample programs using for, while, and do while loops: 18 | 19 | - [for loop](../src/for.c) 20 | - [while loop](../src/while.c) 21 | - [do while loop](../src/dowhile.c) 22 | 23 | ## break and continue statements 24 | 25 | **Note: following explanation is generated by ChatGPT** 26 | In C, the `continue` and `break` statements are control flow statements used within loops to alter the flow of execution. Here's a breakdown of their applications: 27 | 28 | 1. `continue` statement: 29 | - The `continue` statement is used to skip the rest of the current iteration of a loop and proceed to the next iteration. 30 | - When encountered inside a loop (such as `for`, `while`, or `do-while`), the `continue` statement causes the program to immediately jump to the loop's next iteration. 31 | - It is particularly useful when you want to skip certain iterations of a loop based on certain conditions, without executing the remaining code in the loop for that iteration. 32 | - Example: 33 | 34 | ```c 35 | #include 36 | 37 | int main() { 38 | for (int i = 0; i < 5; i++) { 39 | if (i == 2) { 40 | // Skip iteration when i is 2 41 | continue; 42 | } 43 | printf("%d ", i); 44 | } 45 | return 0; 46 | } 47 | ``` 48 | Output: 49 | ``` 50 | 0 1 3 4 51 | ``` 52 | 53 | 2. `break` statement: 54 | - The `break` statement is used to terminate the execution of a loop prematurely. 55 | - When encountered inside a loop, the `break` statement causes the program to exit the loop immediately, regardless of the loop's condition. 56 | - It is commonly used when a certain condition is met and you want to exit the loop without completing all iterations. 57 | - Example: 58 | 59 | ```c 60 | #include 61 | 62 | int main() { 63 | int target = 5; 64 | int sum = 0; 65 | for (int i = 1; i <= 10; i++) { 66 | sum += i; 67 | if (sum >= target) { 68 | // Exit loop when sum becomes greater than or equal to target 69 | break; 70 | } 71 | } 72 | printf("Sum is: %d\n", sum); 73 | return 0; 74 | } 75 | ``` 76 | Output: 77 | ``` 78 | Sum is: 15 79 | ``` 80 | 81 | In summary, `continue` is used to skip the current iteration of a loop, while `break` is used to exit the loop prematurely. Both statements provide ways to control the flow of execution within loops and are essential for writing efficient and concise code. 82 | -------------------------------------------------------------------------------- /markdown/lab-manual.md: -------------------------------------------------------------------------------- 1 | # Laboratory Manual: Programming Fundamentals (C Language) 2 | 3 | ## Lab 1: Introduction to C Programming 4 | - **Aim:** To familiarize students with the basic structure of a C program and basic input/output operations. 5 | 6 | - **Exercises:** 7 | 1. Write a C program to display "Hello, World!" on the screen. 8 | 2. Write a program to take two numbers as input from the user and display their sum. 9 | 3. Write a program to find the area of a rectangle given its length and breadth. 10 | 11 | ## Lab 2: Variables, Data Types, and Operators 12 | - **Aim:** To understand variables, data types, and operators in C programming. 13 | 14 | - **Exercises:** 15 | 1. Write a program to declare and initialize variables of different data types (int, float, char) and display their values. 16 | 2. Write a program to perform arithmetic operations (+, -, \*, /, %) on two integers. 17 | 3. Write a program to convert temperature from Celsius to Fahrenheit. 18 | 19 | ## Lab 3: Control Structures - Decision Making 20 | - **Aim:** To understand decision-making structures in C programming (if, if-else, nested if). 21 | 22 | - **Exercises:** 23 | 1. Write a program to check whether a given number is even or odd. 24 | 2. Write a program to find the largest among three numbers. 25 | 3. Write a program to determine whether a year entered by the user is a leap year or not. 26 | 27 | ## Lab 4: Control Structures - Loops 28 | - **Aim:** To understand loop structures in C programming (for loop, while loop, do-while loop). 29 | 30 | - **Exercises:** 31 | 1. Write a program to display the multiplication table of a given number using a for loop. 32 | 2. Write a program to find the factorial of a number using a while loop. 33 | 3. Write a program to generate Fibonacci series up to a given number using a do-while loop. 34 | 35 | ## Lab 5: Arrays and Strings 36 | - **Aim:** To understand arrays and strings in C programming. 37 | 38 | - **Exercises:** 39 | 1. Write a program to find the sum of elements in an array. 40 | 2. Write a program to find the largest and smallest element in an array. 41 | 3. Write a program to reverse a string. 42 | 43 | ## Lab 6: Functions 44 | - **Aim:** To understand user-defined functions in C programming. 45 | 46 | - **Exercises:** 47 | 1. Write a program to find the factorial of a number using a user-defined function. 48 | 2. Write a program to check whether a number is prime or not using a user-defined function. 49 | 3. Write a program to find the sum of digits of a number using a recursive function. 50 | 51 | ## Lab 7: Pointers and Dynamic Memory Allocation 52 | - **Aim:** To understand pointers and dynamic memory allocation in C programming. 53 | 54 | - **Exercises:** 55 | 1. Write a program to demonstrate basic pointer operations (declaration, initialization, dereferencing). 56 | 2. Write a program to swap two numbers using pointers. 57 | 3. Write a program to dynamically allocate memory for an integer array and display its elements. 58 | 59 | ## Lab 8: Structures and File Handling 60 | - **Aim:** To understand structures and file handling in C programming. 61 | 62 | - **Exercises:** 63 | 1. Write a program to define a structure representing a student with attributes like roll number, name, and marks in three subjects. 64 | 2. Write a program to read and write student records to a file. 65 | 3. Write a program to search for a student record by roll number from a file. 66 | 67 | ## Lab 9: Preprocessor Directives and Macros 68 | - **Aim:** To understand preprocessor directives and macros in C programming. 69 | 70 | - **Exercises:** 71 | 1. Write a program to demonstrate the use of `#define` directive to define constants. 72 | 2. Write a program to demonstrate conditional compilation using `#ifdef`, `#ifndef`, and `#endif` directives. 73 | 3. Write a program to demonstrate the use of macros for performing mathematical operations. 74 | 75 | ## Lab 10: Advanced Concepts 76 | - **Aim:** To explore advanced concepts in C programming. 77 | 78 | - **Exercises:** 79 | 1. Write a program to implement a stack data structure using arrays. 80 | 2. Write a program to implement a linked list data structure. 81 | 3. Write a program to implement basic sorting algorithms (e.g., bubble sort, insertion sort). 82 | 83 | ## Lab 11: Project Work 84 | - **Aim:** To work on a small project that integrates various concepts learned throughout the course. 85 | 86 | - **Project Ideas:** 87 | - Implement a simple calculator application. 88 | - Develop a student management system. 89 | - Create a file encryption/decryption tool. 90 | 91 | --- 92 | 93 | *Note: The laboratory manual is designed to provide hands-on practice and reinforce theoretical concepts taught in the classroom. Each lab session should be accompanied by a detailed explanation of concepts, followed by practical exercises and discussions.* 94 | -------------------------------------------------------------------------------- /markdown/problemSolving.md: -------------------------------------------------------------------------------- 1 | # Introduction to Problem Solving 2 | 3 | - Humans possess the remarkable ability to solve complex problems. 4 | - This unique capability is distinguished by 5 | + the ability to think critically, 6 | + recognize patterns, and 7 | + adapt solutions to new challenges. 8 | - Typically, problem-solving involves a methodical approach that includes: 9 | 10 | - **Decomposition:** Breaking down a large problem into smaller, more manageable subproblems. For example, organizing a large project into individual tasks allows for better focus and efficiency. 11 | 12 | - **Abstraction:** Focusing on the essential aspects of the problem while ignoring irrelevant details. This helps simplify complexity and allows for clearer solutions. 13 | 14 | - **Pattern Recognition:** Identifying recurring patterns or similarities to previously solved problems. This enables the application of existing knowledge to new situations. 15 | 16 | For instance, consider the evolution of number systems: 17 | 18 | **Early Systems:** Systems like Roman numerals (IV for 4, V for 5) were developed to represent quantities. These systems were innovative for their time but had limitations. 19 | 20 | **Limitation:** Performing arithmetic operations, such as adding two large numbers using Roman numerals (e.g., DLIII + CCCCLXXXVII), was highly cumbersome and prone to errors. 21 | 22 | **Improved Systems:** The development of Arabic numerals (1, 2, 3, etc.) significantly simplified calculations, making arithmetic operations faster and more accurate. 23 | 24 | - This example highlights how limitations in existing solutions can drive the development of better alternatives, showcasing human ingenuity in problem-solving. 25 | 26 | ## Key Aspects of Problem Solving: 27 | 28 | - **Problem Understanding:** 29 | 30 | Clearly defining the problem is crucial. Without a clear understanding, solutions may be ineffective or misguided. 31 | Problems can be expressed through words, mathematical symbols, or other representations, depending on the context. 32 | The accuracy of problem expression directly impacts the quality of the solution. For instance, a well-defined problem in software development ensures that the resulting program meets user requirements. 33 | 34 | - **Finding Solutions:** 35 | 36 | **Algorithmic Thinking:** Developing step-by-step procedures (algorithms) to solve the problem systematically.Common strategies include: 37 | 38 | **Brute Force:** Exploring all possible solutions to find the correct one. While simple to implement, this method is often inefficient for large problems. 39 | 40 | **Divide and Conquer:** Breaking the problem into smaller subproblems, solving each independently, and combining their results. This approach is particularly effective in algorithms like merge sort and quicksort. 41 | 42 | **Dynamic Programming:** Solving complex problems by breaking them down into simpler overlapping subproblems and storing the results of solved subproblems to avoid redundant computations. Examples include the Fibonacci sequence and shortest path algorithms. 43 | 44 | **Heuristics:** Employing rules of thumb or educated guesses to find approximate solutions. These methods are particularly useful when an exact solution is computationally challenging or unnecessary. 45 | 46 | ## The Role of Computers in Problem Solving: 47 | 48 | While humans are intelligent, they have limitations: 49 | 50 | - **Computational Speed and Accuracy:** Computers excel at performing complex calculations with speed and precision, far surpassing human capabilities in tasks like cryptographic analysis or simulations. 51 | 52 | - **Handling Large Datasets:** Computers can efficiently process and analyze vast amounts of data, uncovering patterns and insights that would be impossible to detect manually. 53 | 54 | ## The Role of Programming Languages: 55 | 56 | To instruct computers to solve problems, we use programming languages: 57 | 58 | **Communication:** Programming languages provide a structured way to communicate instructions to computers, ensuring clarity and precision in task execution. 59 | 60 | **Problem-Solving Tools:** They enable us to implement algorithms, manipulate data, and create software solutions tailored to specific problems. 61 | 62 | **Examples of Programming Languages:** 63 | 64 | **General-purpose:** C++, Java, Python. These languages are versatile and applicable to a wide range of problems, from web development to machine learning. 65 | 66 | **Domain-specific:** Fortran (scientific computing), MATLAB (numerical computation). These are optimized for specific fields, making them highly efficient for specialized tasks. 67 | 68 | ## Key Takeaways: 69 | 70 | - Problem-solving is an iterative process that often involves trial and error, refinement, and adaptation. 71 | 72 | - Effective problem-solving requires a combination of critical thinking, creativity, and the application of appropriate techniques tailored to the problem at hand. 73 | 74 | - Computers and programming languages empower us to solve complex problems efficiently and effectively, transforming challenges into opportunities for innovation. 75 | 76 | -------------------------------------------------------------------------------- /src/array_sizeof.c: -------------------------------------------------------------------------------- 1 | /* 2 | Array: is a data structure. 3 | It allows to store multiple values 4 | of a single type. 5 | Values are stored in contiguous memory 6 | locations. 7 | */ 8 | 9 | #include 10 | 11 | #define SIZE 10 12 | 13 | int main(void) 14 | { 15 | int array[SIZE]; 16 | 17 | int count; 18 | size_t array_length; 19 | printf("The size of array in bytes can be calculated using sizeof operator = %zu\n", sizeof(array)); 20 | printf("The number of elements can be calculated using sizeof operator as well sizeof(array)/sizeof(array[0]) = %zu\n", sizeof(array)/sizeof(array[0])); 21 | printf("using preprocessor define directive like #define SIZE 10 is another approach %d\n", SIZE); 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | return 0; 30 | } 31 | 32 | /* 33 | Question: 34 | Why sizeof is called unary operator when its syntax is similar to a function? 35 | 36 | ChatGPT response: 37 | 38 | You're right; the terminology can sometimes be misleading. While `sizeof` does resemble a function call in its syntax, it's actually classified as a unary operator because it operates on a single operand. Unary operators typically take one operand, perform an operation on it, and return a result. 39 | 40 | Although `sizeof` appears to be a function, it's treated specially by the compiler. Unlike functions, `sizeof` is evaluated at compile-time rather than run-time. It determines the size of its operand (which can be a type, an expression, or a variable) and returns that size as a compile-time constant. 41 | 42 | So, even though it looks like a function call, the fact that it's resolved at compile-time and operates on a single operand makes it more akin to a unary operator. 43 | 44 | ==================== 45 | Question: Why using sizeof makes more sense instead of using a literal numeric constant when dealing with array length? 46 | 47 | 48 | ChatGPT response: 49 | 50 | Using `sizeof` to determine the length of an array makes code more robust and maintainable for several reasons: 51 | 52 | 1. **Dynamic Sizing**: If the size of the array changes in the future, you won't need to manually update the size in multiple places throughout your code. `sizeof` will always return the correct size of the array regardless of changes made to it. 53 | 54 | 2. **Avoiding Magic Numbers**: Using numeric constants can lead to what's known as "magic numbers" in code—hard-coded numbers that lack clear meaning. Using `sizeof` provides a more semantic and self-documenting way of determining the size of the array. 55 | 56 | 3. **Code Consistency**: If you're using `sizeof` consistently throughout your codebase to determine array sizes, it provides a consistent and standardized approach, making the code easier to understand for others and for future maintenance. 57 | 58 | 4. **Applicable to All Array Types**: `sizeof` works with any type of array, whether it's an array of integers, characters, structures, or any other type. This means you can use it universally across your codebase without worrying about type-specific differences. 59 | 60 | 5. **No Risk of Error**: Manually counting the elements of an array can introduce errors, especially if the array is large or if changes are made to it later on. `sizeof` provides a reliable and error-free way of determining the size of the array. 61 | 62 | Overall, using `sizeof` to determine the length of an array promotes code clarity, consistency, and maintainability, making it the preferred approach in most scenarios. 63 | 64 | ====================== 65 | Question: How does using define directive help in the above context? 66 | 67 | ChatGPT response: 68 | Using the `#define` directive can be another approach to handling array lengths, but it has some differences compared to using `sizeof`. 69 | 70 | Here's how you might use `#define` to define the length of an array: 71 | 72 | ```c 73 | #include 74 | 75 | #define ARRAY_LENGTH 5 76 | 77 | int main() { 78 | int arr[ARRAY_LENGTH] = {1, 2, 3, 4, 5}; 79 | 80 | printf("Size of arr: %d\n", ARRAY_LENGTH); 81 | 82 | return 0; 83 | } 84 | ``` 85 | 86 | Using `#define` in this way provides a named constant `ARRAY_LENGTH` that represents the length of the array. This approach shares some similarities with using `sizeof`: 87 | 88 | 1. **Avoiding Magic Numbers**: Like `sizeof`, using a `#define` constant helps avoid "magic numbers" in your code by giving a clear, meaningful name to the array length. 89 | 90 | 2. **Consistency and Maintainability**: By using `#define`, you can define the array length once and use the constant throughout your code, promoting consistency and making maintenance easier if the length needs to change. 91 | 92 | However, there are some differences: 93 | 94 | 1. **Compile-Time vs. Run-Time**: The value of a `#define` constant is replaced by the preprocessor before compilation, whereas `sizeof` is evaluated at compile-time. This means `sizeof` can handle variable-length arrays (VLAs) and dynamically allocated arrays, while a `#define` constant cannot. 95 | 96 | 2. **Type Safety**: With `#define`, you don't get type checking. You could accidentally use the constant in a way that doesn't make sense, leading to errors that might be caught with `sizeof`. 97 | 98 | In summary, while `#define` constants can be useful for defining array lengths in certain cases, they lack some of the benefits and flexibility of using `sizeof`, particularly when dealing with variable-length or dynamically allocated arrays. For most cases where the array length is known at compile-time and doesn't change, `#define` can be a reasonable choice, but `sizeof` is generally more versatile and safer. 99 | 100 | 101 | * 102 | */ 103 | -------------------------------------------------------------------------------- /markdown/operators.md: -------------------------------------------------------------------------------- 1 | # Operators 2 | 3 | - An operator is a symbol that operates on one or more values or variables. 4 | - e.g + is an operator which performs addition. 5 | - C provides a wide range of operators for performing various tasks. 6 | 7 | ## Arithmetic Operators 8 | 9 | - arithmetic operators perform mathematical operations such as addition, subtraction, multiplication, division etc. 10 | 11 | - Assume variables `num1` holds the value `20` and `num2` has holds the value `3` 12 | - Following table lists arithmetic operators, their description and sample usage: 13 | 14 | | Operator | Description | Example | 15 | |:--------:|:------------------------------------------------------------:|:----------:| 16 | | + | Adds two operands. | A + B = 23 | 17 | | − | Subtracts second operand from the first. | A − B = 17 | 18 | | * | Multiplies both operands. | A * B = 60 | 19 | | / | Divides numerator by de-numerator. | A / B = 6 | 20 | | % | Modulus Operator and remainder of after an integer division. | A % B = 2 | 21 | 22 | - changing the position of operands (i.e. A and B) may change the result in some cases 23 | - e.g. `A - B = 17` but `B - A = -17`similarly `/` and `%` will give different values when the position of `A` and `B` is changed. 24 | - operators which operate on two operands are known as `binary operators` 25 | 26 | [link to c program on arithmetic operators](../src/arithmeticOperators.c) 27 | 28 | ## Arithmetic Assignment Operators 29 | 30 | - C also provides arithmetic assignment operator which provide a concise way of writing expressions involving arithmetic and assignment. 31 | - e.g. if `a=4` then `a = a + 2` (which means add 2 to `a` and assign the result to `a`) may be written as `a+=2`, note that `a` is not repeated. 32 | - `+=, -=, *=, /=` and `%=` are all arithmetic assignment operators 33 | 34 | [link to c program on arithmetic assignment operators](../src/arithmeticAssignmentOperators.c) 35 | 36 | 37 | ## Relational Operators 38 | 39 | | Operator | Description | Example | 40 | |:--------:|:------------------------------------------------------------------------------------------------------------------------------------:|:---------------------:| 41 | | == | Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A == B) is not true. | 42 | | != | Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. | (A != B) is true. | 43 | | > | Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. | (A > B) is not true. | 44 | | < | Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. | (A < B) is true. | 45 | | >= | Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. | (A >= B) is not true. | 46 | | <= | Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. | (A <= B) is true. | 47 | 48 | 49 | [link to c program on relational operators](../src/relationalOperators.c) 50 | 51 | ## Logical Operators 52 | 53 | | Operator | Description | Example | 54 | |:--------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------:|:-------------------:| 55 | | && | Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. | (A && B) is false. | 56 | | \|\| | Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. | (A \|\| B) is true. | 57 | | ! | Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. | !(A && B) is true. | 58 | 59 | ## Bitwise Operators 60 | 61 | Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for `&, |,` and `^` is as follows: 62 | 63 | | p | q | p & q | p \| q | p ^ q | 64 | |:-:|:-:|:-----:|:------:|:-----:| 65 | | 0 | 0 | 0 | 0 | 0 | 66 | | 0 | 1 | 0 | 1 | 1 | 67 | | 1 | 1 | 1 | 1 | 0 | 68 | | 1 | 0 | 0 | 1 | 1 | 69 | 70 | 71 | - Assume `A = 60` and `B = 13`, their binary equivalent is `A = 0011 1100`, `B = 0000 1101` 72 | - The following table lists the bitwise operators supported by C 73 | 74 | | Operator | Description | Example | 75 | |:--------:|:-------------------------------------------------------------------------------------------------------------------------:|:------------------------------:| 76 | | & | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) = 12, i.e., 0000 1100 | 77 | | \| | Binary OR Operator copies a bit if it exists in either operand. | (A \| B) = 61, i.e., 0011 1101 | 78 | | ^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) = 49, i.e., 0011 0001 | 79 | | ~ | Binary One's Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) = ~(60), i.e,. -0111101 | 80 | | << | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 = 240 i.e., 1111 0000 | 81 | | >> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 = 15 i.e., 0000 1111 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /markdown/conditionalStatements.md: -------------------------------------------------------------------------------- 1 | # Conditional Statements and Execution Flow for Conditional Statements 2 | 3 | - Conditionals or conditional statements are programming language commands for handling decisions. 4 | - e.g. to determine if a student's grade is greater than or equal to 50 and whether the program should print "Congratulations! You passed" 5 | 6 | ## Simple if statement 7 | 8 | A simple if statement is written as shown below: 9 | 10 | ``` 11 | 12 | if(grade >= 50) 13 | { 14 | printf("\n Congratulations! You passed"); 15 | } 16 | 17 | ``` 18 | 19 | - Suppose the value in grade is 60, then the condition grade >= 50 will evaluate to true, and the message **Congratulations! You passed** will be displayed 20 | - However if the value in grade is 40, then the condition grade >= 50 will evaluate to false, and the message will not be displayed. 21 | 22 | - [See this program for a complete example of using simple if statement](../src/simpleif.c) 23 | 24 | ## if else 25 | 26 | - if else selection statement allows to specify different actions to be performed when the condition is true and when it is false. 27 | 28 | - e.g. the following code will display message **Congratulations! You passed** if the condition is true, otherwise it will display message **Failed**. 29 | 30 | 31 | ``` 32 | if(grade >= 50) 33 | { 34 | puts("Congratulations! You passed"); 35 | } 36 | else 37 | { 38 | puts("Failed"); 39 | } 40 | ``` 41 | 42 | ### Flow chart single selection if vs if else 43 | 44 | ![Flow chart comparing if vs if else](../figs/conditionals.png "Flow chart compaing if vs if else") 45 | 46 | **Note: following explanation is AI generated** 47 | 48 | ## else if 49 | 50 | In C, the "else if" construct is used when we have multiple conditions that we want to check in a sequential manner. It allows us to test multiple conditions and execute different blocks of code based on the outcome of those conditions. 51 | 52 | Here's how the "else if" construct works: 53 | 54 | 1. We start with an "if" statement to test the first condition. If the condition is true, the code block associated with that "if" statement is executed, and the program moves on to the next statement after the "if-else" construct. 55 | 56 | 2. If the condition of the first "if" statement is false, the program moves to the next "else if" statement. It checks the condition associated with this "else if" statement. If the condition is true, the code block associated with that "else if" statement is executed, and the program again moves on to the next statement after the "if-else" construct. 57 | 58 | 3. If the condition of the current "else if" statement is false, the program moves to the next "else if" statement, and the process repeats. It checks the condition associated with this new "else if" statement, and if it is true, the code block associated with that "else if" statement is executed. 59 | 60 | 4. This process continues until either one of the conditions is true, or there are no more "else if" statements to check. If none of the conditions in the "if" and "else if" statements are true, the code block associated with the final "else" statement (if present) will be executed. 61 | 62 | Here's an example to illustrate the "else if" construct: 63 | 64 | ```c 65 | int num = 10; 66 | 67 | if (num > 10) { 68 | printf("The number is greater than 10.\n"); 69 | } 70 | else if (num < 10) { 71 | printf("The number is less than 10.\n"); 72 | } 73 | else { 74 | printf("The number is equal to 10.\n"); 75 | } 76 | ``` 77 | 78 | In this example, the program first checks if `num` is greater than 10. Since it's not, the first condition is false, and the program moves to the next "else if" statement. Here, it checks if `num` is less than 10. Again, this condition is false. Finally, the program reaches the "else" statement, and since none of the previous conditions were true, it executes the code block associated with the "else" statement, which prints "The number is equal to 10." 79 | 80 | The "else if" construct allows us to handle multiple conditions and make decisions based on the outcome of those conditions, providing more flexibility and control over the program's behavior. 81 | 82 | 83 | **Note: following explanation is AI generated** 84 | 85 | ## Switch statement 86 | 87 | In C, the switch statement is a control flow statement that allows you to compare the value of a variable or expression against multiple cases and execute different blocks of code based on the matching case. 88 | 89 | Here's how the switch statement works: 90 | 91 | 1. You start with the keyword `switch` followed by the variable or expression you want to compare. This variable or expression is often called the "switch expression" or "switch condition." 92 | 93 | 2. After the switch expression, you enclose the case blocks within curly braces `{}`. Each case block represents a specific value or set of values that you want to compare against the switch expression. 94 | 95 | 3. Inside each case block, you specify the value or values that you want to match with the switch expression. If the switch expression matches a case value, the code block associated with that case is executed. 96 | 97 | 4. After executing the code block of a matched case, the program "falls through" to the next case block unless you include a `break` statement. The `break` statement is used to exit the switch statement and continue execution after the switch block. 98 | 99 | 5. Optionally, you can include a `default` case at the end of the switch statement. The code block associated with the `default` case will be executed if none of the previous cases match the switch expression. 100 | 101 | Here's an example to illustrate the switch statement: 102 | 103 | ```c 104 | int day = 3; 105 | 106 | switch (day) { 107 | case 1: 108 | printf("Monday\n"); 109 | break; 110 | case 2: 111 | printf("Tuesday\n"); 112 | break; 113 | case 3: 114 | printf("Wednesday\n"); 115 | break; 116 | case 4: 117 | printf("Thursday\n"); 118 | break; 119 | case 5: 120 | printf("Friday\n"); 121 | break; 122 | default: 123 | printf("Weekend\n"); 124 | break; 125 | } 126 | ``` 127 | 128 | In this example, the switch expression is `day`, which has a value of 3. The code checks each case block one by one. When it finds a match, it executes the corresponding code block. In this case, the code block associated with `case 3` is executed, which prints "Wednesday" to the console. 129 | 130 | If the `break` statement were missing after each code block, the program would continue executing the code in the subsequent case blocks until it encounters a `break` statement or reaches the end of the switch statement. 131 | 132 | If the value of `day` didn't match any of the cases, the code block associated with the `default` case would be executed, printing "Weekend" to the console. 133 | 134 | The switch statement is useful when you have multiple cases to compare against a single variable or expression and want to execute different blocks of code based on the matching case. It provides a concise and structured way to handle such scenarios. 135 | 136 | ## Conditional operator ?: | Ternary operator 137 | 138 | - C provides the Conditional operator `?:` which is closely related to the if else statement 139 | - it takes three operands 140 | - the 1st operand is the condition 141 | - 2nd operand is the value if the condition is true 142 | - 3rd operand is the value if the condition is false 143 | - e.g. `2 < 3 ? "two is less than three" : "two is not less than three"` 144 | - [C program using ternary operator](../src/ternaryoperator.c) 145 | 146 | 147 | -------------------------------------------------------------------------------- /markdown/von-neumann.md: -------------------------------------------------------------------------------- 1 | **Note: images and contents presented here have been taken from wikipedia.org. Questions presented here were responded by chatGPT** 2 | 3 | # John Von-Neumann 4 | 5 | - Before we talk about the architecture let us know a bit about Von-Neumann. 6 | - [Von-Neumann](https://en.wikipedia.org/wiki/John_von_Neumann ) is regarded as the foremost mathematician of his time. 7 | - He made major contributions to many fields, including mathematics, physics, economics, computing, and statistics. 8 | - When he was six years old he could divide two 8 digit numbers in his head!!! 9 | 10 | ![John von Nuemann](../figs/JohnvonNeumann.gif "John von Neumann") 11 | 12 | 13 | ## Von-Neumann Architecture 14 | 15 | - Also known as Princeton architecture is a computer architecture based on a 1945 description by John von Neumann. 16 | - The Von-Neumann architecture for an electronic digital computer has following components: 17 | 18 | 1. A processing unit that contains arithmetic logic unit and processor registers 19 | 2. A control unit that contains an instruction register and program counter 20 | 3. Memory that stores both data and instructions 21 | 4. External mass storage 22 | 5. Input and output mechanisms. 23 | 24 | ![Von-Neumann Architecture](../figs/Von_Neumann_Architecture.png "Von-Neumann Architecture") 25 | 26 | - This architecture refers to any stored-program computer in which an instruction fetch and a data operation cannot occur at the same time because they share a common bus. 27 | 28 | 29 | ## Related topics 30 | 31 | - Harvard architecture has one dedicated set of address and data buses for reading and writing to memory and another set of address and data buses to fetch instructions 32 | 33 | ![Harvard architecture](../figs/Harvard_architecture.png "Harvard architecture") 34 | 35 | **Question: Why Von Neumann architecture is significant?** 36 | 37 | **Response:** 38 | 39 | Von Neumann architecture is significant for several reasons: 40 | 41 | 1. **Foundation of Modern Computing**: It laid the groundwork for the design of modern computers. This architecture separates the CPU, memory, and input/output devices, allowing for the execution of stored program instructions. This concept is fundamental to all general-purpose computers today. 42 | 43 | 2. **Programmability**: Von Neumann architecture introduced the concept of stored-program computers, where both data and instructions are stored in the same memory. This allows for flexibility in programming and executing various tasks without the need for hardware modifications. 44 | 45 | 3. **Efficiency**: By storing instructions in memory, the CPU can fetch and execute them sequentially, making the operation more efficient compared to earlier designs where instructions were hardwired. This architecture facilitates faster computation and easier modification of programs. 46 | 47 | 4. **Versatility**: Von Neumann architecture allows for the development of versatile and programmable computers capable of performing a wide range of tasks. It's not limited to specific applications and can be adapted for various purposes through software programming. 48 | 49 | 5. **Standardization**: The Von Neumann architecture provided a standardized model for computer design, leading to compatibility and interoperability among different computer systems. This standardization has been crucial for the widespread adoption and evolution of computing technology. 50 | 51 | Overall, the Von Neumann architecture forms the basis of modern computing systems, enabling the development of powerful, programmable, and versatile machines that have revolutionized almost every aspect of our lives. 52 | 53 | 54 | 55 | **Question: Which architecture computers followed before Von Neumann Architecture?** 56 | 57 | **Response:** 58 | 59 | Before the Von Neumann architecture, computers followed various architectures, including: 60 | 61 | 1. **Harvard Architecture**: In the Harvard architecture, separate memory units are used to store program instructions and data. This architecture allows for simultaneous access to both instructions and data, which can enhance performance in certain applications. However, it can be more complex to implement compared to the Von Neumann architecture. 62 | 63 | 2. **Fixed-Program Computers**: Early computers, such as the ENIAC (Electronic Numerical Integrator and Computer), were fixed-program computers. They were designed to perform specific tasks and were not programmable in the way modern computers are. These computers had their instructions hardwired into their circuitry and were not capable of storing and executing general-purpose programs. 64 | 65 | 3. **Stored-Program Computers (Pre-Von Neumann)**: There were some early attempts at stored-program computers before the Von Neumann architecture became predominant. For example, the Manchester Baby (Small-Scale Experimental Machine), developed in the late 1940s, demonstrated the concept of storing both instructions and data in memory. However, these early stored-program computers lacked the full architectural features and principles that define the Von Neumann architecture. 66 | 67 | 4. **Other Experimental Architectures**: Various experimental architectures were explored before the Von Neumann architecture became standardized. These included different ways of organizing memory, processing units, and input/output mechanisms. Many of these early architectures were not as efficient or versatile as the Von Neumann architecture. 68 | 69 | Overall, the Von Neumann architecture emerged as the most influential and widely adopted architecture due to its simplicity, efficiency, and flexibility, but before its dominance, several alternative architectures were explored and implemented in early computer designs. 70 | 71 | 72 | **Question: What does the term architecture mean when used in the context of computers?** 73 | 74 | **Response:** 75 | 76 | In the context of computers, "architecture" refers to the fundamental design principles and organization of a computer system. It encompasses the structure and arrangement of its components, including the CPU (Central Processing Unit), memory, input/output devices, and the interconnections between them. 77 | 78 | Computer architecture defines how data is processed, stored, and transferred within the system. It includes specifications such as the instruction set architecture (ISA), which outlines the set of instructions that the CPU can execute, as well as the organization of memory, addressing modes, and input/output mechanisms. 79 | 80 | Computer architects design and optimize computer systems to meet specific performance, power consumption, cost, and reliability requirements. Different architectures can vary significantly in terms of their complexity, performance characteristics, and suitability for specific applications. 81 | 82 | Key aspects of computer architecture include: 83 | 84 | 1. **Instruction Set Architecture (ISA)**: Defines the set of instructions that the CPU can execute and the format of these instructions. 85 | 86 | 2. **Memory Hierarchy**: Organizes memory into different levels, such as registers, cache, main memory (RAM), and secondary storage (disk or SSD), to optimize performance and cost. 87 | 88 | 3. **CPU Organization**: Specifies the structure of the CPU, including the number and type of execution units, pipelining, and caching mechanisms. 89 | 90 | 4. **Input/Output System**: Describes how data is transferred between the computer and external devices, including interfaces, protocols, and controllers. 91 | 92 | 5. **Parallelism and Concurrency**: Addresses how multiple tasks or instructions can be executed simultaneously to improve performance, including concepts such as multi-core processors, vector processing, and parallel computing architectures. 93 | 94 | Computer architecture is a foundational concept in computer science and engineering, shaping the design and development of hardware systems and influencing the performance and capabilities of computing devices. 95 | 96 | --------------------------------------------------------------------------------