SlideShare a Scribd company logo
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
Creating top-
notch Information
Technology Engineers,
innovative
researchers
and successful
entrepreneurs towards
developing a
technically-empowered
humane society.
1. Providing quality technical education and high
caliber skill training that meets the needs of society
and latest technical expectations of the industry.
2. Fostering innovative and rigorous research culture
among staff and students to find optimal solutions for
complex problems.
3. Imparting value-based education to imbibe ethical
principles and act with social responsibility, team
spirit, and leadership.
4. 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 PO10PO11 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 PO10PO11 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 PO10PO11 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 PO10PO11 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
Books
 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
 To know about the structure of
writing C Program.
 Outcome
 Students can able develop C Programs
for 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
 Students can develop C Programs using
basic 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.
UNIT IC programming notes university file
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 stores whole numbers - zero,
positive 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 used in three kinds of situations
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
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.
 Syntax: type *ptr-variable-name;
//declaration variable-name = & ptr-variable-
name;
//assignment
 Example: int *p;
int 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”;
}
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;
▶ 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 -
Enumeration
 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
Objective : To know about the usage
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
 An integer literal can be a decimal,
octal, or hexadecimal constant.
 A prefix specifies the base or radix: 0x or
0X for hexadecimal, 0 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() {
printf("HellotWorldnn");
return 0;
}
Constants in C
 String Literals
 Stringliterals or constants are enclosed in
double quotes "".
 A string contains characters that are
similar to escape
character literals: plain
characters, sequences, and universal
characters.
 Example
 "hello, dear“
 "hello,
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;}
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);
Example C Program
//Program to find the area of the square
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %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;
printf("%d",day)
; return 0;
}
Output:
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:
0 1 2 3 4 5 6 7 8 9 10 11
Keywords & Operators in C
Objective : To know about the usage
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 Keywords are also called as
Reserved 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
0
Bitwise Operators
 Bitwise operator works 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
Objective : To know about the usage
of expressions in C
Outcome: Students can able to develop
any program using statements in C
Expressions in C
 An expression is any legal combination
of symbols that represents a value.
 Every expression consists of at least
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
 Theif statement may be implemented in different
forms depending on the complexity of conditions to be
tested.
 The different forms are,
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. 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 statement-inside will be
executed, otherwise statement-
inside is skipped and only 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
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
statement-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
Decision making statements


 Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
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.
#include <stdio.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 == 0 && 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
#include
<stdio.h> int
main()
{
int x = 2;
switch (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;
while(condition)
{
Statements;
......
Increment/
decrements (++
or --);
}
98
Looping Statements

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("n%d",i); i+
+;
}
getch();
Output
1
2
3
4
99
100
Looping Statements
 For loop
 for loop is a statement which allows code
to be repeatedly executed.
 For loop contains 3 parts
Initialization, Condition and Increment or
Decrements.
Looping Statements
 For
loop
101
102
Looping Statements
#include<stdio.h>
#include<conio.h
> void main()
{
int i;
clrscr();
for(i=1
;i<5;i+
+)
{
printf("
n
%d",i);
}
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-while
104
105
Looping Statements
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
i=1;
do
{
printf("n%d",i);
i++;
}
while(i<5);
getch();
}
Output
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
• 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.
1.#include <stdio.h>
2.int main()
3.{
4.int a = 10,i;
5.printf("%d ",++a);
6.{
7.int a = 20;
8.for (i=0;i<3;i++)
9.{
10.printf("%d ",a); // 20 will be printed 3 times since it is the local value
of a
11.}
12.}
13.printf("%d ",a); // 11 will be printed since the scope of a = 20 is ende
d.
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.
1.#include<stdio.h>
2.void sum()
3.{
4.static int a = 10;
5.static int b = 24;
6.printf("%d %d n",a,b);
7.a++;
8.b++;
9.}
10.void main()
12.int i;
13.for(i = 0; i< 3; i++)
14.{
15.sum(); // The static variables holds their value between multiple function calls.
16.}
17.}
Output:
18.{
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.
1.#include <stdio.h>
2.int main()
3.{
4.register int a; // variable a is allocated me
mory in the CPU register. The initial default v
alue of a is 0.
5.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.
1.#include <stdio.h>
2.int a;
3.int main()
4.{
5.extern int a; // variable a is defined globally, the memory will not
be allocated to a
6.printf("%d",a);
7.}
OUTPUT
0
Functions in C
 Objective
 To know about functions and its usage.
 Outcome
 Students can able to write C program
for 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 are two
types programming:
 Standard library
functions
 User defined functions
of functions 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 availablePfreoprareud sBey
: .
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
functionName(); inside the
main
function, control of the program
jumps to void functionName()
 And, the compiler starts executing the
codes inside the user-
defined 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 function prototype is simply the declaration of a
function that 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 starts executinPr
gepar
ted
hB
ey: L.
cJo
osep
dhin
ee
sUsh
ia
n, AP
s/I
iT
d,
SX CC E
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 programming, argument refers to the
variable passed to the function.
 In the above example, two variables n1 and n2 are
passed during function call.
 The parameters a and b accepts the
passed arguments in the function definition.
 These arguments are called formal
parameters 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
after return
function
statement.
 Syntax:
 return (expression);
Introduction to Functions
 Advantages of user-defined function
 The program will be easier to
understand,
maintain and debug.
 Reusable codes
that programs.
can be used in other
 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;
}
Functions
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:
a. getchar() returns the next character typed on the
keyboard.
b. putchar() outputs a single character to the screen.
c. printf() do the output operation
d. scanf() do the input operation
 string.h: String functions
a. strcat() concatenates a copy of str2 to str1
b. strcmp() compares two strings
c. strcpy() copys contents of str2 to str1
Built-in Functions
 ctype.h: Character functions
a. isdigit() returns non-0 if arg is digit 0 to 9
b. isalpha() returns non-0 if arg is a letter of the alphabet
c. isalnum() returns non-0 if arg is a letter or digit
d. islower() returns non-0 if arg is lowercase letter
e. isupper() returns non-0 if arg is uppercase letter
 math.h: Mathematics functions
a. acos() returns arc cosine of arg
b. asin() returns arc sine of arg
c. atan() returns arc tangent of arg
d. cos() returns cosine of arg
e. exp() returns natural logarithim e
f. fabs() returns absolute value of num
g.sqrt() returns s
q
uP
ar
e
rp
ea
r
e
rd
oB
oy
:
tL
o.
J
o
fs
e
np
uh
i
mn
e
Built-in Functions
 time.h: Time and Date functions
a. time() returns current calender time of system
b. difftime() returns difference in secs between two times
c. clock() returns number of system clock cycles since program execution
 stdlib.h:Miscellaneous functions
a. srand() used to set the startinmalloc() provides dynamic memory
allocation
b. rand() to generate random numbers
c. 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
Example
#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;
}
Example
#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
Example
#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
 To know about the concept of
recursion in functions.
 Outcome
 Students can able to write C programs
using 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() {
recursion();
}
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 %dn", i, factorial(i));
return 0;
}
Output
Factorial of 12 is 479001600
Recursion
Example: Fibonacci Series
Example: Fibonacci Series
#include <stdio.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("%dtn",
fibonacci(i));
}
return 0;
}
Output
0
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.
1.fun()
2.{
3.// write some code
4.fun();
5.// some code
6.}
Indirect Recursion
When a function is mutually called by
another function in a circular manner,
the function is called an indirect
recursion function.
1.fun1()
2.{
3.// write som
e code
4.fun2()
5.}
6.fun2()
7.{
8.// write som
e code
9.fun3()
10.// write so
me code
11.}
12.fun3()
13.{
14.// write so
me code
15.fun1()
16.}
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 searchn");
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 foundn");
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)
{
Recursion
Example: Binary Search
Example Program
Computation of Sine series
Example Program
Computation of Sine series
#include<stdio.h>
#include<conio.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;
sum=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();
}
Assignment
 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
 To know about various ways of
passing 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 %dn", a,
b); return 0
Parameter Passing
#include <stdio.h>
void func(int a, int b)
{
a += b;
printf("In func, a = %d b = %dn", a, b);
}
int main(void)
{
int x = 5, y = 7;
// Passing parameters
func(x, y);
printf("In main, x = %d y = %dn", 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 %dn", 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 and type of arrays cannot be
changed after 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 aren");
for(i=0;i<=4;i++)
printf("%dn",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
 Students can able to write C program
for 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
Example
#include<stdio.h>
#include<conio.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(“%dt”,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 matrixn");
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] =
printf("Transpose of the matrix:n");
for (c = 0; c < n; c++) {
for (d = 0; d < m; d+
+)
printf("%dt", transpose[c][d]);
printf("n");
}
return 0;
}
167
2 D Arrays – Example Program
Determinant of a matrix in C
#include<stdio.h>
int main(){
int a[3][3], i, j;
long determinant;
printf("Enter the
9 elements of
matrix: );
for(i = 0 ;i < 3;i+
+)
for(j = 0;j < 3;j++)
scanf("%d", &a[i][j]);
printf("nThe matrix isn");
for(i = 0;i < 3; i++){
printf("n");
for(j = 0;j < 3; j++)
printf("%dt", 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
#include<stdio.h>
int main()
{
int i, j, row, col, Multi[10][10], Number;
printf("n Please Enter Number of rows and
columnsn");
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++)
{ scanf("%d",&a[i][j]);
}}
printf("enter the second matrix element=n");
for(i=0;i<r;i++) {
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;
for(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("%dt",mul[i]
[j]);
}
printf("n");
}
return 0;
}
171
Ad

More Related Content

Similar to UNIT IC programming notes university file (20)

C AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDYC AND DATASTRUCTURES PREPARED BY M V B REDDY
C AND DATASTRUCTURES PREPARED BY M V B REDDY
Malikireddy Bramhananda Reddy
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
Mansi Tyagi
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
Asfand Hassan
 
Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019
Kayathri Devi D
 
Introduction to computers, input and output devices
Introduction to computers, input and output devicesIntroduction to computers, input and output devices
Introduction to computers, input and output devices
kavyashrikp
 
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
PreethaV16
 
C Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptxC Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptx
kumaranand07297
 
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
A Complete Guide to Programming in C 1st Edition Ulla Kirch-PrinzA Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
loadedalizwa
 
Microcontroller lab manual 2022 scheme vtu
Microcontroller lab manual 2022 scheme vtuMicrocontroller lab manual 2022 scheme vtu
Microcontroller lab manual 2022 scheme vtu
shilpa368375
 
Chap-02-01.ppt
Chap-02-01.pptChap-02-01.ppt
Chap-02-01.ppt
ssuser5ad1571
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
Vamshi171
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
ShraddhaPattnaik
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
UdhayaKumar175069
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
hamsa72
 
Chap 02-1
Chap 02-1Chap 02-1
Chap 02-1
Navjot Singh
 
C programming-1.pptx
C programming-1.pptxC programming-1.pptx
C programming-1.pptx
MohammadAnsari340279
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
ssusere6f5a11
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
Ankit Dubey
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
Mansi Tyagi
 
Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)Oop lec 2(introduction to object oriented technology)
Oop lec 2(introduction to object oriented technology)
Asfand Hassan
 
Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019
Kayathri Devi D
 
Introduction to computers, input and output devices
Introduction to computers, input and output devicesIntroduction to computers, input and output devices
Introduction to computers, input and output devices
kavyashrikp
 
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
Object Oriented Programming using C++ - OOPS concepts using C++ programming l...
PreethaV16
 
C Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptxC Language ppt create by Anand & Sager.pptx
C Language ppt create by Anand & Sager.pptx
kumaranand07297
 
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
A Complete Guide to Programming in C 1st Edition Ulla Kirch-PrinzA Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
A Complete Guide to Programming in C 1st Edition Ulla Kirch-Prinz
loadedalizwa
 
Microcontroller lab manual 2022 scheme vtu
Microcontroller lab manual 2022 scheme vtuMicrocontroller lab manual 2022 scheme vtu
Microcontroller lab manual 2022 scheme vtu
shilpa368375
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
Vamshi171
 
Chap-02-1.ppt
Chap-02-1.pptChap-02-1.ppt
Chap-02-1.ppt
hamsa72
 

Recently uploaded (20)

Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Kenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 CohortKenan Fellows Participants, Projects 2025-26 Cohort
Kenan Fellows Participants, Projects 2025-26 Cohort
EducationNC
 
Engage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdfEngage Donors Through Powerful Storytelling.pdf
Engage Donors Through Powerful Storytelling.pdf
TechSoup
 
"Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules""Basics of Heterocyclic Compounds and Their Naming Rules"
"Basics of Heterocyclic Compounds and Their Naming Rules"
rupalinirmalbpharm
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Contact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: OptometryContact Lens:::: An Overview.pptx.: Optometry
Contact Lens:::: An Overview.pptx.: Optometry
MushahidRaza8
 
Grade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable WorksheetGrade 2 - Mathematics - Printable Worksheet
Grade 2 - Mathematics - Printable Worksheet
Sritoma Majumder
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Ad

UNIT IC programming notes university file

  • 1. 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. 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. 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. 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.
  • 5. Vision Mission Creating top- notch Information Technology Engineers, innovative researchers and successful entrepreneurs towards developing a technically-empowered humane society. 1. Providing quality technical education and high caliber skill training that meets the needs of society and latest technical expectations of the industry. 2. Fostering innovative and rigorous research culture among staff and students to find optimal solutions for complex problems. 3. Imparting value-based education to imbibe ethical principles and act with social responsibility, team spirit, and leadership. 4. Promoting and developing entrepreneurial skills of the students and handhold them towards commercial success. Department of Information Technology Vision & Mission 5
  • 6. 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
  • 7. 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.
  • 8. 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 PO10PO11 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 PO10PO11 PO12 PSO1 3 2 3 - - - - - 1 - - - PSO2 - 2 - 2 3 - 3 3 - - - - PSO3 - - 3 - - 2 - - 2 1 - 2
  • 9. 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 PO10PO11 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 PO10PO11 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
  • 10. 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. 11 Syllabus Outline  C programming Fundamentals  C Programming – Advanced Features  Linear Data Structures  Non-Linear Data Structures  Sorting and Searching Techniques
  • 13. 13 Books  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
  • 14. Unit I Outline  Data Types – Variables – Operations – Expressions and Statements – Conditional Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional Arrays
  • 15. 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
  • 16. 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
  • 18. Structure of C Program  Objective  To know about the structure of writing C Program.  Outcome  Students can able develop C Programs for any problem
  • 19. Structure of C Program
  • 20. 20 Example #include <stdio.h> int main() { /* my first program in C */ printf("Hello, World! n"); return 0; }
  • 21. 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. 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. 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.
  • 24. Programming in C Data types in C
  • 25. Data Types in C  Objective  To know the basic C programming constructs  Outcome  Students can develop C Programs using basic programming constructs.
  • 26. 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.
  • 28. 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
  • 29. Primitive Data Types - character  It stores a single character  requires a single byte of memory  Format specifier - %c  Keyword – char  Example – char test = „h ; ‟
  • 30. Primitive Data Types - integer  It stores whole numbers - zero, positive 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;
  • 31. 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;
  • 32. Primitive Data Types – void  is an incomplete type. i.e. "nothing" or "no type".  It is used in three kinds of situations 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
  • 33. 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
  • 34. 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”;
  • 35. 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.  Syntax: type *ptr-variable-name; //declaration variable-name = & ptr-variable- name; //assignment  Example: int *p; int num;
  • 36.  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)
  • 37. 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”; }
  • 38. 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
  • 39.  Keyword – union  Syntax: union variable { member(s); }; variable(s); ▶ Example: union number { int roll; char option; float mark; ▶ 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
  • 40.  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
  • 41. User defined Data Types - Enumeration  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;
  • 44. Constant in C Objective : To know about the usage of constant in C Outcome: Students can able to develop any program using constants
  • 45. 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.
  • 47. Constants in C  Integer Literals  An integer literal can be a decimal, octal, or hexadecimal constant.  A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.  Examples:  812  0213  0x4b
  • 48. 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
  • 49. 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).
  • 50. Constants in C  Example #include <stdio.h> int main() { printf("HellotWorldnn"); return 0; }
  • 51. Constants in C  String Literals  Stringliterals or constants are enclosed in double quotes "".  A string contains characters that are similar to escape character literals: plain characters, sequences, and universal characters.  Example  "hello, dear“  "hello,
  • 52. Constants in C  Defining Constants  There are two simple ways in C to define constants  Using #define preprocessor.  Using const keyword.
  • 53. 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;}
  • 54. 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);
  • 55. Example C Program //Program to find the area of the square #include<stdio.h> main() { const int SIDE = 10; int area; area = SIDE*SIDE; printf("The area of the square with side: %d is: %d sq. units" , SIDE, area); }
  • 56. 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.
  • 57. Enumeration Constants  Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants
  • 58. 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;
  • 59. Constants in C #include<stdio.h> enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun}; int main() { enum week day; day = Wed; printf("%d",day) ; return 0; } Output: 2
  • 60. 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: 0 1 2 3 4 5 6 7 8 9 10 11
  • 61. Keywords & Operators in C Objective : To know about the usage of keywords in C Outcome: Students can able to develop any program using keywords
  • 62. 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 Keywords are also called as Reserved words .
  • 64. 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(), &, *, ?:)
  • 65. Arithmetic Operators  Assume variable A holds 10 and variable B holds 20
  • 66. Relational Operators  Assume variable A holds 10 and variable B holds 20
  • 67. Logical Operators  Assume variable A holds 1 and variable B holds 0
  • 68. Bitwise Operators  Bitwise operator works on operation. bits and perform bit-by-bit
  • 69. Bitwise Operators  Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &,|, and ^ is as follows
  • 72. 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.
  • 74. Expressions & Statements in C Objective : To know about the usage of expressions in C Outcome: Students can able to develop any program using statements in C
  • 75. Expressions in C  An expression is any legal combination of symbols that represents a value.  Every expression consists of at least one operand and can have one or more operators.
  • 76. 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)
  • 77. 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.
  • 78. Input Output Statements  Formatted I/O  scanf, printf  Unformatted I/O  gets(), puts()  getchar(), putchar()
  • 79. 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.
  • 80. 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
  • 81. 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.
  • 82. 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
  • 83. 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.
  • 84. 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
  • 85. 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;
  • 86. 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)
  • 87. Decision making statements  Decision making with if statement  Theif statement may be implemented in different forms depending on the complexity of conditions to be tested.  The different forms are, 1. Simple if statement 2. if....else statement 3. Nested if....else statement 4. Using else if statement
  • 88. Decision making statements  Simple if statement  Syntax is, if(expression) { statement inside; } statement outside;  If the expression returns true, then the statement-inside will be executed, otherwise statement- inside is skipped and only 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
  • 89. 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 statement-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
  • 90. Decision making statements    Nested if....else statement The general form of a nested if...else statement is, if( expression ) { if( expression1 ) { statement block1; } else { statement block2; } } else { statement block3; } 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. #include <stdio.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"); } } }
  • 91. 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 == 0 && 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"); } }
  • 92. 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
  • 93. Decision making statements  Switch Statement #include <stdio.h> int main() { int x = 2; switch (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;
  • 94. 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.
  • 96. 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. 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.
  • 98. Looping Statements  While loop  Syntax: Assignment; while(condition) { Statements; ...... Increment/ decrements (++ or --); } 98
  • 99. Looping Statements  Example #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=1; while(i<5) { printf("n%d",i); i+ +; } getch(); Output 1 2 3 4 99
  • 100. 100 Looping Statements  For loop  for loop is a statement which allows code to be repeatedly executed.  For loop contains 3 parts Initialization, Condition and Increment or Decrements.
  • 102. 102 Looping Statements #include<stdio.h> #include<conio.h > void main() { int i; clrscr(); for(i=1 ;i<5;i+ +) { printf(" n %d",i); } Output 1 2 3 4
  • 103. 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).
  • 105. 105 Looping Statements #include<stdio.h> #include<conio.h> void main() { int i; clrscr(); i=1; do { printf("n%d",i); i++; } while(i<5); getch(); } Output 1 2 3 4
  • 106. 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.
  • 107. 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,
  • 108. 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. 1.#include <stdio.h> 2.int main() 3.{ 4.int a = 10,i; 5.printf("%d ",++a); 6.{ 7.int a = 20; 8.for (i=0;i<3;i++) 9.{ 10.printf("%d ",a); // 20 will be printed 3 times since it is the local value of a 11.} 12.} 13.printf("%d ",a); // 11 will be printed since the scope of a = 20 is ende d.
  • 109. 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. 1.#include<stdio.h> 2.void sum() 3.{ 4.static int a = 10; 5.static int b = 24; 6.printf("%d %d n",a,b); 7.a++; 8.b++; 9.} 10.void main() 12.int i; 13.for(i = 0; i< 3; i++) 14.{ 15.sum(); // The static variables holds their value between multiple function calls. 16.} 17.} Output: 18.{ 10 24 11 25 12 26
  • 110. 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. 1.#include <stdio.h> 2.int main() 3.{ 4.register int a; // variable a is allocated me mory in the CPU register. The initial default v alue of a is 0. 5.printf("%d",a);
  • 111. •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. 1.#include <stdio.h> 2.int a; 3.int main() 4.{ 5.extern int a; // variable a is defined globally, the memory will not be allocated to a 6.printf("%d",a); 7.} OUTPUT 0
  • 112. Functions in C  Objective  To know about functions and its usage.  Outcome  Students can able to write C program for any problems using functions.  Able to find the solution of complex problems by dividing into smaller sub problems.
  • 113. 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 are two types programming:  Standard library functions  User defined functions of functions in C
  • 114. 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 availablePfreoprareud sBey : .
  • 115. 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.
  • 116. 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 functionName(); inside the main function, control of the program jumps to void functionName()  And, the compiler starts executing the codes inside the user- defined function.  The control of the program jumps to statement next to functionName(); once all the codes inside the function definition are executed.
  • 117. 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 }
  • 118. Introduction to Functions  Function Prototype (Declaration)  A function prototype is simply the declaration of a function that 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);
  • 119. 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 starts executinPr gepar ted hB ey: L. cJo osep dhin ee sUsh ia n, AP s/I iT d, SX CC E
  • 120. 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);
  • 121. Introduction to Functions  Passing arguments to a function  In programming, argument refers to the variable passed to the function.  In the above example, two variables n1 and n2 are passed during function call.  The parameters a and b accepts the passed arguments in the function definition.  These arguments are called formal parameters of the function.
  • 123. 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 after return function statement.  Syntax:  return (expression);
  • 124. Introduction to Functions  Advantages of user-defined function  The program will be easier to understand, maintain and debug.  Reusable codes that programs. can be used in other  A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers.
  • 125. 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.
  • 126. 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.
  • 127. 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); }
  • 128. 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; }
  • 129. 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); }
  • 130. 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; }
  • 131. Functions 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; }
  • 132. 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.
  • 133. 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.
  • 134. Built-in Functions  stdio.h: I/O functions: a. getchar() returns the next character typed on the keyboard. b. putchar() outputs a single character to the screen. c. printf() do the output operation d. scanf() do the input operation  string.h: String functions a. strcat() concatenates a copy of str2 to str1 b. strcmp() compares two strings c. strcpy() copys contents of str2 to str1
  • 135. Built-in Functions  ctype.h: Character functions a. isdigit() returns non-0 if arg is digit 0 to 9 b. isalpha() returns non-0 if arg is a letter of the alphabet c. isalnum() returns non-0 if arg is a letter or digit d. islower() returns non-0 if arg is lowercase letter e. isupper() returns non-0 if arg is uppercase letter  math.h: Mathematics functions a. acos() returns arc cosine of arg b. asin() returns arc sine of arg c. atan() returns arc tangent of arg d. cos() returns cosine of arg e. exp() returns natural logarithim e f. fabs() returns absolute value of num g.sqrt() returns s q uP ar e rp ea r e rd oB oy : tL o. J o fs e np uh i mn e
  • 136. Built-in Functions  time.h: Time and Date functions a. time() returns current calender time of system b. difftime() returns difference in secs between two times c. clock() returns number of system clock cycles since program execution  stdlib.h:Miscellaneous functions a. srand() used to set the startinmalloc() provides dynamic memory allocation b. rand() to generate random numbers c. g point for rand()
  • 137. Built-in Functions  List Of Inbuilt C Functions In Math.h File:
  • 138. Built-in Functions  List Of Inbuilt C Functions in string.h File
  • 139. Example #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; }
  • 140. Example #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
  • 141. Example #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
  • 142. Recursion  Objective  To know about the concept of recursion in functions.  Outcome  Students can able to write C programs using recursion.
  • 143. 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() { recursion(); }
  • 144. 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 %dn", i, factorial(i)); return 0; } Output Factorial of 12 is 479001600
  • 145. Recursion Example: Fibonacci Series Example: Fibonacci Series #include <stdio.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("%dtn", fibonacci(i)); } return 0; } Output 0 1 1 2 3 5 8 13 21 34
  • 146. Types of Recursion Direct Recursion When a function calls itself within the same function repeatedly, it is called the direct recursion. 1.fun() 2.{ 3.// write some code 4.fun(); 5.// some code 6.} Indirect Recursion When a function is mutually called by another function in a circular manner, the function is called an indirect recursion function. 1.fun1() 2.{ 3.// write som e code 4.fun2() 5.} 6.fun2() 7.{ 8.// write som e code 9.fun3() 10.// write so me code 11.} 12.fun3() 13.{ 14.// write so me code 15.fun1() 16.}
  • 147. 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.
  • 148. #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 searchn"); 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 foundn"); 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) { Recursion Example: Binary Search
  • 150. Example Program Computation of Sine series #include<stdio.h> #include<conio.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; sum=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(); }
  • 151. Assignment  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.
  • 152. Passing Parameters  Objective  To know about various ways of passing arguments to functions  Outcome  Students can able to write C programs easily by using C functions.
  • 153. 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.
  • 154. 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.
  • 155. Parameter Passing  Two ways  Pass by Value  Pass by Reference
  • 156. 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.
  • 157. 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 %dn", a, b); return 0
  • 158. Parameter Passing #include <stdio.h> void func(int a, int b) { a += b; printf("In func, a = %d b = %dn", a, b); } int main(void) { int x = 5, y = 7; // Passing parameters func(x, y); printf("In main, x = %d y = %dn", x, y); return 0; } Output: In func, a = 12 b = 7 In main, x = 5 y = 7
  • 159. 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.
  • 160. 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 %dn", a, b); return 0; } Output: a is 20 and b is 10
  • 161. 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 and type of arrays cannot be changed after its declaration 161
  • 162. Introduction to Arrays  Initialization int mark[5] = {19, 10, 8, 17, 9}; int mark[] = {19, 10, 8, 17, 9}; Initialization 162
  • 163. 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. 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 aren"); for(i=0;i<=4;i++) printf("%dn",numbers[i]); getch(); return 0; } Output Array elements are 1 2 3 4 5
  • 165. 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. 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. 167 2 Dimensional Arrays  Objective  To know about 2 D arrays and their usage.  Outcome  Students can able to write C program for any matrix operations.
  • 168. 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
  • 169. Example #include<stdio.h> #include<conio.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(“%dt”,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. 170 2 Dimensional Arrays  Example: Matrix Operations  Addition  Subtraction  Scaling  Determinant  Transpose  Multiplication
  • 171. 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(); }
  • 172. 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
  • 173. 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 matrixn"); 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] = printf("Transpose of the matrix:n"); for (c = 0; c < n; c++) { for (d = 0; d < m; d+ +) printf("%dt", transpose[c][d]); printf("n"); } return 0; } 167
  • 174. 2 D Arrays – Example Program Determinant of a matrix in C #include<stdio.h> int main(){ int a[3][3], i, j; long determinant; printf("Enter the 9 elements of matrix: ); for(i = 0 ;i < 3;i+ +) for(j = 0;j < 3;j++) scanf("%d", &a[i][j]); printf("nThe matrix isn"); for(i = 0;i < 3; i++){ printf("n"); for(j = 0;j < 3; j++) printf("%dt", 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
  • 175. 2 D Arrays – Example Program Scalar Matrix Multiplication #include<stdio.h> int main() { int i, j, row, col, Multi[10][10], Number; printf("n Please Enter Number of rows and columnsn"); 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
  • 176. 2 D Arrays – Example Program Matrix Multiplication 170
  • 177. 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++) { scanf("%d",&a[i][j]); }} printf("enter the second matrix element=n"); for(i=0;i<r;i++) { 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; for(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("%dt",mul[i] [j]); } printf("n"); } return 0; } 171