Unit 01 Part1 Notes
Unit 01 Part1 Notes
USING
{C}
Fundamentals Programming
of C
Features of C Language
Modularity
Extensibility
Elegant syntax
Case sensitive
Less memory required
The standard library concept
The portability of the compiler
A powerful and varied range of operators
Ready access to the hardware when needed
Basics of C 2
Structure of C Program
Program
Documentation section
1 // Program for addition of 2 nos
(Used for comments)
2
Link section 3
4
Definition section 5
6 void fun();
7
Global declaration section 8 int a=10
10;
(Variables used in more than 9
one functions) 10
void main () 11 void main( )
{ 12 {
Declaration part 13 printf(
printf("Value of a inside main function: %d", a);
Executable part 14 fun();
} 15 }
16
Subprogram section 14 void fun()
(User defined functions) 18 {printf(
{printf("Value of a inside fun function: %d", a);}
Basics of C 3
Comments
A comment is an explanation or description of the source code of the program
It helps a programmer to explain logic of the code and improves program
readability.
At run-time, a comment is ignored by the compiler.
There are two types of comments in C:
Single line comment
Represented as // double forward slash
It is used to denote a single line comment only.
Example: // Single line comment
Multi-line comment
Represented as /* any_text */ start with forward slash and asterisk (/*) and end with asterisk and
forward slash (*/).
It is used to denote single as well as multi-linecomment.
comment.
Example: /* multi line comment line -1
multi line comment line -2 */
Basics of C 4
Header files
A header file is a file with extension .h which contains the set of predefined
standard library functions.
The “#include” preprocessing directive is used to include the header files with
extension in the program.
Header file Description
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and clrscr)
math.h Mathematics functions (pow, exp, sqrt etc…)
string.h String functions (strlen, strcmp, strcat etc…)
Basics of C 5
Data Types
Data types are defined as the data storage format that a variable can store a data.
It determines the type and size of data associated with variables.
Data types in C
Basics of C 6
Primary Data Type
Primary data types are built in data types which are directly supported by machine.
They are also known as fundamental data types.
int:
int datatype can store integer number which is whole number without fraction part such as 10, 105
etc.
C language has 3 classes of integer storage namely short int, int and long int. All of these data
types have signed and unsigned forms.
Example: int a=10;
float:
float data type can store floating point number which represents a real number with decimal point
and fractional part such as 10.50, 155.25 etc.
When the accuracy of the floating point number is insufficient, we can use the double to define the
number. The double is same as float but with longer precision.
To extend the precision further we can use long double which consumes 80 bits of memory space.
Example: float a=10.50;
Basics of C 7
Primary Data Type (cont…)
char:
Char data type can store single character of alphabet or digit or special symbol such as ‘a’, ‘5’ etc.
Each character is assigned some integer value which is known as ASCII values.
Example: char a=‘a’;
void:
The void type has no value therefore we cannot declare it as variable as we did in case of int or
float or char.
The void data type is used to indicate that function is not returning anything.
Basics of C 8
Secondary Data Type
Secondary data types are not directly supported by the machine.
It is combination of primary data types to handle real life data in more convenient
way.
It can be further divided in two categories,
categories
Derived data types: Derived data type is extension of primary data type. It is built-in system
and its structure cannot be changed. Examples:
Examples Array and Pointer.
Array: An array is a fixed-size sequenced collection of elements of the same data type.
Pointer: Pointer is a special variable which contains memory address of another variable.
User defined data types: User defined data type can be created by programmer using
combination of primary data type and/or derived data type. Examples: Structure, Union, Enum.
Structure: Structure is a collection of logically related data items of different data types grouped
together under a single name.
Union: Union is like a structure, except that each element shares the common memory.
Enum: Enum is used to assign names to integral constants, the names make a program easy to read
and maintain.
Basics of C 9
Variables and Constants
Variable is a symbolic name given to some value which can be changed.
, , , , . can be variable names..
=5 = +
Constant is a fixed value which cannot be changed.
5, −7.5, 1452, 0, 3.14, .
Basics of C 10
Tokens
The smallest individual unit of a program is known as token.
C has the following tokens:
Keywords
C reserves a set of 32 words for its own use. These words are called keywords (or reserved words), and
each of these keywords has a special meaning within the C language.
Identifiers
Identifiers are names that are given to various user defined program elements, such as variable,
function and arrays.
Constants
Constants refer to fixed values that do not change during execution of program.
Strings
A string is a sequence of characters terminated with a null character \0.
Special Symbols
Symbols such as #, &, =, * are used in C for some specific function are called as special symbols.
Operators
An operator is a symbol that tells the compiler to perform certain mathematical or logical operation.
Basics of C 11
Operators
Arithmetic operators (+, - , *, /, %)
Relational operators (<, <=, >, >=, ==, !=)
Logical operators (&&, ||, !)
Assignment operators (+=, -=, *=, /=)
Increment and decrement operators (++, --)
Conditional operators (?:)
Bitwise operators (&, |, ^, <<, >>)
Special operators ()
Basics of C 12
Arithmetic Operators
Arithmetic operators are used for mathematical calculation.
Operator Meaning Example Description
+ Addition a+b Addition of a and b
- Subtraction a–b Subtraction of b from a
* Multiplication a*b Multiplication of a and b
/ Division a/b Division of a by b
% Modulo division- remainder a%b Modulo of a by b
Basics of C 13
Relational Operators
Relational operators are used to compare two numbers and taking decisions based
on their relation.
Relational expressions are used in decision statements such as if, for, while, etc…
Operator Meaning Example Description
< Is less than a<b a is less than b
<= Is less than or equal to a <= b a is less than or equal to b
> Is greater than a>b a is greater than b
>= Is greater than or equal to a >= b a is greater than or equal to b
== Is equal to a=b a is equal to b
!= Is not equal to a != b a is not equal to b
Basics of C 14
Logical Operators
Logical operators are used to test more than one condition and make decisions.
Operator Meaning
&& logical AND (Both non zero then true, either is zero then false)
|| logical OR (Both zero then false, either is non zero then true)
! Is greater than
a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Basics of C 15
Assignment Operators
Assignment operators (=) is used to assign the result of an expression to a variable.
Assignment operator stores a value in memory.
memory
C also supports shorthand assignment operators which simplify operation with
assignment.
Operator Meaning
= Assigns value of right side to left side
+= a += 1 is same as a = a + 1
-= a -= 1 is same as a = a - 1
*= a *= 1 is same as a = a * 1
/= a /= 1 is same as a = a / 1
%= a %= 1 is same as a = a % 1
Basics of C 16
Increment and Decrement Operators
Increment (++) operator used to increase the value of the variable by one.
Decrement (--) operator used to decrease the value of the variable by one.
Example Explanation
x=100; After the execution the
x++; value of x will be 101.
Example Explanation
x=100; After the execution the
x--; value of x will be 99.
Basics of C 17
Increment and Decrement Operators (cont…)
(
Operator Description
Pre increment operator (++x) value of x is incremented before assigning it to the variable
on the left
Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the variable on
the left
Basics of C 18
Conditional Operators
A ternary operator is known as conditional operator.
Syntax: exp1 ? exp2 : exp3
Working of the ? : Operator
exp1 is evaluated first
if exp1 is true(nonzero) then
- exp2 is evaluated and its value becomes the value of the expression
If exp1 is false(zero) then
- exp3 is evaluated and its value becomes the value of the expression
Example Example
m=2, n=3; m=2, n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Explanation Explanation
Value of r will be 3 Value of r will be 2
Basics of C 19
Bitwise Operators
Bitwise operators are used to perform operation bit by bit.
Bitwise operators may not be applied to float or double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left (shift left means multiply by 2)
>> shift right (shift right means divide by 2)
Basics of C 20
Bitwise Operators
8 = 1000 (In Binary) and 6 = 0110 (In Binary)
Example: Bitwise << (Shift Left) Example Bitwise >> (Shift Right)
Example:
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf
printf("Output = %d", b);
Output Output
16 (multiplying a by a power of two) 4 (dividing a by a power of two)
Basics of C 21
Special Operators
Operator Meaning
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection operator, used in structure.
-> member selection operator, used in pointer to structure.
Basics of C 22
Expressions
An expression is a combination of operators, constants and variables.
An expression may consist of one or more operands, and zero or more operators to
produce a value.
answer = a + b * c;
Basics of C 23
Evaluation of Expressions
An expression is evaluated based on the operator precedence and associativity.
When there are multiple operators in an expression, they are evaluated according
to their precedence and associativity.
Basics of C 24
Operator precedence
Precedence of an operator is its priority in an expression for evaluation.
The operator with higher precedence is evaluated first and the operator with the
least precedence is evaluated last.
Operator precedence is why the expression 5 + 3 * 2 is calculated as 5 + (3 * 2),
giving 11, and not as (5 + 3) * 2, giving 16.
16
We say that the multiplication operator (*) has higher "precedence" or "priority"
than the addition operator (+), so the multiplication
multiplic must be performed first.
Basics of C 25
Operator associativity
Associativity is the left-to-right or right-to-left
right order for grouping operands to
operators that have the same precedence.
precedence
Operator associativity is why the expression 8 - 3 - 2 is calculated as (8 - 3) - 2,
giving 3, and not as 8 - (3 - 2), giving 7.
We say that the subtraction operator (-) is "left associative", so the left subtraction
must be performed first.
When we can't decide by operator precedence alone in which order to calculate an
expression, we must use associativity.
Basics of C 26
Type conversion
Type conversion is converting one type of data to another type.
It is also known as Type Casting.
There are two types of type conversion:
Implicit Type Conversion
This type of conversion is usually performed by the compiler when necessary without any commands
by the user.
It is also called Automatic Type Conversion.
Explicit Type Conversion
These conversions are done explicitly by users using the pre-defined functions.
Example: Implicit Type Conversion Example: Explicit Type Conversion
int a = 20; double a = 4.5, b = 4.6, c = 4.9;
double b = 20.5; int result = (int)da + (int)db + (int)dc;
printf("%lf", a + b); printf("result = %d", result);
Output Output
40.500000 12
Basics of C 27
printf()
printf() is a function defined in stdio.h file
It displays output on standard output, mostly monitor
Message and value of variable can be printed
Let’s see few examples of printf
printf(“ ”);
printf(“Hello World”); // Hello World
printf(“%d”, c); // 15
printf(“Sum = %d”, c); // Sum = 15
printf(“%d+%d=%d”, a, b, c); // 10+5=15
15
Basics of C 28
scanf()
scanf() is a function defined in stdio.h file
scanf() function is used to read character, string, numeric data from keyboard
Syntax of scanf
scanf("%X", &variable);
where %X is the format specifier which tells the compiler what type of data is in a variable.
& refers to address of “variable” which is directing the input value to a address returned by &variable.
Basics of C 29
getchar and putchar
Program
getchar function reads a single
1 #include <stdio.h>
character from terminal. 2 void main( )
putchar function displays the 3 {
character passed to it on the screen. 4 int c;
5 printf("Enter a character: ");
6 /* Take a character as input */
7 c = getchar();
8 /* Display the character */
9 printf("Entered character is: ");
10 putchar(c);
11 }
Output
Enter a character: a
Entered character is: a
Basics of C 30
gets and puts
Program
gets function reads a line from stdin
1 #include <stdio.h>
into the buffer pointed to by s until 2 void main( )
either a terminating newline or EOF 3 {
(End of File) occurs. 4 /*Character array of length 100*/
5 char str[100];
puts function writes the string 's' 6 printf("Enter a string: ");
and 'a' trailing newline to stdout. 7 /* Take a string as input */
8 gets( str );
9 /* Display the string */
10 printf("Entered string is: ");
11 puts( str );
12 }
Output
Enter a string: india
Entered string is: india
Basics of C 31
Preprocessor
Preprocessors are programs that process our source code before compilation.
There are a number of steps involved between writing a program and executing a
program in C.
Let us have a look at these steps before we actually start learning about
Preprocessors.
C Program
Object Executable
Are there No Code Code
preprocessor Compiler Linker
directive
Yes
Basics of C 33
Macro
A macro is a fragment of code which has been given a name. Whenever the name
is used in program, it is replaced by the contents of the macro.
Macro definitions are not variables and cannot be changed by your program code
like variables.
The ‘#define’ directive is used to define a macro.
Do not put a semicolon ( ; ) at the end of #define statements.
There are two types of macros:
Object-like Macros
Function-like Macros
Basics of C 34
Macro
Description Object-like Macros Function-like Macros
Definition The object-like
like macro is an identifier that The function-like macro looks like
is replaced by value. function call.
Use It is used to represent numeric constants. It is used to represent function.
Syntax #define CNAME value #define CNAME (expression)
Example #define PI 3.14 #define MIN(a,b) ((a)<(b)?(a):(b))
Program 1 #include <stdio.h> 1 #include <stdio.h>
2 #define PI 3.14 2 #define MIN(a,b) ((a)<(b)?(a):(b))
3 void main() 3 void main()
4 { int r=2; 4 {
5 float a; 5 printf("%d", MIN(2, 5));
6 a=PI*r*r; 6 }
7 printf("%f", a);
8 }
Basics of C 35
Programming for Problem Solving
USING
{C}
Decision Programming
making in
C
Need of decision making
if number is odd
{
/* code */
}
Decision Making 2
Decision Making or Conditional Statement
C program statements are executed sequentially.
sequentially
Decision Making statements are used to control the flow of program.
It allows us to control whether a program segment is executed or not.
It evaluates condition or logical expression first and based on its result (either true
or false), the control is transferred to particular statement.
If result is true then it takes one path else it takes another path.
Decision Making 3
Decision Making Statements in C
Decision Making 4
Relational Operators
Relational Operator is used to compare two expressions.
It gives result either true or false based on relationship of two expressions.
Decision Making 5
If statement
if
if is single branch decision making statement.
If condition is true then only body will be executed.
if is a keyword. Flowchart of if
Syntax
if(condition)
{ False
// Body of the if condition
// true part
}
True
Decision Making 7
WAP to print Zero if given number is 0
Program Output
1 #include<stdio.h> Enter Number:0
2 void main() Zero
3 {
4 int a;
5 printf("Enter Number:");
6 scanf("%d",&a);
7 if(a == 0)
8 {
9 printf("Zero");
10 }
11 }
Decision Making 8
WAP to print Positive or Negative Number
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 if(a < 0)
12 {
13 printf("Negative Number");
14 }
15 }
Decision Making 9
Modulus Operator
% is modulus operator in C
It divides the value of one expression (number) by the value of another expression (number), and
returns the remainder.
Syntax: express1 % express2
E.g.
7%2 Answer: 1
6%2 Answer: 0
25%10 Answer: 5
37%28 Answer: 9
Decision Making 10
WAP to print Odd or Even Number
Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 if(a%2 != 0)
12 {
13 printf("Odd Number");
14 }
15 }
Decision Making 11
If..else statement
if...else
if…else is two branch decision making statement
If condition is true then true part will be executed else false part will be executed
else is keyword
Flowchart of if…else
Syntax
if(condition)
{ True False
// true part condition
}
else
{
// false part … …
}
Decision Making 13
WAP to print Positive or Negative Number using if…else
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 else
12 {
13 printf("Negative Number");
14 }
15 }
Decision Making 14
WAP to print Odd or Even Number using if…else
Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 else
12 {
13 printf("Odd Number");
14 }
15 }
Decision Making 15
WAP to find largest number from given 2 numbers using if
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 if(a < b)
12 {
13 printf("%d is largest", b);
14 }
15 }
Decision Making 16
WAP to find largest number from given 2 numbers using if…else
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 else
12 {
13 printf("%d is largest", b);
14 }
15 }
Decision Making 17
{ }
If body of if contains only one statement then { } are not compulsory
But if body of if contains more than one statements then { } are compulsory
Decision Making 18
Decision Making 20
if…else if…else ladder flowchart
condition False
1
… …
Decision Making 21
WAP to print Zero, Positive or Negative Number
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a > 0)
8 printf("Positive Number");
9 else if(a==0)
10 printf("Zero");
11 else
12 printf("Negative Number");
13 }
Decision Making 22
Nested if
Nested if
If condition-1 is true then condition-2 is evaluated.
evaluated If it is true then statement-1 will
be executed.
If condition-1 is false then statement-3 will be executed.
Syntax
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
Decision Making 24
Nested if flowchart
True
Statement Statement
1 2
Next
Statement
Decision Making 25
WAP to print maximum from given three numbers
Program
1 void main(){
2 int a, b, c; Output
3 printf("Enter Three Numbers:"); Enter Three Numbers:7
4 scanf("%d%d%d",&a,&b,&c); 5
5 if(a>b) 9
6 { 9 is max
7 if(a>c)
8 printf("%d is max",a);
9 else
10 printf("%d is max",c);
11 }
12 else
13 {
14 if(b>c)
15 printf("%d is max",b);
16 else
17 printf("%d is max",c);
18 }
19 }
Decision Making 26
Conditional Operator
? : (Conditional Operator)
The conditional works operator is similar to the if-else.
It is also known as a ternary operator.
It returns first value of expression (before colon(:)) if expression is true and second
value of expression if expression is false.
False
True
Decision Making 28
Conditional operator flowchart
Here, Expression1 is the condition to be
evaluated
evaluated.
True Expression False
1 If the condition(Expression1) is True then
Expression will be executed and the result
Expression2
will be returned.
Expression Expression
2 3
Otherwise, if condition(Expression1) is
false then Expression3 will be executed
Variable
and the result will be returned.
Decision Making 29
WAP to find largest number from given 2 numbers using ? :
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b, max;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 max = a>b?a:b;
8 printf("%d is largest",max);
9 }
Decision Making 30
switch…case
switch...case
The switch statement allows to execute one code block among many alternatives.
It works similar to if...else..if ladder.
Syntax The expression is evaluated once and
switch (expression) compared with the values of each case.
{
case constant1: If there is a match, the corresponding
// statements statements after the matching case are
break; executed.
case constant2:
// statements If there is no match, the default
break; statements are executed.
.
. If we do not use break, all statements
. after the matching label are executed.
default:
// default statements The default clause inside the switch
} statement is optional.
Decision Making 32
WAP that asks day number and prints day name using switch…case
void main(){ case 7:
int day; printf("Saturday");
printf("Enter day number(1-7):"); break;
scanf("%d",&day); default:
switch(day) printf("Wrong input");
{ break;
case 1: }
printf("Sunday"); }
break;
case 2:
printf("Monday");
break;
case 3:
Output
printf("Tuesday");
break; Enter day number(1-7):5
number(1
case 4: Thursday
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
Decision Making 33
Practice programs
1) Write a program to check whether entered character is vowel or not?
2) Write a program to perform Addition, Subtraction, Multiplication and Division of
2 numbers as per user’s choice (using if…else/Nested
if… if/Ladder if).
3) Write a program to read marks of five subjects. Calculate percentage and print
class accordingly. Fail below 35, Pass Class between 35 to 45, Second Class
between 45 to 60, First Class between 60 to 70, Distinction if more than 70.
4) Write a program to find out largest number from given 3 numbers (Conditional
operator).
5) Write a program to print number of days in the given month.
Decision Making 34
Thank you
Programming for Problem Solving
USING
{C}
Looping Programming
Life is all about Repetition.
We do same thing everyday
What is loop?
Loop is used to execute the block of code several times according to the condition
given in the loop. It means it executes the same code multiple times.
“Hello” 5
Output
printf("Hello\n"); Hello
printf("Hello\n"); Hello loop(condition)
{
printf("Hello\n"); Hello //statements
printf("Hello\n"); Hello }
printf("Hello\n"); Hello
Looping 3
if v/s while
False False
condition condition
True True
… …
Looping 4
Looping or Iterative Statements in C
Looping Statements are
Entry Controlled Loop: while, for
Exit Controlled Loop: do…while
Virtual Loop: goto
Looping 5
While loop
While Loop
while is an entry controlled loop
Statements inside the body of while are repeatedly executed till the condition is
true
while is keyword
Syntax
while(condition)
{
// Body of the while
// true part
}
Looping 7
WAP to print 1 to n(while loop)
Program Output
1 #include <stdio.h> Enter n:10
2 void main() 1
3 { 2
4 int i,n; 3
5 i=1; 4
6 printf("Enter n:"); 5
7 scanf("%d",&n); 6
8 while(i<=n) 7
9 { 8
10 printf("%d\n",i); 9
11 i=i+1; 10
12 }
13 }
Looping 8
WAP to print Odd numbers between 1 to n(while loop)
Line i n condition Process Output
Program 1 Linking header file
1 #include<stdio.h> 2 Calling void main()
3
2 void main() 4 1 Declarations
3 { 5 Enter value of
n
4 int i=1, n; 6 5 Scanning value of n 5
5 printf(“Enter the value of n”); 7 i <= n, TRUE While loop condition
6 scanf(“%d ”,&n); 8
9 i%2 != 0 TRUE If condition
7 while(i <= n) 10 Printing value of i 1
8 { 11 2 Incrementing value of i by 1
12 Jump to line:7
9 if(i%2!=0) 7 i <= n, TRUE While loop condition
10 printf(“%d/n”,i); 8
11 i=i+1; 9 i%2 != 0 FALSE If condition, skip line:10
11 3 Incrementing value of i by 1
12 } 12 Jump to line:7
13 } 7 i <= n, TRUE While loop condition
8
9 i%2 != 0 TRUE If condition
Output 10 Printing value of i 3
Enter the value of n 11 4 Incrementing value of i by 1
5 12 Jump to line:7
1
3
5 13 End of program
Looping 9
WAP to print multiplication table(while loop)
Program Output
1 #include<stdio.h> Enter n for multiplication table:5
2 void main() 5 * 1 = 5
3 { 5 * 2 = 10
5 * 3 = 15
4 int i=1,n;
5 * 4 = 20
5 printf("Enter n for multiplication table:");
table:" 5 * 5 = 25
6 scanf("%d",&n); 5 * 6 = 30
7 while(i<=10) 5 * 7 = 35
8 { 5 * 8 = 40
9 printf("%d * %d = %d\n",n,i,n*i);
); 5 * 9 = 45
10 i=i+1; 5 * 10 = 50
11 }
12 }
Looping 10
WAP to Sum of 5 numbers entered by user(while loop)
Program Output
1 #include<stdio.h> Enter a number=10
2 void main() Enter a number=20
3 { Enter a number=30
Enter a number=40
4 int sum=0, i=1,n;
Enter a number=50
5 while(i<=5) Sum is=150
6 {
7 printf("Enter a number=");
8 scanf("%d",&n);
9 sum=sum+n;
10 i=i+1;
11 }
12 printf("Sum is=%d",sum);
13 }
Looping 11
Looping
Loop Control in C, is the repeated execution of code, for a specified number of
times, if the condition is met.
loop (repeat 50
10 times)
{
printf
printf("*");
}
Looping 12
Syntax and Logic
Swimming Rules To Swim
1. Breath control
2. Kicking legs
3. Back stroke with arms
4. Front stroke with arms
5. Crawling in water
Syntax Logic
while(condition) int i = 1;
{ while (i <= 5)
// Body of the while {
// true part printf("%d\n", i);
} i=i+1;
}
Looping 13
How to build logic? Step-1
Step 1: Understand the problem statement
e.g. Write a program to find factors of a number.
Run following questions through mind
What is the factor of a number?
Factor is a number that divides another number evenly with no remainder.
For example, 1,2,3,4,6,12 are factors of 12.
How many variables needed? What should be their data types?(Inputs/Outputs)
To get number from user we need variable n.
Now we need to divide n with 1,2,3,...,n. For this we will declare a loop variable i initialized as 1.
Both variables should be of integer data type.
What control structure you require?
First we need a loop to divide n by 1,2,3,…,n,, loop will start from 1 and ends at n.
Inside loop we need if structure to check n%i==0
n%i (Number n is evenly divisible by i or not).
Looping 14
How to build logic? Step-2
Step 2: Think for 1 or 2 examples
Consider n=6, now take i=1
6%1==0, TRUE; So, 1 is factor of 6
6%2==0, TRUE; So, 2 is factor of 6
6%3==0, TRUE; So, 3 is factor of 6
6%4==2, FALSE; S0, 4 is not factor of 6
6%5==1, FALSE; S0, 5 is not factor of 6
6%6==0, TRUE; S0, 6 is factor of 6
From this we can infer that loop variable i starts with 1 and incremented by one
for next iteration then ends at value n.
Consider n=10, factors are 1,2,5,10
Consider n=11, factor is 1,11
From this we can infer that 1 and number itself are always factors of any number n.
Looping 15
How to build logic? Step-3
Step 3: Draw flowchart/steps on paper or in mind
Start
Steps
i=1 Step 1: Start
Step 2: Declare variables n,i
read n Step 3: Initialize variable
i ← 1
Step 4: Read value of n
i<=n? Step 5: Repeat the steps until i = n
True False 5.1: if n%i == 0
Display i
n%i==0? 5.2: i=i+1
True False Step 7: Stop
print i
i=i+1
Stop
Looping 16
How to build logic? Step-4
Step 4: Writing Pseudo-code
Pseudo-code
code is an informal way to express the design of a computer program or
an algorithm.
It does not require any strict programming language syntax.
Pseudo-code
Initialize i=1 integer
Declare n as integer
Input n
while i<n
if n%i
print i
end if
increment i=i+1
1
end while
Looping 17
WAP to find factors of a number(while loop)
Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i=1,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 while(i<=n)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 i=i+1;
12 }
13 }
Looping 18
WAP to print reverse a number(while loop)
Program Output
1 #include <stdio.h> Enter a number=1234
2 void main() 4321
3 {
4 int n;
5 printf("Enter a number=");
6 scanf("%d",&n);
7 while(n!=0)
8 {
9 printf("%d",n%10);
10 n=n/10;
11 }
12 }
Looping 19
WAP to check given number is perfect or not(while loop)
1 void main(){
2 int i=1,n,sum=0;
3 printf("Enter a number:"); Output
4 scanf("%d",&n); Enter a number:6
5 while(i<n) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0)
Output
8 {
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 i=i+1;
Output
13 }
14 printf("=%d",sum); Enter a number:496
1+2+4+8+16+31+62+124+248+=496
15 if(sum==n) 496 is a perfect number
16 printf("\n%d is a perfect number",n
,n);
17 else
18 printf("\n%d is not a perfect number",n);
number"
19 }
Looping 20
WAP to check given number is prime or not(while loop)
1 void main()
2 {
3 int n, i=2,flag=0; Output
4 printf("Enter a number:"); Enter a number:7
5 scanf("%d",&n); 7 is a prime number
6 while(i<=n/2)
7 {
Output
8 if(n%i==0)
9 { Enter a number:9
9 is not a prime number
10 flag=1;
11 break;
12 }
13 i++;
14 }
15 if (flag==0)
16 printf("%d is a prime number",n);
17 else
18 printf("%d is not a prime number",n
,n);
19 }
Looping 21
for loop
for Loop
for is an entry controlled loop
Statements inside the body of for are repeatedly executed till the condition is true
for is keyword
Syntax
for (initialization; condition; updateStatement)
{
// statements
}
Program Output
1 #include<stdio.h> Enter a number:5
2 void main() 1
3 { 2
4 int i,n; 3
5 printf("Enter a number:"); 4
6 scanf("%d",&n); 5
7 for(i=1;i<=n;i++)
8 {
9 printf("%d\n",i);
10 }
11 }
Looping 24
WAP to find factors of a number (for loop)
Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 for(i=1;i<=n;i++)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 }
12 }
Looping 25
WAP to check given number is perfect or not(for loop)
1 void main(){
2 int i,n,sum=0;
3 printf("Enter a number:"); Output
4 scanf("%d",&n); Enter a number:6
5 for(i=1;i<n;i++) 1+2+3=6
6 is a perfect number
6 {
7 if(n%i==0)
Output
8 {
9 printf("%d+",i); Enter a number:8
1+2+4+=7
10 sum=sum+i;
8 is not a perfect number
11 }
12 }
Output
13 printf("=%d",sum);
14 if(sum==n) Enter a number:496
1+2+4+8+16+31+62+124+248+=496
15 printf("\n%d is a perfect number",n
,n); 496 is a perfect number
16 else
17 printf("\n%d is not a perfect number",n);
number"
18 }
Looping 26
do while loop
do while Loop
do while is an exit controlled loop.
Statements inside the body of do while are repeatedly executed till the condition
is true.
Do and while are keywords. Syntax
do
{
// statement
}
while (condition);
Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(i%2!=0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
Looping 29
WAP to find factors of a number(do while loop)
Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(n%i==0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
Looping 30
WAP to print reverse a number(do while loop)
Program Output
1 void main() Enter a number=1234
2 { 4321
3 int n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 printf("%d",n%10);
9 n=n/10;
10 }
11 while(n!=0);
12 }
Looping 31
goto statement
goto Statement
goto is an virtual loop
The goto statement allows us to transfer control of the program to the specified
label.
goto is keyword
Syntax Syntax
goto label; label:
. .
. .
. .
label: goto label;
The label is an identifier. When the goto statement is encountered, the control of
the program jumps to label: and starts executing the code.
Looping 33
WAP to print Odd numbers between 1 to n(goto)
Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(i%2!=0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
Looping 34
WAP to find factors of a number(goto)
number(
Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(n%i==0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
Looping 35
Types of loops
Entry Control Loop Entry Control Loop Exit Control Loop Virtual Loop
int i=1; int i; int i=1; int i=1;
while(i<=10) for(i=1;i<=10;i++) do labelprint:
{ { { printf("%d",i++);
printf("%d",i++); printf("%d",i); printf("%d",i++); if(i<=10)
} } } goto labelprint;
while(i<=10);
False
Loop Body Label Statement
condition
True True
condition condition
Loop Body
False True False
goto
Looping 36
Pattern
Always detect pattern in pattern
Pattern
There are important points to note in pattern
1. Determine, how many rows?
2. Determine, how many numbers/characters/columns in a row?
3. Determine, Increment/Decrement among the number of rows.
4. Determine, starting in each row
1 1 1 *
11 12 23 * *
111 123 456 * * *
1111 1234 78910 * * * *
11111 12345 * * *
* *
*
Looping 38
WAP to print given pattern (nested loop)
* Program
** 1 void main()
*** 2 {
**** 3 int i,j;
***** 4 for(i=1;i<=5;i++)
;i++)
5 {
No. of rows: 5 6 for(j=1; j<=i;
j<= j++)
No. of characters 7 {
Row-1: * 8 printf
printf("*");
Row-2: ** 9 }
Row-3: *** 10 printf("\n"
n");
Row-4: **** 11 }
Row-5: ***** 12 }
Starting: *
Looping 39
WAP to print given pattern (nested loop)
1 Program
12 1 void main()
123 2 {
1234 3 int i,j;
12345 4 for(i=1;i<=5;i++)
;i++)
5 {
No. of rows: 5 6 for(j=1; j<=i;
j<= j++)
No. of values 7 {
Row-1: 1 8 printf
printf("%d",j);
Row-2: 12 9 }
Row-3: 123 10 printf("\n"
n");
Row-4: 1234 11 }
Row-5: 12345 12 }
Starting: 1
Looping 40
WAP to print given pattern (nested loop)
5 Program
54 1 void main()
543 2 {
5432 3 int i,j;
54321 4 for(i=5;i>0;i--
--)
5 {
No. of rows: 5
6 for(j=5; j>=i
j>= ; j--)
No. of values 7 {
Row-1: 5 8 printf
printf("%d",j);
Row-2: 54 9 }
Row-3: 543 10 printf("\n"
n");
Row-4: 5432 11 }
Row-5: 54321 12 }
Thank you
Programming for Problem Solving
USING
{C}
Array & Programming
Strings
Need of Array Variable
Suppose we need to store rollno of the student in the integer variable.
Declaration
int rollno;
float
Each character in the array occupies one byte of memory, and the last character
must always be null('\0').
The termination character ('\0') is important in a string to identify where the
string ends.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0
Initialization method 1:
char name[10]={'D','A','R','S','H','A','N'
'N','\0'};
Initialization method 2:
char name[10]="DARSHAN";
//'\0' will be automatically inserted at the end in this type of declaration.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0
gets(): Reads characters from the standard input and stores them as a string.
puts(): Prints characters from the standard.
standard
scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
gets(): Does not stop reading input when it encounters whitespace instead it
takes whitespace as a string.
Program
1 #include <stdio.h> Output
2 #include <string.h> //header file for string functions Enter string: CE Darshan
3 void main() 10
4 {
5 char s1[10];
6 printf("Enter string:");
7 gets(s1);
8 printf("%d",strlen(s1)); // returns length of s1 in integer
9 }
strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1, (s1,'i'));
Output : ir
strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1, (s1,"he"));
Output : heir
Thank you
Programming for Problem Solving
USING
{C}
Functions Programming
What is Function?
A function is a group of statements that perform a specific task.
It divides a large program into smaller parts.
A function is something like hiring a person to do a specific job for you.
Every C program can be thought of as a collection of these functions.
Program execution in C language starts from the main function.
Syntax
void main()
{
// body part
}
Why function ?
Avoids rewriting the same code over and over.
Using functions it becomes easier to write programs and keep track of what they doing.
Functions 2
Types of Function
Function
Functions 3
Program Structure for Function
When we use a user-defined
defined function program structure is divided into three parts.
Function Structure
void func1(); Function Prototype
void main()
{
....
func1(); Function call
}
void func1()
{
.... Function definition
//function body
....
}
Functions 4
Function Prototype and Function Definition
Syntax Example
Declaration
return-type function-name (arg-1, arg 2, …);
); void addition(int, int);
Definition
return-type function-name (arg-1, arg 2, …) void addition(int x, int y)
{ {
//... Function body printf("Addition is=%d“,(x+y));
} }
Functions 5
Function Prototype
A function Prototype also know as function declaration.
A function declaration tells the compiler about a function name and how to call the
function.
It defines the function before it is being used or called.
A function prototype needs to be written at the beginning of the program.
Syntax Example
return-type function-name (arg-1, arg 2, …);
); void addition(int, int);
Functions 6
Function Definition
A function definition defines the functions header and body.
A function header part should be identical to the function prototype.
Function return type
Function name
List of parameters
A function body part defines function logic.
Function statements
Syntax Example
return-type function-name (arg-1, arg 2, …) void addition(int x, int y)
{ {
//... Function body printf("Addition is=%d“,(x+y));
} }
Functions 7
WAP to add two number using add(int, int) Function
Program Output
1 #include <stdio.h> Addition is = 11
2 void add(int, int); // function declaration
3
4 void main()
5 {
6 int a = 5, b = 6;
7 add(a, b); // function call
8 }
9
10 void add(int x, int y) // function definition
11 {
12 printf("Addition is = %d", x + y);
13 }
Functions 8
Actual parameters and Formal parameters
Values that are passed to the called function from the main function are known
as Actual parameters.
The variables declared in the function prototype or definition are known as Formal
parameters.
When a method is called, the formal parameter is temporarily "bound" to the
actual parameter.
Functions 9
Return Statement
If function is returning a value to calling function, it needs to use the keyword
return.
The called function can only return one value per call.
Syntax
return;
Or
return (expression);
Functions 10
WAP to find maximum number from two number
Program Output
1 #include <stdio.h> Max value is : 200
2 int max(int a, int b);
3 void main()
4 {
5 int a = 100;
6 int b = 200;
7 int maxvalue;
8 maxvalue = max(a, b);
9 printf("Max value is : %d\n",
10 maxvalue);
11 }
12 int max(int a, int b)
13 {
14 if (a > b)
15 return a; // return a
16 else
17 return b; // return b
18 }
Functions 11
WAP to calculate the Power of a Number
Program Output
1 #include <stdio.h> Enter any number : 5
2 int power(int, int); Enter power of number : 3
3 void main() 5's power 3 = 125
4 {
5 int num, pow, res;
6 printf("Enter any number : ");
7 scanf("%d", &num);
8 printf("Enter power of number : ");
9 scanf("%d", &pow);
10 res = power(num, pow);
11 printf("%d's power %d = %d", num,
, pow, res);
12 }
13 int power(int n, int p)
14 { int r = 1;
15 while (p >= 1)
16 {
17 r = r * n;
18 p--;
19 }
20 return r;}
Functions 12
WAP to find Factorial of a Number
Program Output
1 #include <stdio.h> Enter the number :
2 int fact(int); 5
3 int main() factorial = 120
4 {
5 int n, f;
6 printf("Enter the number :\n");
7 scanf("%d", &n);
8 f = fact(n);
9 printf("factorial = %d", f);
10 }
11 int fact(int n)
12 {
13 int i, fact = 1;
14 for (i = 1; i <= n; i++)
15 fact = fact * i;
16 return fact;
17 }
Functions 13
WAP to check Number is Prime or not
Program Program contd.
1#include <stdio.h> 14 int checkPrime(int n1)
2int checkPrime(int); 15 {
3void main() 16 int i = 2;
4{ 17 while (i <= n1 / 2)
5 int n1, prime; {
6
18
printf("Enter the number :"); if (n1 % i == 0)
7 scanf("%d", &n1); 19 return 0;
8 prime = checkPrime(n1); 20 else
9 if (prime == 1) 21 i++;
10 printf("The number %d is a prime 22 }
number.\n", n1); 23 return 1;
11 else 24 }
12 printf("The
"The number %d is not a prime
number.\n", n1);
13 }
Output
Enter the number :7
The number 7 is a prime number.
Functions 14
Category of Function
(1) Function with no argument and but no return value
No
void main() Input void fun1()
{ {
..... .....
No return
fun1(); .....
value
..... .....
} }
Functions 15
Category of Function cont.
(3) Function with argument and but no return value
Value of
void main() Argument void fun1(int f)
{ {
..... .....
fun1(a); No Return .....
..... value .....
} }
Functions 16
Storage Classes
Storage class decides the scope, lifetime and memory allocation of variable.
Scope of a variable is the boundary within which a variable can be used.
Storage Initial
Storage Scope Life Example
Specifier Value
Automatic int a;
Stack Garbage Within block End of block
{auto} auto int a;
Till end of
Static Data Zero Within block static extern int var;
program
{static} segment static int var;
Functions 17
Static Example
Program Output
1 #include <stdio.h> Counter = 1
2 int incrementCounter(); Counter = 2
3
4 void main()
5 {
6 printf("Counter = %d \n", incrementCounter());
incrementCounter
7 printf("Counter = %d \n", incrementCounter
incrementCounter());
8 }
9
10 int incrementCounter()
11 {
12 static int count = 0; // static variable
13 count++;
14 return count;
15 }
Functions 18
Advantages of Function
Using function we can avoid rewriting the same logic or code again and again in a
program.
We can track or understand large program easily when it is divide into functions.
It provides reusability.
It help in testing and debugging because it can be tested for errors individually in
the easiest way.
Reduction in size of program due to code of a function can be used again and
again, by calling it.
Functions 19
Practice Programs
1) WAP to count simple interest using function.
2) WAP that defines a function to add first n numbers.
3) WAP using global variable, static variable.
4) WAP that will scan a character string passed as an argument and convert all
lowercase character into their uppercase equivalents.
5) Build a function to check number is prime or not. If number is prime then
function return value 1 otherwise return 0.
6) Write a program to calculate nCr using user defined function. nCr = n! / (r! * (n-
r)!)
7) Create a function to swap the values of two variables.
8) Write a function which takes 2 numbers as parameters and returns the gcd of the
2 numbers. Call the function in main().
Functions 20
Thank you
Programming for Problem Solving
USING
{C}
Pointer Programming
What is Pointer?
A normal variable is used to store value.
A pointer is a variable that store address / reference of another variable.
Pointer is derived data type in C language.
language
A pointer contains the memory address of that variable as their value. Pointers are
also called address variables because they contain the addresses of other variables.
Pointer 2
Declaration & Initialization of Pointer
Syntax Output
1 datatype *ptr_variablename; 10 10 5000
Example
1 void main()
2 { Variable Value Address
3 int a=10, *p; // assign memory address of a
4 to pointer variable p a 10 5000
5 p = &a;
6 printf("%d %d %d", a, *p, p); p 5048
7 }
5000
Pointer 4
Pointer to Pointer – Double Pointer
Pointer holds the address of another variable of same type.
When a pointer holds the address of another pointer then such type of pointer is
known as pointer-to-pointer or double pointer.
pointer
The first pointer contains the address of the second pointer, which points to the
location that contains the actual value.
Syntax
Pointer Pointer Variable
1 datatype **ptr_variablename;
address address value
Example
1 int **ptr;
Pointer 5
Write a program to print variable, address of pointer variable and pointer to pointer variable.
Program
WAP to print Odd numbers between 1 to n
1 #include <stdio.h>
2 int main () {
3 int var;
4 int *ptr;
5 int **pptr;
6 var = 3000;
7 ptr = &var; // address of var
8 pptr = &ptr; // address of ptr using address of operator &
9 printf("Value of var = %d\n", var );
10 printf("Value available at *ptr = %d\n",
, *ptr
* );
11 printf("Value available at **pptr = %d\n",
%d **pptr);
12 return 0;
13 }
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Pointer 6
Relation between Array & Pointer
When we declare an array, compiler allocates continuous blocks of memory so that
all the elements of an array can be stored in that memory.
The address of first allocated byte or the address of first element is assigned to an
array name.
Thus array name works as pointer variable.
variable
The address of first element is also known as base address.
Pointer 7
Relation between Array & Pointer – Cont.
Example: int a[10], *p;
a[0] is same as *(a+0), a[2] is same as *(a+2)
*(a+ and a[i] is same as *(a+i)
Pointer 8
Array of Pointer
As we have an array of char, int, float etc, same way we can have an array of pointer.
Individual elements of an array will store the address values.
So, an array is a collection of values of similar type. It can also be a collection of
references of similar type known by single name.
Syntax
1 datatype *name[size];
Example
1 int *ptr[5]; //declares an array of integer pointer of size 5
Pointer 9
Array of Pointer – Cont.
An array of pointers ptr can be used to point to different rows of matrix as follow:
Example
1 for(i=0; i<5; i++)
2 {
3 ptr[i]=&mat[i][0];
4 }
ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
Output
Enter value of num1 and num2: 5
10
Before Swapping: num1 is: 5, num2 is: 10
After Swapping: num1 is: 10, num2 is: 5
Pointer 11
Pointer and Function
Like normal variable, pointer variable can be passed as function argument and
function can return pointer as well.
There are two approaches to passing argument to a function:
Call by value
Call by reference / address
Pointer 12
Call by Value
In this approach, the values are passed as function argument to the definition of
function.
Program Output
1 #include<stdio.h> Values before calling 10, 20
2 void fun(int,int); Values after calling 10, 20
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
);
7 fun(A,B); Address 48252 24688
8 printf("\nValues after calling %d, %d",A,B);
);
9 return 0; Value 10 20 10 11 20 22
10 }
11 void fun(int X,int Y) Variable A B X Y
12 {
13 X=11;
14 Y=22;
15 }
Pointer 13
Call by Reference / Address
In this approach, the references / addresses are passed as function argument to the
definition of function.
Program
Output
1 #include<stdio.h>
Values before calling 10, 20
2 void fun(int*,int*); Values after calling 11, 22
3 int main()
4 {
5 int A=10,B=20;
6 printf("\nValues before calling %d, %d",A,B);
);
7 fun(&A,&B); Address 24688
48252
8 printf("\nValues after calling %d, %d",A,B);
);
9 return 0; Value 10 11 20 22 48252 24688
10 }
11 void fun(int *X,int *Y) Variable A B *X *Y
12 {
13 *X=11;
14 *Y=22;
15 }
Pointer 14
Pointer to Function
Every function has reference or address, and if we know the reference or address of
function, we can access the function using its reference or address.
This is the way of accessing function using pointer.
Syntax
1 return-type (*ptr-function)(argument
function)(argument list);
return-type: Type
ype of value function will return.
argument list: Represents the type and number of value function will take, values
are sent by the calling statement.
(*ptr-function): The parentheses around *ptr-function
* tells the compiler that it is
pointer to function.
If we write *ptr-function without parentheses then it tells the compiler that ptr-
function is a function that will return a pointer.
Pointer 15
Write a program to sum of two numbers using pointer to function.
Program
WAP to print Odd numbers between 1 to n
1
2
#include<stdio.h>
int Sum(int,int);
Output
Enter 1st number : 5
3 int (*ptr)(int,int);
4 int main() Enter 2nd number : 10
5 {
6 int a,b,rt; The sum is : 15
7 printf("\nEnter 1st number : ");
8 scanf("%d",&a);
9 printf("\nEnter 2nd number : ");
10 scanf("%d",&b);
11 ptr = Sum;
12 rt = (*ptr)(a,b);
13 printf("\nThe sum is : %d",rt);
14 return 0;
15 }
16 int Sum(int x,int y)
17 {
18 return x + y;
19 }
Pointer 16
Practice Programs
1. Write a C program to print the address of variable using pointer.
2. Write a C a program to swap two elements using pointer.
pointer
3. Write a C a program to print value and address of a variable
4. Write a C a program to calculate sum of two numbers using pointer
5. Write a C a program to swap value of two numbers using pointer
6. Write a C a program to calculate sum of elements of an array using pointer
7. Write a C a program to swap value of two variables using function
8. Write a C a program to print the address of character and the character of string using pointer
9. Write a C a program for sorting using pointer
Pointer 17
Thank you