UNIT IC programming notes university file

ANISHYAPIT 17 views 177 slides Aug 21, 2024
Slide 1
Slide 1 of 177
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177

About This Presentation

notes


Slide Content

EC22303 - C Programming and Data Structures UNIT I C PROGRAMMING FUNDAMENTALS Prepared By, P. Anishya , Asst. Professor/IT, St.Xavier ' s Catholic College of Engineering

2 Course Objective To introduce the basics of C programming language. To learn the concepts of advanced features of C. To understand the concepts of ADTs and linear data structures. To know the concepts of non-linear data structure and hashing. To familiarize the concepts of sorting and searching techniques.

3 Course Outcomes On Completion of the course, the students should be able to: CO1: Describe the basics of C programming language. CO2: Explain the concepts of advanced features of C. CO3: Implement the concepts of linear data structures. CO4: Apply non-linear data structures. CO5: Explore sorting and searching techniques

4 College Vision & Mission Vision Mission To be an institution of eminence of optimal human development, excellent engineering education and pioneering research towards developing a technically- empowered humane society. To transform the (rural) youth into top class professionals and technocrats willing to serve local and global society with ethical integrity, by providing vibrant academic experience of learning, research and innovation and stimulating opportunities to develop personal maturity and professional skills, with inspiring and high caliber faculty in a quality and serene infrastructural environment.

Vision Mission C r eating to p -notch I n formation T e c h n ology E n gine e rs, in n ovative r esea r chers a n d s u c c essf u l ent r ep r eneurs t o w ards dev e loping a technically-empowered humane society. Providing quality technical education and high caliber skill training that meets the needs of society and latest technical expectations of the industry. Fostering innovative and rigorous research culture among staff and students to find optimal solutions for complex problems. Imparting value-based education to imbibe ethical principles and act with social responsibility, team spirit, and leadership. Promoting and developing entrepreneurial skills of the students and handhold them towards commercial success. Department of Information Technology Vision & Mission 5

Program Outcome Engineering knowledge Problem analysis Design/development of solutions Conduct investigations of complex problems Modern tool usage The engineer and society Environment and sustainability Ethics Individual and team work Communication Project management and finance Life-long learning

Program Specific Outcome Design optimal solutions for the challenges in the area of Information and Communication Engineering using programming proficiencies. Apply the modeling and prediction tools, techniques and resources to analyze the real-world problems. Develop computing systems using the software design and development skills to enhance the lifestyle of the public.

PO CO MAPPING Mapping of Program Educational Objectives to Program Outcomes Mapping of Program Specific Outcomes to Program Outcomes PEO Program Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P O10 P O11 PO12 PEO1 3 2 - - - - - - - - - - PEO2 3 3 1 1 - - - - - - - 2 PEO3 - - 3 - - 1 - - - - - 3 PEO4 - - 3 - 1 2 3 1 - - - - PEO5 - - - 3 - - - 1 1 2 2 1 PSO Program Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P O10 P O11 PO12 PSO1 3 2 3 - - - - - 1 - - - PSO2 - 2 - 2 3 - 3 3 - - - - PSO3 - - 3 - - 2 - - 2 1 - 2

PO CO MAPPING Mapping of Course Outcomes to Program Outcomes Mapping of Course Outcomes to Program Specific Outcomes CO Program Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P O10 P O11 PO12 CS8251. 1 3 2 2 - - - - - - - - 2 CS8251. 2 3 3 3 - - - - - - - - 2 CS8251. 3 3 3 3 - - - - - - - - 2 CS8251. 4 3 3 3 - - - - - - - - 2 CS8251. 5 3 3 3 - - - - - - - - 2 CS8251. 1 3 2 2 - - - - - - - - 2 CO Program Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P O10 P O11 PO12 CS8251. 1 3 2 2 - - - - - - - - 2 CS8251. 2 3 3 3 - - - - - - - - 2 CS8251. 3 3 3 3 - - - - - - - - 2 CS8251. 4 3 3 3 - - - - - - - - 2 CS8251. 5 3 3 3 - - - - - - - - 2 CS8251. 1 3 2 2 - - - - - - - - 2

PO CO MAPPING CO Program Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 EC22303. 1 3 3 3 - - - - - - - - - EC22303. 2 3 3 3 - - - - - - - - - EC22303. 3 3 3 3 - - - - - - - - - EC22303. 4 3 3 3 - - - - - - - - - EC22303. 5 3 3 3 1 - - - - - - - - EC22303 3 3 3 1 - - - - - - - - Mapping of Course Outcomes to Program Outcomes

11 Syllabus Outline C programming Fundamentals C Programming – Advanced Features Linear Data Structures Non-Linear Data Structures Sorting and Searching Techniques

C Map 12

13 Bo o ks Reema Thareja, Programming in C, Oxford University Press, Second Edition, 2016. T2. Kernighan, B.W and Ritchie,D.M, ―The C Programming language ‖ , Second Edition, Pearson Education, 2006

Unit I Outline  Data Types – Variables – Operations – Expressions and Statements – Conditional Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional Arrays

Introducing C C is a programming language developed at AT & T Bell Laboratories of USA in 1972, designed and written by “Dennis Ritchie”. C is highly portable i.e., software written for one computer can be run on another computer. An important feature of C is its ability to extend itself. Basically it is a collection of functions . 15

History of C 1960: ALGOL (ALGOrithmic Language) 1967: BCPL (Basic Combined Programming Language) 1970: B programming language (typeless) 1972: C: BCPL plus B with types 1978: Kernighan + Ritchie standard for C 1989: ANSI standard for C

Topic Structure of C Program 17

Structure of C Program Objective T o kno w abo u t t he st r uc t u r e o f w ri t ing C Program. Outcome St u dents ca n able devel o p C P r o g ra m s f o r any problem

Structure of C Program

20 Example #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! \n"); return 0; }

21 Structure of C Program /* Comments */ Comments are a way of explaining what makes a program. Comments are ignored by the compiler and used by others to understand the code. #include<stdio.h> This is a preprocessor command that notify the compiler to include the header file stdio.h in the program before compiling the source-code.

22 Structure of C Program int/void main() int/void is a return value. main() The main() is the main function where program execution begins. Every C program must contain only one main function.

23 Structure of C Program Braces Two curly brackets “{…}” are used to group all printf() It is a function in C, which prints text on the screen.

Programming in C Data types in C

Data Types in C Objective To know the basic C programming constructs Outcome St u de n ts ca n deve l op C Pr o g r a m s us i ng ba s ic programming constructs.

Data Types Each variable in C has an associated data type . Each data type requires different amounts of memory and has some specific operations which can be performed over it.

Primitive Data Types a primitive is a fundamental data type that cannot be broken down into a more simple data type They are character integer float void

Primitive Data Types - character It stores a single character requires a single byte of memory Format specifier - %c Keyword – char Example – char test = „h‟;

Primitive Data Types - integer It st o r e s wh o le nu m bers - zer o , p o sit i ve and negative values It cannot store decimal values Usually requires 2 or 4 bytes of memory Format specifier - %d Keyword – int Example – int age=22;

Primitive Data Types – floating point It stores fractional numbers (real numbers) Usually requires 4 bytes of memory Format specifier - %f Keyword – float Example – float factor=22.442e2;

Primitive Data Types – void is an incomplete type. i.e. "nothing" or "no type".  It is us ed in three kinds of situation s Type Description Example Function returns as void A function with no return value has the return type as void. void exit (int status); Function arguments as void functions which do not accept any parameter. int rand(void); Pointers to void A pointer of type void * represents the address of an object, but not its type void *malloc( size_t size ); returns a pointer to void which can be casted to any data

Derived Data Types A derived type is formed by using one or more basic types in combination. Using derived types , an infinite variety of new types can be formed. They are arrays pointers

Derived Data Types – arrays An array is a collection of similar data types under a single variable name in continuous memory location i.e. one or more than one integers can be stored under a single name similarly for other data types too Example: int new[5] = {1,2,3,4,5}; char name = “Program”;

Derived Data Types – pointers A pointer is a special variable that stores address of another variable you must declare a pointer before using it to store any variable address. S y ntax: ty p e * pt r -variable-na m e; // d e c laration variable-name = & ptr-variable-name; //assignment Example: int *p; int num; p = &num;

User - defined datatypes use the built- in datatypes and other user - defined datatypes They are also called as data structures They are: Structure Union Enumeration User-defined Data Types (UDT)

User-defined Data Types - Structure  Keyword – struct member(s); It is a package of variables of different types under a single name . Structures are used to represent a record The struct statement defines a new data type, with more than one member. ▶ Example: struct book {  Syntax: struct variable { int book-id = 234; char name[20] = “C – Program”; } b } 1 ; ,b v 2; ariable(s);

User-defined Data Types - Union A union is a special data type that allows to store different data types in the same memory location . You can define a union with many members , but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose The union tag is optional

Keyword – union Syntax: union variable { member(s); }; variable(s); ▶ Example: union number { int roll; char option; float mark; } n1,n2; ▶ Now, the union variable can store an integer, a floating-point number, or a string of characters. ▶ It means a single variable, i.e., same memory location, can be used to store multiple types of data. User-defined Data Types - Union

The memory occupied by a union will be large enough to hold the largest member of the union In the above example, the memory allocated is for float which is the largest data type

User defined Data Types - E numeration Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which makes a program easy to read and maintain. Keyword – enum Syntax – enum variable {constant1, constant2,…} Example – enum week{Sunday,Monday,Tuesday,Wednesday,…….}; enum week day;

Other Data types…..

Recall: Data Types in C

Constant in C Obj e c t i v e : T o kno w a b o u t the usag e of constant in C Outcome: Students can able to develop any program using constants

Constants in C Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals . Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal .

Constants in C

Constants in C Integer Literals A n i n teg e r literal ca n b e a deci m al, octal, or hexadecimal constant. A p r efix s pecifies the base or radi x : 0x or 0X for hexadecimal, for octal, and nothing for decimal. Examples:  812  0213  0x4b

Constants in C Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Examples:  3.14159  314159E-5L

Constants in C Character Constants Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t).

Constants in C  Example #include <stdio.h> int main() { pri n tf("H e ll o\ tWorl d \ n \ n"); return 0; }

Constants in C String Literals St r i n g l it e rals o r con s ta n ts are enclosed in d o uble quotes "". A st r ing conta i ns c hara c ters that are s i m ilar to esc a pe chara c ter literal s : p l ain chara c ters, sequences, and universal characters. Example "hello, dear“ "hello, \ dear "

Constants in C Defining Constants There are two simple ways in C to define constants Using #define preprocessor. Using const keyword.

Constants in C Defining Constants Using #define Preprocessor Syntax: #define identifier value #include <stdio.h> #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0;} Output: value of area : 50

Constants in C Defining Constants Using const Keyword Syntax: const type variable = value #include <stdio.h> int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; }

Example C Program //Program to find the area of the square #include<stdio.h> main() { const int SIDE = 10; int area; area = SIDE*SIDE; prin t f ("The area o f th e s qua r e with sid e : % d is: % d sq. units" , SIDE, area); }

Constants in C Enumeration Constants Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.

Enumeration Constants Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants

Constants in C Enumeration Constants Variables of type enum can also be defined. They can be defined in two ways: They are, // In both of the below cases, "day" is // defined as the variable of type week. enum week{Mon, Tue, Wed}; enum day; // Or enum week{Mon, Tue, Wed}day;

Constants in C #include<stdio.h> enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; int main() { enum week day; day = Wed; p r intf ( " % d " ,da y ); return 0; } O u tput: 2

Constants in C #include<stdio.h> enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec}; int main() { int i; for (i=Jan; i<=Dec; i++) printf("%d ", i); return 0; } Output: 1 2 3 4 5 6 7 8 9 10 11

Keywords & Operators in C Obj e c t i v e : T o kno w a b o u t the usag e of keywords in C Outcome: Students can able to develop any program using keywords

Keywords Keywords are those words whose meaning is already defined by Compiler Cannot be used as Variable Name There are 32 Keywords in C C Ke y wo r ds are also called a s Re s erved words .

Keywords

Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators Arithmetic Operators (+, -, *,/,%, ++,--) Relational Operators (==, !=, >, <, >=, <=) Logical Operators (&&, ||, !) Bitwise Operators (&, |, ^, ~, <<, >>) Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=) Misc Operators (sizeof(), &, *, ?:)

Arithmetic Operators  Assume variable A holds 10 and variable B holds 20

Relational Operators  Assume variable A holds 10 and variable B holds 20

Logical Operators  Assume variable A holds 1 and variable B holds

Bitwise Operators  Bitwi s e oper a tor w or ks on operation. bits and perform bit-by-bit

Bitwise Operators  Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &,|, and ^ is as follows

Assignment Operators

Misc Operators

Operator Precedence Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.

Operator Precedence

Expressions & Statements in C Obj e c t i v e : T o kno w a b o u t the usag e of expressions in C Outcome: Students can able to develop any program using statements in C

Expressions in C An ex p r ession i s any l e gal c o mbinat i on of symbols that represents a value. Eve r y expression consists o f a t l e a st one operand and can have one or more operators.

Statements in C Input/ Output statements, Assignment statements (x=5) Decision making statements (if, if-else, if-elseif- else, nested-if) Switch statement Looping statements (while, for, do…while)

Input Output Statements Input - means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement. Output - means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.

Input Output Statements Formatted I/O scanf, printf Unformatted I/O gets(), puts() getchar(), putchar()

Input Output Statements The getchar() and putchar() Functions int getchar(void) This function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. int putchar(int c) This function puts the passed character on the screen and returns the same character. This function puts only single character at a time.

Input Output Statements #include <stdio.h> int main( ) { int c; printf( "Enter a value :"); c = getchar( ); printf( "\nYou entered: "); putchar( c ); return 0; } Output1 Enter a value: d You Entered: d Output 2: Enter a value : this is test You entered: t

Input Output Statements The gets() and puts() Functions char *gets(char *s) This function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File). int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout .

Input Output Statements #include <stdio.h> int main( ) { char str[100]; printf( "Enter a value :"); gets( str ); printf( "\nYou entered: "); puts( str ); return 0; }  Output Enter a value : this is test You entered: this is test

Input Output Statements The scanf() and printf() Functions int scanf(const char *format, ...) This function reads the input from the standard input stream stdin and scans that input according to the format provided. int printf(const char *format, ...) This function writes the output to the standard output stream stdout and produces the output according to the format provided. The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively.

Input Output Statements #include <stdio.h> int main( ) { char str[100]; printf( "Enter a value :"); scanf("%s", &str); printf( "\nYou entered: %s", str); return 0; }  Output Enter a value : Good You entered: Good

Assignment Statements An assignment statement gives a value to a variable. For example, x = 5; The general syntax of an assignment statement is variable = expression ; where: the variable must be declared; the variable may be a simple name, or an indexed location in an array, or a field (instance variable) of an object, or a static field of a class; and the expression must result in a value that is compatible with the type of the variable. In other words, it must be possible to cast the expression to the type of the variable. Example : int i=0;

Decision making statements Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met. They are, if statement switch statement conditional operator statement (? : operator)

Decision making statements Decision making with if statement The i f stat e m ent m ay be i m ple m en t ed i n dif f e r e n t for m s depending on the complexity of conditions to be tested. The different forms are, Simple if statement if....else statement Nested if....else statement Using else if statement

Decision making statements Simple if statement Syntax is, if(expression) { statement inside; } statement outside; If the expression returns true, then the s t a t e m e n t -i n s i de w i ll be executed, otherwise statement- ins i de i s s k i p p e d a n d on l y the statement-outside is executed. #include <stdio.h> void main( ) { int x, y; x = 15; y = 13; if (x > y ) { printf("x is greater than y"); } }

Decision making statements if...else statement Syntax is, if(expression) { statement block1; } else { statement block2; } If the expression is true, the statement-block1 is executed, else s tatement-block1 is skipped and statement-block2 is executed. #include <stdio.h> void main( ) { int x, y; x = 15; y = 18; if (x > y ) { printf("x is greater than y"); } else { printf("y is greater than x"); } }

Decision making statements    Nested if....else statement The general form of a nested if...else statement is, if( expression ) { if( expression1 ) { s t a t e m ent bloc k 1; } else { s t a t e m ent bloc k 2; } } else { state m ent bloc k 3; } if expression is false then statement-block3 will be executed, otherwise the execution continues and enters inside the first if to perform the check for the next if block, where if expression 1 is true the statement-block1 is executed otherwise statement- block2 is executed. # i n c l ud e < stdi o . h > void main( ) { int a, b, c; printf("Enter 3 numbers..."); scanf("%d%d%d",&a, &b, &c); if(a > b) { if(a > c) { printf("a is the greatest"); } else { printf("c is the greatest"); } } else { if(b > c) { printf("b is the greatest"); } else { printf("c is the greatest"); } } }

Decision making statements else if ladder The general form of else-if ladder is, if(expression1) { statement block1; } else if(expression2) { statement block2; } else if(expression3 ) { statement block3; } else default statement; #include <stdio.h> void main( ) { int a; printf("Enter a number..."); scanf("%d", &a); if(a%5 == && a%8 == 0) { printf("Divisible by both 5 and 8"); } else if(a%8 == 0) { printf("Divisible by 8"); } else if(a%5 == 0) { printf("Divisible by 5"); } else { printf("Divisible by none"); } }

Decision making statements Switch Statement Switch case statements are a substitute for long if statements that compare a variable to several integral values The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Switch is a control statement that allows a value to change control of execution. Syntax: switch (n) { case 1: // code to be executed if n = 1; break; case 2: // code to be executed if n = 2; break; default: // code to be executed if n doesn't match any cases }

Decision making statements Switch Statement #inclu d e <stdio. h > int main() { int x = 2; s w itch ( x ) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0; }

Looping statements Looping statement are the statements execute one or more statement repeatedly several number of times. In C programming language there are three types of loops; while, for and do-while. Why use loop ? When we need to execute a block of code several number of times then we need to use looping concept in C language. Advantage with looping statement Reduce length of Code Take less memory space. Burden on the developer is reducing. Time consuming process to execute the program is reduced.

Looping Statements 95

96 Looping Statements Types of Loops There are three type of Loops available in 'C' programming language. while loop for loop do...while Difference between conditional and looping statement Conditional statement executes only once in the program where as looping statements executes repeatedly several number of times.

97 Looping Statements While loop In while loop First check the condition if condition is true then control goes inside the loop body otherwise goes outside the body. while loop will be repeats in clock wise direction.

Looping Statements While loop Syntax: Assignment; w h i l e(condition) { Statements; ...... Increment/decrements (++ or --); } 98

Looping Statements  Example #include<stdio.h> #in c lud e < c onio . h> void main() { int i; c l rscr(); i=1; while (i<5) { prin t f(" \n%d", i ); i++; } getch(); } Outp u t 1 2 3 4 99

100 Looping Statements For loop for loop is a statement which allows code to be repeatedly executed. For l oop conta i ns 3 parts In i t ializat i on, Condition and Increment or Decrements.

Looping Statements  For loop 101

102 Looping Statements #include<stdio.h> #inc l u d e<c o n i o. h > void main() { int i; c l rsc r (); for (i=1;i<5;i++) { printf("\n%d",i); } getch(); } Output 1 2 3 4

103 Looping Statements do-while A do-while loop is similar to a while loop, except that a do-while loop is execute atleast one time. A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given condition at the end of the block (in while).

Looping Statements  do- w hile 104

105 Looping Statements #include<stdio.h> #incl u de< c onio.h> void main() { int i; clrscr ( ); i=1; do { print f ( " \n% d " , i); i++; } w hil e (i<5); getch(); } Outp u t 1 2 3 4

106 Looping Statements Nested Loops In Nested loop one loop is place within another loop body. When we need to repeated loop body itself n number of times use nested loops.

Storage Classes in C Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C Automatic. External. Static. Register . Scope is defined as the availability of a variable inside a program, scope is basically the region of code in which a variable is available to use. There are four types of scope: file scope, block scope, function scope and prototype scope. Visibility of a variable is defined as if a variable is accessible or not inside a particular region of code or the whole program. Lifetime of a variable is the time for which the variable is taking up a valid space in the system's memory, it is of three types: static lifetime, automatic lifetime and dynamic lifetime.

Automatic Automatic variables are allocated memory automatically at runtime. The visibility of the automatic variables is limited to the block in which they are defined. The scope of the automatic variables is limited to the block in which they are defined. The automatic variables are initialized to garbage by default. The memory assigned to automatic variables gets freed upon exiting from the block. The keyword used for defining automatic variables is auto. Every local variable is automatic in C by default. #include < stdio.h >    int  main()   {   int  a = 10,i;    printf ( "%d " ,++a);   {   int  a = 20;    for  ( i =0;i<3;i++)   {   printf ( "%d " ,a);  // 20 will be printed 3 times since it is the local value of a    }   }   printf ( "%d " ,a);  // 11 will be printed since the scope of a = 20 is ended.     }  

Static The variables defined as static specifier can hold their value between the multiple function calls. Static local variables are visible only to the function or the block in which they are defined. A same static variable can be declared many times but can be assigned at only one time. Default initial value of the static integral variable is 0 otherwise null. The visibility of the static global variable is limited to the file in which it has declared. The keyword used to define static variable is static. #include<stdio.h>    void  sum()   {   static   int  a = 10;   static   int  b = 24;    printf ( "%d %d \n" , a,b );   a++;    b++;   }   void  main()   int   i ;   for ( i  = 0;  i < 3;  i ++)   {   sum();  // The static variables holds their value between multiple function calls.      }   }   Output: {   10 24 11 25 12 26

Register The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU. We can not dereference the register variables, i.e., we can not use &operator for the register variable. The access time of the register variables is faster than the automatic variables. The initial default value of the register local variables is 0. The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler?s choice whether or not; the variables can be stored in the register. We can store pointers into the register, i.e., a register can store the address of a variable. Static variables can not be stored into the register since we can not use more than one storage specifier for the same variable . #include < stdio.h >    int  main()   {   register   int  a;  // variable a is allocated memory in the CPU register. The initial default value of a is 0.     printf ( "% d" ,a );   }  

The external storage class is used to tell the compiler that the variable defined as extern is declared with an external linkage elsewhere in the program. The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that the variable is declared elsewhere in the program. The default initial value of external integral type is 0 otherwise null. We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method. An external variable can be declared many times but can be initialized at only once. #include < stdio.h >    int  a;    int  main()   {   extern   int  a;  // variable a is defined globally, the memory will not be allocated to a    printf ( "% d" ,a );   }   OUTPUT

Functions in C Objective To know about functions and its usage. Outcome St u dents ca n able to write C p r o g ram f o r any problems using functions. Able to find the solution of complex problems by dividing into smaller sub problems.

Introduction to Functions A function is a block of code that performs a specific task. Types of functions Depending on whether a function is defined by the user or already included in C compilers, there are two types of functions in C programming There a r e two t y p es programming: Standard library functions User defined functions o f f u ncti o ns in C

Introduction to Functions Standard library functions The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc. These functions are defined in the header file. When you include the header file, these functions are available for use. Example: printf() - is a standard library function to send formatted output to the screen (display output on the screen) - defined in "stdio.h“ header file. There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions are available P f re o p r are u d s B e y : .

Prepared By: L.Josephine Usha, AP/IT, SXCCE Introduction to Functions User-defined functions C allow programmers to define functions. Such functions created by the user are called user- defined functions. Depending upon the complexity and requirement of the program, we can create as many user- defined functions as you want.

Introduction to Functions  Syntax: #include <stdio.h> void functionName() { ... .. ... } int main() { ... .. ... ... .. ... functionName(); ... .. ... ... .. ... }  The execution of a C program begins from the main() function.  When the compiler encounters fu n c t i o nN a m e () ; i n s ide t h e m ain function, control of the program jumps to void functionName()  And, the compiler starts executing the c od e s i n si d e the u s e r -d e f i n e d function.  The control of the program jumps to statement next to functionName(); once all the codes inside the function definition are executed.

Introduction to Functions #include <stdio.h> int addNumbers(int a, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a, int b) // function definition { int result; result = a+b; return result; // return statement }

Introduction to Functions Function Prototype (Declaration) A f u n c t i o n p r o t otype i s s i m ply the dec l arat i on o f a func t i o n t hat specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program. Syntax: returnType functionName(type1 argument1, type2 argument2,...); Example : int addNumbers(int a, int b);

Introduction to Functions Function definition Function definition contains the block of code to perform a specific task i.e. in this case, adding two numbers and returning it. Syntax of function definition returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function } When a function is called, the control of the program is transferred to the function definition. And, the compiler s t a r ts exe c uti n P r g e p a r t e d h B e y : L . c J o o se p d h i n e e s U s h i a n , A P s / I i T d , S X e C C t E he body of a funct i o n .

Introduction to Functions Function Call Control of the program is transferred to the user- defined function by calling it. Syntax of function call functionName(argument1, argument2, ...); addNumbers(n1,n2);

Introduction to Functions Passing arguments to a function In p r o g r a m m i n g, a r g u m ent refers to t he varia b le passed to the function. In the above example, two variables n1 and n2 are passed during function call. The par a m eters a and b a c c e p t s t he pas s e d arguments in the function definition. These ar g u m ents a r e c a lled f o r m al pa r a m eters of the function.

Introduction to Functions

Introduction to Functions Return Statement The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling a fter return function stat e m ent. Syntax:  return (expression);

Introduction to Functions Advantages of user-defined function The program will be easier to understand, maintain and debug. R e usab l e codes that programs. ca n be used in ot h er A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.

Categories of Functions Objective To know about different categories of writing a functions Outcome Students can able to write C programs using any function categories.

Categories of Functions User-defined functions can be categorized as: Function with no arguments and no return value Function with no arguments and a return value Function with arguments and no return value Function with arguments and a return value.

Categories of Functions: Function with no arguments and no return value #include<stdio.h> void addNumbers(); int main() { addNumbers(); return 0; } void addNumbers() { int a, b, res; printf(“Enter two values:\n); scanf(“%d%d”, &a,&b); res=a+b; printf(“The Sum is:%d”, res); }

Categories of Functions: Function with no arguments and a return value #include<stdio.h> int addNumbers(); int main() { int sum; sum=addNumbers(); printf(“The Sum is:%d”, sum); return 0; } int addNumbers() { int a, b, res; printf(“Enter two values:\n); scanf(“%d%d”, &a,&b); res=a+b; return res; }

Categories of Functions: Function with arguments and no return value #include<stdio.h> void addNumbers(int, int); int main() { int a, b; printf(“Enter two values:\n); scanf(“%d%d”, &a,&b); addNumbers(a,b); return 0; } void addNumbers(int c, int d) { int res; res=c + d; printf(“The Sum is:%d”, res); }

Categories of Functions: Function with arguments and a return value #include<stdio.h> int addNumbers(int, int); int main() { int a, b, sum; printf(“Enter two values:\n); scanf(“%d%d”, &a,&b); sum=addNumbers(a,b); printf(“The Sum is:%d”, sum); return 0; } int addNumbers(int c, int d) { int res; res=c+d; return res; }

Fu n ctions Example: Checking whether a number is prime or not #include <stdio.h> int checkPrimeNumber(int n); int main() { int n, flag; printf("Enter a positive integer: "); scanf("%d", &n); flag = checkPrimeNumber(n); if(flag==1) printf("%d is not a prime number",n); else printf("%d is a prime number",n); return 0; } } int checkPrimeNumber(int n) { int i; for(i=2; i <= n/2; ++i) { if(n%i == 0) return 1; } return 0; }

Built-in Functions Objective To know about various standard library functions of C Outcome Students can able to write C programs easily by using any standard library functions.

Built-in Functions The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O processing, string handling etc. These functions are defined in the header file. When you include the header file, these functions are available for use.

Built-in Functions stdio.h: I/O functions: getchar() returns the next character typed on the keyboard. putchar() outputs a single character to the screen. printf() do the output operation scanf() do the input operation string.h: String functions strcat() concatenates a copy of str2 to str1 strcmp() compares two strings strcpy() copys contents of str2 to str1

Built-in Functions ctype.h: Character functions isdigit() returns non-0 if arg is digit to 9 isalpha() returns non-0 if arg is a letter of the alphabet isalnum() returns non-0 if arg is a letter or digit islower() returns non-0 if arg is lowercase letter isupper() returns non-0 if arg is uppercase letter math.h: Mathematics functions acos() returns arc cosine of arg asin() returns arc sine of arg atan() returns arc tangent of arg cos() returns cosine of arg exp() returns natural logarithim e fabs() returns absolute value of num sqrt() returns squ P a re r p e are r d o B o y: t L o .Jo f se n p u hi m ne

Built-in Functions time.h: Time and Date functions time() returns current calender time of system difftime() returns difference in secs between two times clock() returns number of system clock cycles since program execution stdlib.h:Miscellaneous functions srand () used to set the startin malloc () provides dynamic memory allocation rand() to generate random numbers g point for rand()

Built-in Functions  List Of Inbuilt C Functions In Math.h File:

Built-in Functions  List Of Inbuilt C Functions in string.h File

Ex a mple #include <stdio.h> #include <math.h> int main() { float num, root; printf("Enter a number: "); scanf("%f", &num); // Computes the square root of num and stores in root. root = sqrt(num); printf("Square root of %.2f = %.2f", num, root); return 0; }

Ex a mple #include<stdio.h> #include <string.h> int main() { char str[20]; printf("Enter string: "); gets(str);//reads string from console printf("String is: %s",str); printf("\nReverse String is: %s",strrev(str)); return 0; } Enter string: javatpoint String is: javatpoint Reverse String is: tnioptavaj

Ex a mple #include<stdio.h> #include <string.h> int main() { char str[20]; printf("Enter string: "); gets(str);//reads string from console printf("String is: %s",str); printf("\nLower String is: %s",strlwr(str)); return 0; } Enter string: JAVATpoint String is: JAVATpoint Lower String is: javatpoint

Recursion Objective T o kno w abo u t t he concept o f recur s i o n in functions. Outcome St u dents ca n able to write C p r o g ra m s u s i n g recursion.

Recursion Recursion if a program allows you to call a function inside the same function, then it is called a recursive call of the function. Example: void recursion() { recursion(); /* function calls itself */ } int main() { recu r sion ( ); }

Recursion Example: Factorial #include <stdio.h> int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; } Output Factorial of 12 is 479001600

Recursion Example: Fibonacci Series Example: Fibonacci Series #i n c l u de < s t d i o . h > int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2); } int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i)); } return 0; } Out p ut 1 1 2 3 5 8 13 21 34

Types of Recursion Direct Recursion When a function calls itself within the same function repeatedly, it is called the direct recursion. fun()   {   // write some code    fun();   // some code    }   Indirect Recursion When a function is mutually called by another function in a circular manner, the function is called an indirect recursion function. fun1()   {   //  write some code     fun2()   }   fun2()   {   // write some code    fun3()   // write some code    }   fun3()   {   // write some code    fun1()   }  

Tail Recursion A recursive function is called the tail-recursive if the function makes recursive calling itself, and that recursive call is the last statement executes by the function . After that, there is no function or statement is left to call the recursive function. Linear Recursion A function is called the linear recursive if the function makes a single call to itself at each time the function runs and grows linearly in proportion to the size of the problem.

#include <stdio.h> void binary_search(int [], int, int, int); int main() { int key, size, i;int list[25]; printf("Ener size of a list: ") scanf("", &size); for(i= 0; i < size; i++) { scanf(“%d”, list[i]); } printf("Enter key to search \n "); scanf("%d", &key); binary_search(list, 0, size, key); } void binary_search(int list[], int lo, int hi, int key) { int mid; if (lo > hi) { printf("Key not found \n "); return; } mid = (lo + hi) / 2; if (list[mid] == key) { printf("Key found \n "); } else if (list[mid] > key) { binary_search(list, lo, mid - 1, key); } else if (list[mid] < key) { binary_search(list, mid + 1, hi, key); Recursion Example: Binary Search

Example Program Computation of Sine series

Example Program Computation of Sine series #include<stdio.h> #in c lud e < c onio . h> void main() { int i, n; float x, sum, t; clrscr(); printf("Enter the value for x : "); scanf("%f",&x); printf("Enter the value for n : "); scanf("%d", &n); x=x*3.14159/180; t=x; su m =x; /* Loop to calculate the value of Sine */ for(i=1;i<=n;i++) { t = (t* ( -1)*x*x)/(2*i*(2* i +1)); sum=sum+t; } printf(" The value of Sin(%f) = %.4f",x,sum); getch(); }

Assi g nment Write a C program for the following: Computation of Cosine Series Reverse a string Checking whether the number is palindrome or not Checking whether the string is palindrome or not Implement Scientific Calculator using built-in functions.

Passing Parameters Objective T o kno w abo u t vari o us ways o f pas s ing arguments to functions Outcome Students can able to write C programs easily by using C functions.

Parameter Passing There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A() . In this case A is called the “caller function” and B is called the “called function or callee function” . Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments .

Parameter Passing Formal Parameter : A variable and its type as they appear in the prototype of the function or method. Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.

Parameter Passing Two ways Pass by Value Pass by Reference

Parameter Passing Pass by Value Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value .

Parameter Passing #include <stdio.h> void swapnum(int i, int j) { int temp = i; i = j; j = temp; } int main(void) { int a = 10, b = 20; // passing parameters swapnum(a, b); printf("a is %d and b is %d\n", a, b); return

Parameter Passing #include <stdio.h> void func(int a, int b) { a += b; printf("In func, a = %d b = %d\n", a, b); } int main(void) { int x = 5, y = 7; // Passing parameters func(x, y); printf("In main, x = %d y = %d\n", x, y); return 0; } Output : In func, a = 12 b = 7 In main, x = 5 y = 7

Parameter Passing Pass by Reference Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as call by reference . This method is efficient in both time and space.

Parameter Passing #include <stdio.h> void swapnum(int* i, int* j) { int temp = *i; *i = *j; *j = temp; } int main(void) { int a = 10, b = 20; // passing parameters swapnum(&a, &b); printf("a is %d and b is %d\n", a, b); return 0; } Output : a is 20 and b is 10

Introduction to Arrays An array is a collection of data that holds fixed number of values of same type. Syntax: data_type array_name[array_size];  Declaration float mark[5];  The size a nd type of a r ra ys ca n not be c ha nged aft e r its declaration 161

Introduction to Arrays  Initialization int mark[5] = {19, 10, 8, 17, 9}; int mark[] = {19, 10, 8, 17, 9};  Initialization 162

163 Introduction to Arrays  How to insert and print array elements? int mark[5] = {19, 10, 8, 17, 9} // insert different value to third element mark[3] = 9; // take input from the user and insert in third element scanf("%d", &mark[2]); // print first element of an array printf("%d", mark[0]);

164 Introduction to Arrays  Program to initialize an integer array with five values and prints the array. #include <stdio.h> #include <conio.h> int main() { int numbers[]={1,2,3,4,5}; int i; clrscr(); printf("Array elements are\n"); for(i=0;i<=4;i++) printf("%d\n",numbers[i]); getch(); return 0; } Output Array elements are 1 2 3 4 5

Introduction to Arrays #include <stdio.h> int main() { int marks[10], i, n, sum = 0, average; printf("Enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) { printf("Enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; } average = sum/n; //sum=sum+marks[i] printf("Average = %d", average); return 0; } Output Enter n: 5 Enter number1: 45 Enter number2: 35 Enter number3: 38 Enter number4: 31 Enter number5: 49 Average = 39 159

166 Example Programs Example: Computing mean, median and mode Mean  Mean is same as average. The mean is found by adding up all of the given data and dividing by the number of elements.  Mean of 1,2,3,4,5 is (1+2+3+4+5 )/5 = 15/3 = 3 Median  The median is the middle number in an ordered list (ascending or descending). First arrange the numbers in orders in ascending order, then find the middle number and save it as median Example: 1 2 3 4 5  Median is 3 Mode  Mode is the element which happens most number of time in the list. If no element happens more than once, all elements are considered as mode. Example: 1 2 3 3 4 5  Mode is 3

167 2 Dimensional Arrays Objective To know about 2 D arrays and their usage. Outcome St u dents ca n able to write C p r o g ram f o r any matrix operations.

2 Dimensional Arrays Two-dimensional array are those type of array, which has finite number of rows and finite number of columns. The declaration form of 2-dimensional array is Data_type Array_name [row size][column size]; Example: int a[3][3]; 168

Ex a mple #include<stdio.h> #in c lud e < c onio . h> int main() { int matrix [3][3],i,j,r,c; clrscr(); printf(“Enter the order of matrix\n”); scanf(“%d%d”,&r,&c); printf(“Enter elements of %d * %d matrix \n”,r,c); for(i=0;i<r;i++) for(j=0;j<c;j++) scanf(“%d”,&matrix[i][j]); printf(“Given matrix:\n”); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf(“%d\t”,matrix[i][j]); printf(“\n”); } return 0; } // Output Enter the order of matrix 2 2 Enter elements of 2*2 matrix 1 2 3 4 Given matrix : 1 2 3 4 163

170 2 Dimensional Arrays Example: Matrix Operations Addition Subtraction Scaling Determinant Transpose Multiplication

2 D Arrays – Example Program Matrix Addition 171 #include <stdio.h> #include <conio.h> void main() { int a[2][3],b[2][3],c[2][3],i,j; clrscr(); printf("\nENTER VALUES FOR MATRIX A:\n"); for(i=0;i<2;i++) for(j=0 ; j < 3; j + +) scanf("%d",&a[i][j]); printf("\nENTER VALUES FOR MATRIX B:\n"); for(i=0;i<2;i++) for(j=0 ; j < 3; j + +) scanf("%d",&b[i][j]); for(i=0;i<2;i++) for(j=0 ; j < 3; j + +) c[i][j]=a[i][j]+b[i][j]; printf("\nTHE VALUES OF MATRIX C ARE:\n"); for(i=0;i<2;i++) { for(j=0;j<3;j++) printf("%5d",c[i][j]); printf("\n"); } getch(); }

2 D Arrays – Example Program Transpose of a matrix in C  To obtain Transpose of a matrix, we interchange rows and columns of the matrix.  For example, consider the following 3 X 2 matrix: 1 2 3 4 5 6 Transpose of the matrix: 1 3 5 2 4 6 166

2 D Arrays – Example Program Transpose of a matrix in C #include <stdio.h> int main() { int m, n, c, d, matrix[10][10], transpose[10][10]; printf("Enter the number of rows and columns of a matrix \n "); scanf("%d%d", &m, &n); printf("Enter elements of the matrix \n "); for (c = 0; c < m; c++){ for (d = 0; d < n; d++){ scanf("%d", &matrix[c][d]);}} for (c = 0; c < m; c++){ for (d = 0; d < n; d++){ transpose[d][c] = matrix[c][d];}} printf("Transpose of the matrix: \n "); for (c = 0; c < n; c++) { for (d = 0; d < m; d++) printf("%d \t ", transpose[c][d]); printf(" \n "); } return 0; } 167

2 D Arrays – Example Program Determinant of a matrix in C #in c lud e <std i o.h> int main(){ int a[3][3], i, j; long determinant; printf("Enter the 9 elements of matrix: ); for(i = ;i < 3;i++) for(j = 0;j < 3;j++) scanf("%d", &a[i][j]); printf("\nThe matrix is\n"); for(i = 0;i < 3; i++){ printf("\n"); for(j = 0;j < 3; j++) printf("%d\t", a[i][j]); } determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1] * (a[1][0] * a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2][1] - a[2][0] * a[1][1]); printf("\nDeterminant of 3X3 matrix: %ld", determinant); return 0; } 168

2 D Arrays – Example Program Scalar Matrix Multiplication #in c lud e <std i o.h> int main() { int i, j, row, col, Multi[10][10], Number; printf("\n Please Enter Number of rows and columns\n"); scanf("%d %d", &i, &j); printf("\n Please Enter the Matrix Elements \n"); for(row = 0; row < i; row++) for(col = 0;col < j; col++) scanf("%d", Multi[rows][columns]); printf("\n Please Enter the Multiplication value: "); scanf("%d", &Number); for(row = 0; rows< i; row++) for(col = 0; col < j; col++) Multi[row][col] = Number * Multi[row][col]; printf("\n The Result of a Scalar Matrix Multiplication is : \n"); for(row = 0; row < i; row++) for(col = 0; col < j; col++) printf("%d \t ", Multi[row][col]); printf("\n"); return 0; } 169

2 D Arrays – Example Program Matrix Multiplication 170

2 D Arrays – Example Program Matrix Multiplication #include<stdio.h> #include<stdlib.h> int main(){ int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; printf("enter the number of row="); scanf("%d",&r); printf("enter the number of column="); scanf("%d",&c); printf("enter the first matrix element=\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { sca nf ( " % d " ,& a [ i][ j ] ); }} printf("enter the second matrix element=\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { scanf("%d",&b[i][j]); } } printf("multiply of the matrix=\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { mul[i][j]=0; f or ( k=0;k<c;k++) { mul[i][j]+=a[i][k]*b[k][j]; } } } //for printing result for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("%d\t",mul[i][j]); } printf("\n"); } return 0; } 171
Tags