CHAPTER-4 C PROGRAMMING FOR PROBLEM-SOLVING Sayooj Devadas K C was developed at Bell Labs by Dennis Ritchie between the years 1972 and 1973. C is one of the oldest general purpose programming languages of all time and it was developed to construct utilities running on Unix and was applied to re-implement the kernel of the Unix operating system. 20XX 2 Advantages of C Language : •Simple: easy to learn , offer structural approach to solve problems •Portable: C programs can be written on one platform and can be executed in the same way on another operating system. C is a machine-independent language. •Structured programming language: C provides different functions that enable us to break the code into small parts, that is why C programs are easy to understand and modify. Functions also offer code reusability. •Fast and Efficient: The compilation and execution time of the C language is also fast. 20XX 3 C Python Low-level language, closer to machine language High-level language, further from machine language Statically-typed, requires explicit variable declaration Dynamically-typed, variables do not need to be declared beforehand Prioritizes performance and control Prioritizes readability and ease of use Used for system programming, embedded systems, and performance-critical applications Used for general-purpose programming, scripting, and data analysis Procedural Oriented programming language Object Oriented programming language Uses compiler Uses Interpreter 20XX 4 C BASIC COMMANDS: #include <stdio.h> It is a preprocessor command which consists of a standard input output header file(stdio.h) before compiling a C program. int main() The main function from where execution of any C program starts. { Indicates the beginning of the main function. } The function or method block is closed with these curly braces. /*_some_comments_*/ Any content inside “/* */” will not be used for compilation and execution. printf The output is printed to the console screen using this C 20XX 5 return This C function returns 0 after terminating the C programme or main function. Scanf The user data is taken from the usual console terminal window using this C function. (similar to input() in python) // Used for ingle line comments, /*_some_comments_*/ Any content inside “/* */” will not be used for compilation and execution. printf The output is printed to the console screen using this C return This C function returns 0 after terminating the C programme or main function. 20XX 6 HEADER FILES IN C • Header files are external libraries. - By adding header files to your code, you get additional functionality that you can use in your programs without having to write the code from scratch. • #include is a preprocessor command that tells the C compiler to include a file. • The stdio.h header file stands for standard input-output. It contains function definitions for input and output operations 20XX 7 SIMPLE C PROGRAM(HELLO WORLD PROGRAM) #include <stdio.h> int main (void) { printf("\n Hello World \n"); return 0; } 20XX Pitch deck title 8 WHAT IS THE MAIN() FUNCTION IN C • “ int main(void) { …} ’’ is the main function and starting point of every C program. • It is the first thing that is called when the program is executed. The int keyword in “int main(void) { .. }” indicates the return value of the main() function. Anything inside the curly braces, {}, is considered the body of the function • • 20XX We need to save the file with a `.c` extension, or it won’t be a valid C file. 20XX Pitch deck title 10 WHAT IS SEMICOLON ‘;’ IN C • The semicolon, ;, terminates the statement. • All statements need to end with a semicolon in C, as it identifies the end of the statement. • You can think of a semicolon similar to how a full stop/period ends a sentence. 20XX 11 EXAMPLE OF SYNTAX ERROR IN C #include <stdio.h> void main() { var = 5; // we did not declare the data type of variable printf("The variable is: %d", var); } 20XX 12 output: error: 'var' undeclared (first use in this function) 20XX 13 DATA TYPES IN C • Data types used in C language declare various types of functions or variables in a program. • Based on the type of variable present in a program, we determine the space that it occupies in storage • A data type specifies the type of data that a variable can store such as integer, floating, character, etc. 20XX 14 20XX 15 Relational Operators •Relational operators are binary operators that evaluate the truthhood or falsehood of a relationship between two arguments and produce a value of true ( 1 ) or false ( 0 ) as a result. 20XX 16 20XX 17 Logical Operators • Logical operators are used to combine and evaluate boolean expressions, generally in combination with the relational operators we discussed in previously. 20XX 18 20XX Pitch deck title 19 Example: To determine whether x is between 5.0 and 10.0: • INCORRECT: 5.0 < x < 10.0 • CORRECT: 5.0 < x && x < 10.0 20XX 20 Example: Finding Leap year Leap year occurs when the current year is divisible by 4, but NOT when the year is divisible by 100, UNLESS the year is also divisible by 400 int year; bool leap_year; leap_year = ( ( ( ( year % 4 ) == 0 ) && ( ( year % 100 ) != 0 ) ) || ( ( year % 400 ) == 0 ) ); // Or equivalently: leap_year = !( year % 4 ) && year % 100 || !( year % 400 ); 20XX 21 printf() function printf ( "formatted_string", arguments_list); #include <stdio.h> int main() { printf("Hello world!"); return 0; } 20XX 22 Specifier It is the character that denotes the type of data. Some commonly used specifiers are: •%d: for printing integers •%f: for printing floating-point numbers •%c: for printing characters •%s: for printing strings 20XX 23 #include <stdio.h> int main() { int num1 = 99; int num2 = 1; printf("The sum of %d and %d is %d\n", num1, num2, num1 + num2); return 0; } 20XX 24 if-else •"if" blocks and "if-else" blocks are used to make decisions, and to optionally execute certain code. •The general syntax of the if-else structure is as follows: if( condition ) true_block else false_block 20XX 25 • Example: if( x < 0.0 ) { printf( "Error - The x coordinate cannot be negative. ( x = %f ) \n", x ); exit( -1 ); } 20XX 26 20XX 27 20XX 28 FOR LOOP for (initializationStatement; testExpression; updateStatement) { // statements inside the body of loop } 20XX Pitch deck title 29 • The initialization statement is executed only once. • Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated. • However, if the test expression is evaluated to true, statements inside the body of the for loop are executed, and the update expression is updated. • Again the test expression is evaluated. • This process goes on until the test expression is false. When the test expression is false, the loop terminates. 20XX 30 COMPARISON BETWEEN PYTHON 20XX Pitch deck title 31 BREAK IN C • break statement is used to exit a loop (for, while or do-while loop) or a switch statement immediately, without waiting for the loop or switch to finish its normal execution cycle. • Syntax : • break; 20XX 32 CONTINUE IN C • Continue statement in C is used within looping constructs (for, while & do-while loops). When the continue statement is encountered, the current iteration of the loop is terminated immediately, and the loop’s controlling expression is reevaluated to determine if the loop should continue with the next iteration. • Syntax : • continue; 20XX 33 EXAMPLE: PROGRAM THAT PRINTS EVEN NUMBERS BETWEEN 1 AND 50. #include <stdio.h> int main() { int i; printf("Printing even numbers between 1 and 50:\n"); for (i = 1; i <= 50; i++) { if (i % 2 != 0) { continue; // Skip odd numbers } printf("%d\n", i); } return 0; } 20XX Pitch deck title 34 USER-DEFINED FUNCTIONS Syntax : returnType functionName (parameter1, parameter2,...) { // function body } // function declaration void hello() { printf("Hello World!"); } In the above example, •the name of the function is hello() •the return type of the function is void •the empty parentheses mean it doesn't have any parameters •the function body is written inside {} 20XX 36 int main() { // calling a function hello(); } Calling a function • When a program calls a function, program control is transferred to the called function. • A called function performs defined task and when it's return statement is executed, it returns program control back to main program. • To call a function, we need to pass the requirement parameters along with function name, and if function returns a value, then we can store returned value. 20XX 37 Function Parameters void printnum(int a) { printf("%d ", a); } int main() { int a = 7; // calling the function // a is passed to the function as argument printnum(a); return 0; } 20XX 38 #include <stdio.h> int add(int a, int b) { return (a + b); } int main() { int sum; // calling the function and storing // the returned value in sum sum = add(10, 50); printf("10 + 50 = %d", sum); return 0; } Output: 20XX + 50 = 60 10 39 ARRAY An array is a variable which is used to store a collection of similar type of data items stored at contiguous memory locations. This is similar to the concept of lists in Python. Syntax: Datatype Array_name[Array_size] = { element1, ...........}; 20XX 40 Example : int num[10] = {1,2,3,4,5,6,7,8,9,0}; int marks[] = {11,12,13,14,15,16,17,18,19,20}; In the above example, we have declared an integer type array num[10] having size of 10 i.e. it can store maximum 10 integer values. 20XX 41 //Program to print an element of an array #include <stdio.h> void main() { int num[5] = {3,2,4,6,7}; printf("%d ", num[3]); } Output : 6 20XX Pitch deck title 42 Question //Program to change value of element of an array #include <stdio.h> void main() { int num[5] = {1, 2, 3, 4, 5}; num[3] = 10; num[0] = 9; for(int b = 0; b < 5; b++) { printf("%d ", num[b]); } } 20XX Pitch deck title 43 OUTPUT: 9 2 3 10 5 20XX 44 SCANF() - TAKE INPUT scanf() function is used to take input of the user read numeric data, character from keyboard. 20XX 45 Example : Take Integer Input #include <stdio.h> int main(){ int num; printf("Enter a number: "); scanf("%d", &num); printf("Your entered number is %d",num); return 0; } Output Enter a number : 12 Your entered number is 12 20XX 46 Input and Output Array Elements #include <stdio.h> int main() { int a, b, num[5]; printf("Enter a integer : "); for(a = 0; a < 5; a++) { scanf("%d", &num[a]); } printf("Elements in the array : "); for(b = 0; b < 5; b++) { printf("%d ", num[b]); } return 0; } 20XX Output : Enter a integer : 2 5 6 1 9 Elements in the array : 2 5619 47 MULTI-DIMENSIONAL ARRAYS •The data in multi-dimensional array is stored in a tabular form (row * column) as shown in the diagram below. 20XX 48 Initialization of two-dimensional array Syntax: Data_type array_name[x][y]; First method : int arr[2][3] = {2, 0, 3, 5, 1, 12}; Better method : int arr[2][3] = { {2, 0, 3}, {5, 1, 12}}; Here we initialize a 2D array arr, with 2 rows and 3 columns as an array of arrays. Total elements in this array : 2 * 3 = 6 , and Each element of the array is yet again an array of integers. 20XX 49 Example : Taking Input from user for Two Dimensional Array #include <stdio.h> int main(){ int a[2][2], i, j; // Taking input using nested for loop for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { printf("Enter a[%d][%d] : ", i, j); scanf("%d", &a[i][j]); } } printf("\n All the elements of matrix : \n"); // Printing Output using nested for loop for (i = 0; i < 2; ++i) { for (j = 0; j < 2; ++j) { printf("a[%d][%d] : %d\n", i, j, a[i][j]); } } return 0; } 20XX 50 • In the previous program, we have used a nested for loop to take the input of the 2D array. • Once all the input has been taken, we have used another nested for loop to print the array members. • Finally, we print the array elements in each iteration. 20XX 51