Professional Documents
Culture Documents
C Notes 2020
C Notes 2020
C
PROGRAMMING
First Year Engineering
Semester II – Common to all Branches
By Nitin Sir
Nitin Sir
Module Detailed Content Hrs.
01 Introduction to Computer, Algorithm and 06
Flowchart.
1.1 Basic of computer : Turing Model, Von
Neumann Model, Basics of Positional
Number Systems, Introduction to
Operating Systems and component of an
operating system.
1.2 Algorithm & Flowchart: Three construct
of algorithm and flowchart : Sequence,
Decision and reparation.
02 Fundamentals of C-Programming 06
2.1 Character set, Identifier and Keywords,
Data types, Constants, Variables.
2.2 Operators: Arithmetic, Relational and
Logical, Assignment, Unary, Conditional,
Bitwise, Comma, other operators.
Expression, Statements, Library functions,
Pre-processor.
2.3 Data Input and Output: getchar(),
putchar(), scanf(), printf(), gets(), puts().
03 Control Structures 12
3.1 Branching: If statement, if-else statement,
multiway decision.
3.2 Looping: while, do-while, for
3.3 Nested control structure : switch
statement, continue statement break
statement, goto statement
04 Functions and Parameter 06
4.1 Function: Introduction of function,
function main, defining a function,
accessing a function, function prototype,
passing arguments to a function, recursion.
4.2 Storage Classes: auto, externs, static,
register.
The Turing model forms the basis of software development. it shows the
behaviour expected from the system to be designed. Using a Turing model, one
can design and develop the step expected in the procedural oriented
programming
e.g. (𝟓)𝟏𝟎 = ( ? )𝟐
Quotient Remainder
2 5
2 2 1
2 1 0
0 1
(𝟓)𝟏𝟎 = (𝟏 𝟎 𝟏)𝟐
Binary to decimal:
= 1 1 1 0 0
= 16+8+4+0+0
= (28)10
Steps:
Hexa Decimal Number System (Base 16. Digits used: 0 to 9, Letters used: A-
F)
These numbers are used extensively in microprocessor work.The hexadecimal
number system has a base of 16, and hence it consists of the following sixteen
number of digits.
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
Steps:
(2861)10 = (B2D)16
There are various operations that are performed on binary data like AND,
OR, EXOR and NOT.
1. AND: The output is 1 if and only if A AND B (A&B being the inputs) are 1.
0 1 0
1 0 0
1 1 1
0 1 1
1 0 1
1 1 1
A(INPUT) Y(OUTPUT)
0 1
1 0
0 1 1
1 0 1
1 1 0
Defining a Problem
Algorithm development
Program implementation
PROPERTIES OF ALGORITHM
Q. 4) Points to consider while developing an algorithm
1. The algorithms should always begin with “START” and end with “STOP”.
2. To accept input from the user, we will use “INPUT” or the “READ”.
3. To display output on the monitor, we will use “PRINT” statement. The
words to be displayed as it is will be written in double quotes while the
variables whose values are to be displayed will not be in double quotes.
4. We will use the basic arithmetic operators to indicate the operations.
5. We will use “AND”, “OR” and “NOT” to indicate conjunction, disjunction
and negation respectively.
6. To check conditions we can use the “IF” “THEN” and “ELSE”
CONSTRUCTS.
7. To Jump from one step to another the construct used is “GOTO”, statement
is always associated with a step number
• Algorithm
Step I : Start
Step II : Input a number
Step III : Calculate the square of the user entered number.
Step IV : Display the calculated result.
Step V : Stop
• Pseudo code
Step I : START
Step II : PRINT “Enter a number”
Step III : Input n
Step IV : a=n*n
Step V : PRINT a
Step VI : STOP
• Algorithm
Step I : Start
Step II : Input two numbers.
Step III : Calculate product of two number.
Step IV : Display product.
Step V : Stop
• Pseudo code
Step I : START
Step II : PRINT “Enter two numbers”
Step III : Input a,b
Step IV : x=a*b
Step V : PRINT x
Step VI : STOP
• Algorithm
Step I : Start
Step II : Initialize the counter with value as 1
Step III : Check if counter is greater than 10, if yes then goto step VII.
Step IV : Display the value of counter variable.
Step V : Increment the counter variable.
Step VI : Goto step III
Step VII : Stop
• Pseudo code
Step I : START
Step II : i=1
Step III : IF i>10 THEN GOTO Step VII.
Step IV : PRINT i
Step V : i=i+1
Step VI : GOTO step III
Step VII : STOP.
• Algorithm
Step I : Start
Step II : Input a number
Step III : Initialize the counter with value as 1.
Step IV : Check if counter is greater than user entered number, if yes
then goto step VIII.
Step V : Multiply the fact variable with counter value.
Step VI : Increment the counter variable.
Step VII : Goto step IV
Step VIII : Display the value of factorial.
Step IX : Stop
• Pseudo code
Step I : START
Step II : PRINT “Enter a number”
Step III : Input n.
Step IV : i=1, fact=1;
Step V : IF i>n THEN GOTO step IX.
Step VI : fact=fact*i
Step VII : i=i+1;
Step VIII : GOTO step V;
Step IX : PRINT fact;
Step X : STOP.
Step I : START
Step II : Input N as size of the list
Step III : PRINT ‘Enter list of elements’
Step IV : For I ←0 to N – 1 DO Repeat step 5
Step V : INPUT A[I]
Step VI : FOR I←N – 1 DOWNTO 1 DO Repeat step 7
Step VII : FOR j←0 TO I – 1 DO Repeat step 8
Step VIII: IF A[j] > A[j+1] THEN
Begin
TEMP ← A[j]
A[j] ← A[j+1]
Time complexity for the above algorithm must be measured for the average case
as well as worst case (array is in descending order ).When we have N elements
than the number of comparisons required for sorting the complete list will be
given as follows.
Number of comparison = (N – 1) + (N – 2)+……….+2+ 1
=(N(N-1)) / 2 = (𝑁 2 -N) / 2
Time complexity of this algorithm will be O(𝑁 2 ) in average case as well as
worst case.
Product=num1 X num2
Display product
STOP
START
Accept a
num
Mult=num x num.
Display Mult
STOP
ALGORITHM
Start
Step 1: Input A, B
Step 2: IF (A>B) THEN
Read A, B
MAX=A
ELSE
IS
MAX=B
A>B
END IF
Step 3: PRINT “The largest value is”, MAX Max=A Max=B
Display
Max
End
ALGORITHM
Start
Step 1: Input num
Step 2: IF (num%2==0) THEN
Read num
PRINT “the number is even”;
ELSE
IS
PRINT “the number is odd”; num%2=0
END IF
Step 3: STOP Print “The number is even” Print “The number is odd”
End
Step 1: Start.
Step 3: N=N+1
Step 4: SUM=SUM+N
Step 7: End.
Step 2 : d sqrt (𝑏 2 − 4 × 𝑎 × 𝑐)
−𝑏+𝑑
dsqrt(𝒃𝟐 − 𝟒 × 𝒂 × 𝒄)
Step 3 : x1 ( )
2×𝑎
Step 4 : x2 (
−𝑏−𝑑
) x1(–b + d) / (2 x a)
2×𝑎
Print
x1 ,x2
STOP
Features of ‘C ’
1) It is a procedural language
2) It is high level language
3) It is used for software development.
4) ‘C’ language is a first step for programmer to start
5) It is reliable, simple , & easy to use.
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
/* Comments */
This is a comment block, which is ignored by the compiler. Comment
can be used anywhere in the program to add info about the program or
code block, which will be helpful for developers to understand the existing
code in the future easily.
#include<stdio.h>
int/void main()
int/void is a return value, which will be explained in a while.
This is the main function, which is the default entry point for every C
program and the void in front of it indicates that it does not return a value.
Braces
Curly braces which shows how much the main() function has its scope.
printf()
return 0
CHARACTER SET OF C
Character Set Example
Alphabets (Upper case and A, B, C ……Z
lower case) a, b, c …….z
Digits (numbers) 0, 1, 2, 3. .. .. . .. 9
Special Symbol @, #, $, ^, &, *, +, _, /, <, >
KEYWORDS:-
• There are some special words that have a predefined meaning for the C
compiler known as keywords.
• Keywords are a set of words which are reserved for the certain operations and
hence are also sometimes referred as reserved words.
• These words cannot be used as identifiers.
• There are 32 Keywords in C
• The keywords used in C are as given below:
auto double Int struct
break else Long switch
case enum register typedef
char extern Return union
const float Short unsigned
continue for signed void
default goto Sizeof volatile
do if Static while
DATA TYPES IN C :-
• What type of data can a variable hold is called data type?
• The data type decides the type of data required for storing in the memory.
• The data types of C can be divided into two types: primary and secondary data
types.
Declaration
#include <stdio.h>
#include<conio.h>
void main ()
{
float area, r, circ;
const float pi=3.14;
printf ("Enter a radius of circle: ");
scanf ("%f", & r);
area = pi * r * r;
circ = 2 * pi * r;
printf ("Area of Circle is %f \n",area);
printf ("Circumference of circle is %f \n",circ);
return (0);
}
ESCAPE SEQUENCES
• Escape sequence is a character followed by a backslash (\).
• They are used specially to perform some operations like going to new line,
providing a horizontal tab, vertical tab etc.
• The following is a list of escape sequences.
\n Newline
\t Horizontal Tab
\v Vertical Tab
\b Backspace
\r Carriage Return
OPERATORS
• Operators are different symbols used to perform operations on operands.
• The operators are one of the tokens of C.
• There are different types of operators classified based on their functions
Unary Operators
o These are operators that require only one operand
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
float b;
clrscr();
printf(“enter float number”);
scanf(“%f”.&b);
a = (int)b;
printf(“the integer part of the number is %d”,a);
getch();
}
output:
enter a float number : 3.14
the integer part of the number is: 3
#include<stdio.h>
#include<conio.h>
void main()
{
int x=4, y=9;
int z;
z=(x++)+(--y)+y;
Printf(“Value=%d\n”,z);
z=(--x)+x+(y--);
printf(“Value=%d\n”,z);
getch();
}
O/P : Value=20
Value=16
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10, y , z;
z=y=x;
y-=--x;
z-=x--;
x-=--x-x--;
printf(“x=%d y=%d z=%d”, x, y, z);
}
O/P: x=6 y=1 z=1
5. Size of operator
This operator is used to know the size of variable required to store value in
memory.
Size of operator can also find size of a data type.
e.g
1. sizeof(int) will return value as 2.
2. char a;
sizeof(a); will return 1
Binary Operators: -
Operators that require two operands are called as binary operators.
1. Arithmetic Operators:-
• This are set of operators used to perform basic arithmetic operations like
addition, subtraction, multiplication and division.
• There are five operators in this set. They are :
1. + to find the sum
2. - to find the difference
3. * to find the product
4. / to find the quotient after division
5. % to find the remainder after division
Division ‘/’ operator is used to find quotient and MOD ‘%’ operator is
used to find remainder after division of two numbers.
2. Bitwise operators :-
3. Logical operators :-
• Logical operators are used to evaluate conditions or expressions.
• The logical operators are AND and OR.
• AND Operator (&)
o The AND operators checks for all conditions to be true then only it
returns true else false.
o For example a statement
o y >5 && y <10;
o will result in “true” i.e. 1 if the value of y is greater than 5 AND
less than 10, else it will result in false i.e.0
• OR Operator :-
o The OR operator checks for any one or all conditions from the
given conditions to be true then it evaluates true.
o Otherwise if all conditions are false then it returns false.
o For example a statement
o y >5 || y <10;
o will result in “true” i.e. 1 if the value of y is greater than 5 OR less
than 10, else it will result in false i.e.0
4. Relational Operator: -
• The relational operators are used to test the relation between two variables or
a variable and constant.
• The operators like
o ‘<’ (less than)
o >’ (greater than)
o “= =” (equality operator)
o ‘<=’ (less than equal to)
o ‘>=’ (greater than equal to)
o ‘!=’ (not equal to)
Conditional Operators
• Conditional operator is also known as ternary operator.
• The operator that requires three operands is called as ternary operator.
• Syntax :
(Condition)? Expr1 : Expr2 ;
• It checks for the condition if condition is true then expr1 will be executed
otherwise expr2 will be executed.
E.g. max= (a > b)? a : b;
• This will put the value of a into max if condition is true else the value of b
into max
Write a program to accept two numbers from user and display greatest of
two numbers using conditional operator.
#include<stdio.h>
#include<conio.h>
Void main()
{
int n1 , n2, greater;
printf(“Enter a two number”);
scanf(“%d %d”,&n1,&n2);
greater=(n1>n2)?n1:n2;
printf(“The greater number is: %d”,greater);
getch();
}
Write a program to accept three numbers from user and display the
greatest of three using the conditional operator.
#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,n3,greater;
clrscr();
printf(“enter three numbers\n”);
scanf(“%d %d %d”,&n1,&n2,&n3);
Nitin Sir Page 30
greater = (n1>n2)?((n1>n3)?n1:n3): ((n2>n3)?n2:n3));
printf(“the largest number is : %d ”,greater);
getch();
}
Output:
enter three numbers
234
23
33
the largest number is : 234
1. Formatted IO Functions
Two formatted IO functions in C
o printf() :- display a data on monitor.
o scanf() :- accept data from keyboard.
printf() :-
Example :
printf(“ The simple interest is %f”, si);
This statement will print the output where the format specifier % f will be
replaced with the float type value of the variable si.
This statement is used to accept a int type value from user in the variable x.
2. Unformatted IO Functions
• The unformatted IO functions do not have any format specifier. They are mostly
used to accept and display only one character or a string (string is a set of
characters to make a word or sentence).
1. getch () : This function is used accept one character from the user.
2. getche () : This function is used accept one character from the user and echo
it to screen (accept input without pressing enter).
3. getchar () : This function is used to accept one character from the user and
echo it (display it on the screen) and also wait after that for the user to press
the enter key.
4. gets () : This function is used to accept a string from the user. We will see in
details of this when studying the chapter on strings.
5. putch() or putchar() :These functions are used to display a character on the
monitor.
6. puts : This function is used to display a string on the monitor.
1. Runtime Errors
2. Compile Errors
3. Logical Errors
C RUNTIME ERRORS are those errors that occur during the execution of a c
program
These types of error are hard to find as the compiler doesn’t point to the line at
which the error occurs.
COMPILE ERRORS
Compile errors are those errors that occur at the time of compilation of the
program. C compile errors may be further classified as:
SYNTAX ERRORS
When the rules of the c programming language are not followed, the compiler
will show syntax errors.
LOGICAL ERRORS
Logical errors are the errors in the output of the program. The presence of
logical errors leads to undesired or incorrect output and are caused due to error
in the logic applied in the program to produce the desired output.
Also, logical errors could not be detected by the compiler, and thus,
programmers has to check the entire coding of a c program line by line.
Programs
C Program to Calculate Simple Interest
#include<stdio.h>
#include<conio.h>
void main()
{
#include <stdio.h>
#include <conio.h>
void main()
{
int x , y ;
printf("Enter two integers: ") ;
scanf("%d %d" , &x , &y) ;
printf("x=%d y=%d \n" , x , y) ;
x=x+y ;
y=x-y ;
x=x-y ;
printf("After swapping: \n") ;
printf("x=%d y=%d" , x , y) ;
Nitin Sir Page 34
getch() ;
}
Output:
Enter two integers: 5 8
x=5 y=8
After swapping:
x=8 y=5
WAP to accept the length and breadth of a rectangle from the user.
Calculate and display the area and perimeter.
#include<stdio.h>
#include<conio.h>
void main ()
{
float length, breadth, area, perimeter; clrscr():
printf (“Enter the length and breadth of the rectangle:”);
scanf(“%f%f”, &lenghth, & breadth);
area = length * breadth;
perimeter = 2* (length + breadth);
printf(“The area of rectangle is = % f and its perimeter is = % f”, area,
perimeter);
getch();
}
Output:
Enter the length and breadth of the rectangle: 10
15
The area of rectangle is 150.000000 and its perimeter is = 50.000000
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c;
float x1,x2;
clrscr(0;
printf (Enter the coefficients of the quadratic equation :”);
Output:
2
3
#include<stdio.h>
#include<conio.h>
void main()
int x=1;
clrscr();
printf (“%d”%d%d\n”,x,(x=x+2),(x<<2));
x<<2;
printf (“%d”%d%d\n”,++x,++,++x);
getch();
Output
334
644
ii) 5 + 5 = = 10 | | 1 + 3 = = 5 ans: 1
Control Structures
1. If Statement
2. If – else Statement
3. Nested if- else Statement
4. Switch – Case
1. If Statement
Syntax
If (condition)
{
Statements1;
}
the condition given with the if statement is true. Then statements1 are
executed in this case.
If the condition specified in the if statements is false then the statements
named as statements1 are not executed in this case.
2. If Else Statement
Syntax
If (condition)
{
Statements-1;
}
else
{
Statements-2;
}
• The set of statements named as statements 1 in the above syntax are executed
if the condition given with the if statement is true.
• If the condition specified in the if statements is false then the statements
named as statements2 in the above syntax are executed.
3. Nested if-else
In some cases we have to check multiple cases of a particular condition. In
such cases we have to use an nested if-else.
Syntax:
If (condition-1)
{
if(condition-2)
statement1;
else
statement2;
}
else
{
if(condition-3)
statement13;
else
statement4;
}
In this case the first condition is checked, if it is true then statements inside that
if block are executed. But if the condition is false it goes to the else statement.
Again there is a condition with if; the statements are executed if this second
condition is true. Else it again goes to the else and again checks the condition
associated with this if statement.
4. Else if ladder
If condtion1 is true then statement1 will be executed otherwise condition2 will
be check if it is true then statment2 will be executed otherwise statement 3 will
be executed.
Syntax:
If(condition1)
{
Statment1;
}
elseif(condition2)
{
Statment2;
}
else
{
Statment3;
}
#include <stdio.h>
#include <conio.h>
void main()
{
int marks;
printf(“Enter the marks\n”);
scanf(“%d, &marks);
if(marks>=70)
{
printf(“Distinction”);
}
elseif(marks>=60)
{
printf(“First Class”);
}
elseif(marks>=40)
{
printf(“Second Class”);
}
else
{
printf(“Fail”);
}
getch();
}
• Value in the case statement must be integer or character and value must
be unique.
• If case value did not matched then default block gets executed.
Nitin Sir Page 42
• Using switch-case the if-else ladder can be implemented in a much better
way.
Switch (variable or condition)
{
case value1:
Statement1;
Break;
case value2:
Statement2;
Break;
case value3:
Statement3;
Break;
default:
Statement default;
}
Switch Ladder of if else
The keyword switch is used only once. The keyword if and else are used many
time
The keyword case is used many times. The logical OR(I I)operator used many
That is because many cases are to be times to manage the condition.
written.
The break statement is to used to take When all the condition expressions goes
the control out of switch. If all the false the final else part is used to take the
comparisons are a failure then default final action.
part comes in picture.
#include <stdio.h>
#include <conio.h>
void main()
{
int ch,a=10,b=20;
float ans;
printf("\nMenu");
printf("\n1.ADD\n2.Sub\n3.Mul\n4.Div");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
ans = a + b;
printf("\nRes is %f",ans);
break;
case 2:
ans = a - b;
printf("\nRes is %f", ans);
break;
case 3:
ans = a * b;
printf("\nRes is %f", ans);
break;
case 4:
ans = a / b;
printf("\nRes is %f", ans);
break;
default:
printf("\nWrong ch");
}//end of switch
getch();
return 0;
}
#include <stdio.h>
#include <conio.h>
void main()
{
int m ;
clrscr() ;
printf("Enter a month number: ") ;
scanf("%d" , &m) ;
printf("Month in words is: ") ;
switch(m)
{
case 1: printf("January") ;
break ;
case 2: printf("February") ;
break ;
case 3: printf("March") ;
break ;
case 4: printf("April") ;
break ;
case 5: printf("May") ;
break ;
case 6: printf("June") ;
break ;
case 7: printf("July") ;
break ;
case 8: printf("August") ;
break ;
case 9: printf("September") ;
break ;
case 10: printf("October") ;
break ;
case 11: printf("November") ;
break ;
case 12: printf("December") ;
break ;
default: printf("\nWrong Input") ;
break ;
Nitin Sir Page 45
}
getch() ;
}
FOR LOOP
o/p
Hello
Hello
Hello
.
.
. Hello
#include <stdio.h>
#include <conio.h>
void main()
{
int n,i, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(i=1;i<=n;i++) //for loop terminates if count>n
{
sum=sum+i;
}
printf("Sum=%d",sum);
return 0;
}
Output:-
Enter the value of n.
5
Sum=15
WHILE LOOP
• While and do-while loops are also for iterative operation.
• The while loop is used when you want to execute a block of code repeatedly
with checked condition before making iteration.
Syntax:
While (condition)
{
Statements;
}
• The operation of the while loop is such that, first the condition is checked. If
the condition is true, then the statements are executed. Once the statements
are executed, the condition is again checked and this keeps on repeating, until
the condition is false. If the condition is false, the statements insides the loop
is not executed, instead the control directly comes out of the loop.
#include <stdio.h>
#include <conio.h>
int main()
{
int n, reverse=0, rem,temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp=n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
temp=n/10;
}
if(reverse==temp)
{
printf("%d is a palindrome.",n);
}
else
{
printf("%d is not a palindrome.",n);
}
return 0;
}
#include <stdio.h>
int main()
{
int num, sum = 0, temp, rem;
printf("Enter an integer\n");
scanf("%d",&num);
temp = num;
while( num != 0 )
{
rem = num%10;
sum = sum + rem *rem *rem;
Nitin Sir Page 49
num = num/10;
}
if (temp == sum )
printf("Entered number is an armstrong number.\n");
else
printf("Entered number is not an armstrong number.\n");
return 0;
}
DO-WHILE LOOPS
Eg:-
i=10;
do
{
printf(“%d”);
i++;
} While (i! =0);
4. If the exp2 is false in the If the condition is false Since the statement
first iteration then in the first iteration part is executed first
statement part will not then statement part will and then the condition
executed. not be executed. is checked so
statement will be
always executed at
least once.
5. e.g. e.g.
for(i=1;i<=5;i++) i=1; e.g.
printf(“%d”,i); while(i<=5) i=1;
printf(“%d”,i++); do
will result into output will result into output printf(“%d”,i++);
12345. 12345. while(i<=5);
will result into output
12
*
**
***
****
…
#include <stdio.h>
#include <conio.h>
void main()
{
int i , j , n ;
printf("Enter the number of lines: ") ;
scanf("%d" , &n) ;
printf("Required pattern is as follows: \n") ;
for(i=1 ; i<=n ; i++)
{
for(j=1 ; j<=i ; j++)
{
printf("*”) ;
}
printf("\n") ;
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j ;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch();
}
Write a program to display the following asking the user for the number of
lines in the upper half.
*
***
*****
*******
*********
********
*****
***
*
#include<stdio.h>
#include<conio.h>
void main
{
int i, j, n;
clrscr();
printf(“Enter the number of lines in the upper half:”);
scanf (“%d”,&n);
for (i=1;i<=n;i++)
{
for(j=1;j<=n-I;j++)
{
printf(“ ”);
}
for(j=1;j<=2*i-1;j++)
{
printf(“* ”);
Nitin Sir Page 58
}
for(i=n-1;i>=1;i--)
{
printf(“ ”);
for(j=1;j<=2*i-1;j++)
{
printf(“* ”);
}
printf(“\n ”);
}
getch();
}
Output
Enter the number of lines in the upper half:5
*
***
*****
*******
*********
********
*****
***
*
Write a program to display the following asking the user for the number of
lines.
1
121
12321
1234321
123454321
12345654321
#include<stdio.h>
#include<conio.h>
void main()
{
int i , j , n;
clrscr();
printf(“enter the number of lines”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
Nitin Sir Page 59
{
for(j=1;j<=n-i;j++)
{
printf(“ ”);
}
for(j=1;j<=i; j++)
{
printf(“%d”,j);
}
for(j=i-1;j>=1;j--)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}
OUTPUT:
enter the number of lines : 6
1
121
12321
1234321
123454321
12345654321
Write a program to display the following asking the user for the number of
lines.
1
232
34543
4567654
567858765
#include<stdio.h>
#include<conio.h>
void main()
{
int i , j , n, k;
clrscr();
printf(“enter the number of lines”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
Nitin Sir Page 60
{
printf(“ ”);
}
k=i;
for(j=1;j<=i; j++)
{
printf(“%d”,k);
k--;
}
k=2*i-2;
for(j= 1;j<=i ;j++)
{
printf(“%d”,k);
k--;
}
printf(“\n”);
}
getch();
}
OUTPUT:
enter the number of lines : 6
1
121
12321
1234321
123454321
OUTPUT:
Enter the number of lines: 5
1
21A
321AB
4321ABC
54321ABCD
#include<stdio.h>
#include<conio.h>
void main
{
int i, j, N;
printf("Enter N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
printf("\n");
}
getch();
}
#include<stdio.h>
void main()
{
int i,j,k;
for(i=0 ; i<=4 ; i++)
{
for(j=4 ; j > i ; j--)
{
printf(" ");
}
for(j=0; j<=i ; j++)
{
if(j%2 == 0)
Nitin Sir Page 63
printf("0");
else
printf("1");
}
printf("\n");
}
return 0;
}
1
12A
123AB
1234ABC
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=4;i++)
{
for(j=1;j<4-i;j++)
printf(“ “);
}
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
for(j=1;j<=i-1;j++)
{
printf(“%c”,(char)(j+64);
}
printf(“%n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
Nitin Sir Page 66
void main()
{
int i, j, k;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=5-i;j++)
{
printf(“ ”);
}
for(j=1,k=5;j<=i;j++)
{
printf(“%d”, k--)’
}
printf(“\n”);
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, n;
printf(“Enter the number of lines:”);
scanf(“%d”, &n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
printf(“ ”);
}
for(j=1;j<=i;j++)
Output 1:
Enter a number:12
Binary form is:0000000000001100
Output 2:
Enter a number:8
Binary form is:0000000000001000
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
for(i=1;i<=5;i++)
{
if(i%2!=0)
{
for(j=1;j<=i;j++)
printf(“%d”, j);
}
else
{
for(j=0;j>=1;j--)
printf(“%d”, j);
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
int n , i , j, m=65, k=64;
printf(“Enter n”);
#include <stdio.h>
#include <conio.h>
void main()
{
double n,f=1,i,sum=0;
printf("\n Enter the value: ");
scanf("%lf", &n);
for (i = 1; i <= n; i++)
{
f = f * i;
sum = sum +(i / f);
}
printf("\n Sum of the above series = %lf ", sum);
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int units;
float charge;
clrscr();
printf(“Enter the units consumed:”);
scanf(“%d”, &units);
switch(units/200)
{
case 0: charge=units *0.5;
break;
case 1: charge=(units-200) *0.65+100;
break;
Nitin Sir Page 74
case 2: charge=(units-400) *0.85+230;
break;
default: charge=(units-600) +390;
break;
}
printf(“Charges=%f”, charge);
getch();
}
Break :-
e.g :-
#include <stdio.h>
int main ()
{
int i = 1;
while( i <=10 )
{
printf("value of i: %d\n", i);
if( i= =5)
{
/* terminate the loop using break statement */
break;
}
i++;
}
return 0;
}
O/P
value of i: 1
Continue statement
Syntax
continue;
e.g :
for (int j=1; j<=10; j++)
{
if (j==5)
{
continue;
}
printf("%d ", j);
}
Output:
1 2 3 4 6 7 8 9 10
GOTO statement
goto statement are used to transfer the control of a program from one part to
another part.
Syntax
goto label;
..
..
label: statement;
#include <stdio.h>
void main ()
{
int n = 1;
accept :
printf(“Enter a number\n”);
scanf(“%d”, & n);
if(n<0)
Nitin Sir Page 77
{
goto accept;
}
getch();
}
Questions:-
1. Explain difference between for, while and do while loop. (4 Mks)
2. Write a program to generate patters.
3. Write a program to generate prime nos between 1 to 100. (10M)
4. Write a program to generate following patterns. 10M
Nitin Sir Page 81
5. Explain difference between while and do-while. [5 M]
6. Explain for loop with syntax and example [4 M]
1. Explain switch control statement with example [4 M].
2. Discuss what is need of break statement in switch case [4 M]
3. Explain the following with example 1) goto, 2) continue 3) break [4 M]
4. Write a program print the sum of following series
1+22+33+…….+nn [5 Marks] [MAY-18]
5. Comapre break and continue statements [5 Marks] [MAY-18]
6. Compare if-else and switch statements [5 Marks] [MAY-18]
7. Write a program to calculate number of vowels in the entered string. [6
Marks] [MAY-18]
8. Write a program to print following pattern
i) 5432*
543*1
54*21
5*321
*4321
ii) 5
54
543
5432
54321
Why Function
➢ Advantages of functions:
1. The length of the program gets reduce because functions are called
only whenever they are required.
2. While debugging errors, it becomes easy to find out errors if any.
3. The function written once can be used many times by many
programmers in the same program or in the external program.
4. Functional approach saves time and memory space.
Function prototype
Function definition
Function Defination
• Syntax :-
return _type function _name (argument _list)
{
Statements;
}
1. Return_type is the date type of the data to be returned by function
return_type can be void if no data is return.
The return type of the data can be any of the data types like int, char, float
etc.
2. Function name can be anything as far as rules of identifer is consider.
3. Argument list is set of data type with identifier to accept data passed to the
function when it is called.
4. Statement inside the function are the statement to be executed when
function is called.
Function Call
functionName (parameter list);
#include <stdio.h>
int add(int p, int q); // Function Prototype
int main()
{
int a,b,c;
printf(“Enter two numbers\n”);
scanf(“%d %d”,&a,&b);
c=add(a,b); // Calling Function
printf(“\n sum of two number is %d”,c);
return 0;
}
int add(int p, int q) // Function Defination
{
int result;
result=p+q;
Nitin Sir Page 84
return (result);
}
#include <stdio.h>
int fact(int); // Function Prototype
void main()
{
int no, ans;
printf(“Enter a number\n”);
scanf(“%d ”,& no);
ans=fact(a,b); // Calling Function
printf(“\n factorial of number is %d”,ans);
getch();
}
int fact(int no) // Function Defination
{
int i, ans=1;
for(i=1;i<=no;i++)
{
ans=ans* i;
}
return ans;
}
O/P
Enter a number: 4
Factorial =24
Library functions
1. pow (x,y)
• This functions is available in the header file “math.h”
• This functions calculate and returns the value of xy.
• The parameters as well the ans returned are of double data type.
2. sqrt(x)
• This function find the square root of the parameter passed to it.
• This functions is available in the header file “math.h”
• This function also accepts parameter of double data type.
ans = sqrt(x); // 4.
3. ceil(x)
• This function returns the smallest integral value of the parameter passed
to the function.
e.g :-
double x, val=1.6
x=ceil(val); // x=2.0
4. floor(x)
• This function returns the largest integral value of the parameter passed to
the function.
x=floor(val); // x=1.0
5. abs()
x=abs(y); // x=9;
6. isalnum()
Coping value of variable is another variable. So any changes made in the copy
will not affect the original location.
#include <stdio.h>
void swap(int a, int b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (m.n);
printf(“value after swap m=%d and n=%d”,a,b);
}
Creating link for the parameter to the original location, since the address is
same, changes to the parameter will refer to the original location and value will
be overwritten.
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (&m.&n);
printf(“value after swap m=%d and n=%d”,*a,*b);
}
void swap(int *a, int *b) // Function Defination
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
O/P
value before swap m=10 and n=20
value after swap m=20 and n=10
#include<stdio.h>
#include<conio.h>
void main ()
{
int n,r,ncr ;
int fact (int no);
clrscr();
pintf(“enter the values of n and r”);
scanf(“%d %d ”,&n,&r);
ncr = fact (n) / (fact(r)*fact(n- r));
printf(“ncr=%d”,ncr);
getch();
}
int fact (int no)
{
int i , f=1 ;
for(i= 1; i<=no; i++)
{
f = f * i;
}
return f;
}
OUTPUT:
enter the values of n and r:5
3
ncr = 10
if(rev==temp)
return 1 ;
else
return 0 ;
}
void main()
{
int n , flag ;
clrscr() ;
printf("Enter a number: ") ;
scanf("%d" , &n) ;
flag=palindrome(n) ;
if(flag==1)
printf("%d is a palindrome" , n) ;
else
printf("%d is not a palindrome" , n) ;
getch() ;
}
Output1:
Enter a number: 24542
24542 is a palindrome
Output2:
Enter a number: 2464
2464 is not a palindrome
/*
Output:
int rev(int n)
{
Static sum,r;
if(n>0)
{
r=n %10;
s=s*10+r;
rev(n/10);
}
else
{
return 0;
}
return sum;
}
Questions :
• The different locations in the computer where we can store data and their
accessibility, initial values etc. vary based on the way they are declared. These
different ways are termed as different storage classes.
• In C, we have four storage classes, Namely
1. Automatic
2. Register
3. Static
4. External or Global
int i;
or
auto int i;
Questions:-
• Data _type is the data type like int, float, double etc.
• Array _name is the identifier i.e. the name of an array.
• Array _size is an integer value which determines size of the array
Initilisation of an array :-
age[0]=18;
age[1]=20;
30
12
14
88
19
Output:-
Enter Element: 2
Enter Element: 5
Enter Element: 9
Enter Element: 7
Enter Element: 3
Sorted array: 2 3 5 7 9
#include<stdio.h>
#include<conio.h>
void main()
{
int a [30],i,j, no,temp;
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++)
{
printf("\n Enter Element");
scanf("%d",&a[i]);
}
for(i=1;i<no;i++)
{
for(j=0;j<no-i;j++)
{
if(a[j] < a[j+1])
{
temp=a[j];
Nitin Sir Page 104
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nSorted array:");
for(i=0;i<no;i++)
{
printf("\t%d",a[i]);
}
getch();
}
Output:-
Enter Element: 2
Enter Element: 5
Enter Element: 9
Enter Element: 7
Enter Element: 3
Sorted array: 9 7 5 3 2
Write a program to find smallest of ‘n’ numbers taken from user, using
function. [DEC-15]
#include <stdio.h>
int main()
{
int a[30],i, small, n;
printf("Enter the number of elements \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
30
12
14
88
19
#include<stdio.h>
#include<conio.h>
int search(int a[], int n, int x);
void main()
{
int a [30],i,x, no,index;
printf("\nEnter the no of Elements: ");
scanf("%d", &no);
for(i=0;i<no;i++)
{
Nitin Sir Page 106
printf("\n Enter Element");
scanf("%d",&a[i]);
}
printf("\n Enter the element to be searched:");
scanf(“ %d ”, &x);
index=search(a,n,x);
if(index==n)
{
Printf(“Element Not found\n”);
}
Else
{
Printf(“Element is found at index %d \n”, index);
}
getch();
}
int search(int a[], int n, int x)
{
int i;
for(i=0;i<n-1;i++)
{
if(x = =a[i])
{
break;
}
}
Return i;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int a[7]={1,2,3,4,2,5,2};
int b[10];
int i,j,count=0;
clrscr();
for(i=0;i<6;i++)
{
for(j=0;j<count;j++)
{
if(a[i]==b[j])
break;
}
if(j==count)
{
b[count] = a[i];
count++;
}
}
for(i=0;i<count;i++)
{
printf("%d",b[i]);
}
getch();
}
• Multi dimensional arrays are used to store data that requires multiple
references like row number and column number.
• “matrix” is a best example of two dimensional arrays.
• The size of the array will be 3×3, but the indices will be from 0 to 2 in both
the rows and columns.
• Syntax:-
Initialisation:-
a[3][3]={{1,2,3},{4,5,6},{7,8,9}}
1 2 3
4 5 6
7 8 9
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[3][3], i, j, sum=0;
/*Accepts input from the user and stores it in 2-D array*/
printf(“Enter the number of rows and columns\n”)
scanf(“%d %d” ,&m, & n);
printf(“Enter the value for matrix A\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&arr[i][j]);
1 2 3
4 5 6
7 8 9
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter the Second matrix");
Nitin Sir Page 111
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",c[i][j]);
}
printf(“\n”);
}
getch();
}
int n,i,j,temp,a[5][5],flag=0,b[5][5];
clrscr();
printf("Enter the order of the matrix::\n");
scanf("%d",&n);
printf("Enter the elements of the matrix::\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=a[i][j];
}
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
}
printf("Transpose Matrix is::\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]!=b[i][j])
{
flag=1;
Nitin Sir Page 113
}
}
}
if(flag==1)
{
printf("The matrix is not symmetric.");
}
else
printf("Matrix is symmetric.");
}
getch();
#include <stdio.h>
void transpose (int [][] ,int ,int );
int main()
{
int m, n, i, j, matrix[10][10];
printf("Enter the number of rows and columns of matrix ");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix \n");
for( i= 0 ; i < m ; i++ )
{
for( j = 0 ; j < n ; j++ )
{
scanf("%d", &matrix[i][j]);
}
}
transpose (matrix,m,n);
return 0;
}
Syntax :
H e l l o \0
0 1 2 3 4 5 6
Initializing String :
String can be initialized in two ways.
eg. :-
Three are many string standard library function. These functions are available in
string.h
Some of them can be explained as follows.
1) strlen( )-
Syntax
int strlen(char*)
The strlen ( ) accepts string and calculates and returns the length of the
string which determines number of characters present in the string.
For example,
int n;
n = strlen(“hello”);
will assign value 5 to variable n.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
Nitin Sir Page 122
int len;
char str[100];
printf(“Enter a string\n”);
gets (str);
len=strlen(str);
printf( “The length of string is %d”, len);
getch();
}
2) strcpy( )-
Syntax
char * strcpy(char *d, char *s);
char s1[ ]= “hello”,s2[80];
strcpy(s2,s1);
3) strncpy( ) –
Syntax
char * strncpy(char *destination, char *source, int length)
The strncpy ( ) will copy maximum length number of characters from
source string into destination character array.
For example
char s1[ ]= “welcome”, s2[80];
strncpy (s2,s1, 3);
Due to strncpy( ) string first three character from string s1 i.e. ‘w’,’e’,’l’
4) stracat()-
Syntax
char * strcat(char *destination, char *source)
The strcat ( )will concatenate (Join) source string into destination
character array.
For e.g.,
Char s1[]= “hello”, s2[80]= “welcome”;
strcat(s2,s1);
Due to strcat () string “hello” present in character array s1 will be
Concatenated onto string present in character array s2 into
“welcomehello” in s2.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[100],d[100];
printf(“Enter two string\n”);
gets (s);
gets (d);
strcat(s,d);
printf( “The concatenated string is %s”, s);
getch();
}
5) strcmp()
Syntax
int strcmp( char *s. char *d);
This function compares the two string variables passed to it.
It returns integer value
• 0 if two strings are equal.
• Negative value, if the first string is smaller than second
string.
• Positive value, if the first string is greater than second
string.
Write a program to accept a string and find its length without using string
header file.
#include<stdio.h>
#include<conio.h>
void main()
{
int len=0;
char str[100];
printf(“Enter a string\n”);
gets (str);
while(str[len]!=’\0’)
{
len++;
Write a program to copy one string to another without using string header
file.
#include<stdio.h>
#inlclude<conio.h>
void main()
{
char tar[20],src[20],*t;
int i=0;
clrscr();
printf("\nEnter first string: ");
gets(tar);
t = tar;
printf("\nEnter second string: ");
gets(src);
while(src[i]!='\0')
{
tar[i] = src[i];
i++;
}
tar[i]= '\0';
printf("\nSecond string after copy::");
puts(t);
getch();
}
Write a program to join one string to another without using string header
file.
#include<stdio.h>
#inlclude<conio.h>
void main()
{
char a[20],b[20];
int i=0,j=0;
Nitin Sir Page 126
clrscr();
printf("\nEnter first string: ");
gets(a);
printf("\nEnter second string: ");
gets(b);
while(a[i]!='\0')
{
i++;
}
while(b[j]!='\0')
{
a[i]=b[j];
i++;
j++;
}
a[i]=’\0’;
printf("\n New string after join::");
puts(a);
getch();
}
String - Program which reads month number and displays the same in
words. (Use two dimensional array) */
#include <stdio.h>
#include <conio.h>
void main()
{
int m ;
char x[12][10] = {"January" , "February" , "March" , "April" ,
"May" , "June" , "July" , "August" , "September" , "October",
"November" , "December" } ;
clrscr();
printf("Enter the month number: ") ;
scanf("%d" , &m) ;
printf("Month in words is: %s" , x[m-1]) ;
getch();
}
Output:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main()
{
char str[50] , c ;
int i , v=0 ;
clrscr() ;
printf("Enter a string: ") ;
Nitin Sir Page 128
gets(str) ;
for(i=0 ; str[i]!='\0' ; i++)
{
c=tolower(str[i]) ;
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u')
v++ ;
}
printf("Number of vowels in %s is %d" , str , v) ;
getch() ;
}
Output:
Enter a string: Umbrella is nice
Number of vowels in Umbrella is nice is 6
Questions : -
Write a user defined function to copy one string to another. 4 Marks.
Structures
• Structure is a collection of multiple data elements that can be of different
data types.
• Array is a collection of data items of same type, while structure can have
data items of different type
• The memory space required to store one variable of structure is equal to
the memory space by all the elements independently.
struct structure_name
data_type variable_name;
};
For example a structure to store the some information like name, roll number
and fees of a student in college can be declared as show below.
struct student
{
char name [20];
int roll_no;
float fees;
};
Structure is normally used when a set of data items corresponding to a common
thing are to be stored together.
#include<stdio.h>
struct Student
{
int iRollNo;
char cName[20];
float fMarks;
};
int main()
{
//create var inside main
struct Student s1;
struct Student s2 = {1,"aa",70.6};//create and initialize
float m;
clrscr();
#include<stdio,h>
#include<conio.h>
struct employee
{
int age;
char name [40];
char street [40];
char city [40];
};
void main()
{
struct employee e[5];
for(i=0;i<5;i++) /*reading/
{
printf(“Enter employee name”);
gets(e[i].name);
printf(“Enter age”);
scanf(“%d”,&e[i].age);
printf(“Enter street”);
gets(e[i].street);
printf(“Enter city”);
gets(e[i].city);
}
printf(“Employe Name\t Age \t Street\t City\n”);
for(i=0;i<5;i++)
{
printf(“%s\t %d\t %s\t %s\n”, e[i].name, e[i].age, e[i].street,
e[i].city);
}
getch();
}
#include<stdio,h>
#include<conio.h>
struct employee
{
int id;
char name [40];
float salary;
};
void main()
{
struct employee e[100],temp;
int n;
printf(“How many elements(not more than 100)=”);
scanf(“%d”,&n);
printf(“Enter information of all\n”)
for(i=0;i<n;i++) /*reading/
{
printf(“ID = ”);
scanf(“%d”,&e[i].id);
printf(“Name =”);
gets(e[i].name);
printf(“Salary=”);
scanf(“%f”,&e[i].salary);
}
for(i = n – 1;i>0;i - -)
{
for(j=0;j < i ; j++)
{
if(e[j].salary < e[j+1].salary) /*descending order*/
{
temp = e[j];
e[j] = e[j+1];
e[j+1] = temp;
}
}
Nested Structure
Nested structure in c is nothing but structure within structure.
One structure can be declared inside other structure as we
declare structure member inside other structure.
Syntax
Struct structure_name
Data_type variable_name;
Struct
Data_type variable_name;
Data_type variable_name;
}Internal_structure_name;
Write a program to store the name, runs scored and wickets taken of ‘n’
cricketers using structures. Display the output in tabular form.
#include<conio.h>
#include<stdio.h>
Struct cricketer
Nitin Sir Page 136
{
char name[20];
int runs, wickets;
};
void main ()
{
struct cricketer c[100];
int n, i;
clrscr ();
print(“enter the number of cricketers”);
scanf(“%d”,&n);
for(i=0;i<=n-1;i++)
{
Printf(“enter the cricketer’s name , runs scored and wickets
taken:”);
Scanf(“%s%d%d”,c[i].name , &c[i]. runs, &c[i].wickets);
}
printf (“name/t runs/t wickets/n:”);
printf (“---------------------------------/n”);
for(i=0;<=n-1;++)
{
printf(“%s/t %d/t %d\n”,c[i].runs,c[i].wicket);
}
getch();
}
Write a program to store the name, matches played and runs scored by ‘n’
cricket players using structure. Generate a list with runs scored in
descending order i.e. display the output in tabular form in order of
maximum runs to minimum runs scored.
#include<conio.h>
#include<stdio.h>
struct cricketer
{
char name[20];
int matches , runs;
};
void main()
{
struct cricketers s[100],temp;
Unions
• Union is a collection of multiple data elements that can be of different
data types. But, only one of these data items can be stored in the union
variable.
• The memory space required to store one variable of union is equal to the
memory space required by the largest element in the union.
Union union_name
{
Data_type variable_name;
Structure Union
Memory allotted for a structure is Memory allotted for a union is equal
equal to the space require collectively to the space required by the largest
by all the members of that structure. member of that union.
Data is more secure in structures Data can be corrupt in union
Structure provides ease of Unions are comparatively difficult for
programming programming
Structures requires more memory Union requires less memory
Structure must be used when Unions must be used when only one
information of all the member of the member elements of the union
elements of a structure are to be is to be stored.
stored
#include<stdio.h>
#include<conio.h>
struct patient
{
char
fname[20], sname[20], mname[20], birthdate[20], disease[20];
};
void main()
{
struct patient s[100];
int n, i, j, k;
char d[20];
printf(“Enter the number of patients\n”);
Nitin Sir Page 139
scanf(“%d”,&n);
for(i=0i<=n-1;i++)
{
printf(“Enter the first name, middle name, surname, date of birth
and disease:”);
scanf(“%s %s %s %s %s, s[i].fname, s[i].mname, s[i].sname,
s[i].birthdate, s[i].disease);
}
printf(“\n Enter the disease whose patients are to be listed :”);
scanf(“%s”, d);
printf(“\n Patients with said disease are:”);
for(j=0;j<=n-1;j++)
{
for(k=0;d[k]!=‘\0’’k++)
{
If(d[k]!=s[j].disease[k])
{
Break;
}
}
if(d[k]==‘\0’)
printf(“%s %s %s \n”, s[j].fname, s[j].mname, s[j].sname);
}
getch();
}
Questions :-
“Data _type” is the type of the variable to which the pointer is supposed
to point.
If we want a pointer to point to an integer than, we need to have the data
type of the pointer as “int”, for a float type data pointer should also be of
the “float” type and so on.
“ptr _name” is an identifier i.e. the name of the pointer.
Example :
Int *p;
Hence, the pointer name is “p”. Hence, “p” can be used as a pointer to
point to any of the variable of type “int”
y = *p;
i.e. the value of the variable pointed by the pointer “p” is stored in the
variable “y”.
Write a program to add two numbers using function. Pass the pointers to the
variables as reference to the functions.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b;
Output:
Enter two numbers: 4
7
The sum is equal to 11
Pointers to Array
Find output of the following statement.
#include<stdio.h>
#include<conio.h>
Void main()
{
Output:
20
21
22
22
Creating link for the parameter to the original location, since the address is
same, changes to the parameter will refer to the original location and value will
be overwritten.
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m=10,n=20;
printf(“value before swap m=%d and n=%d”,m,n);
swap (&m.&n);
printf(“value after swap m=%d and n=%d”,*a,*b);
}
void swap(int *a, int *b) // Function Defination
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
O/P
value before swap m=10 and n=20
value after swap m=20 and n=10
If we want to change the size of the array during the execution of the program
then we have to use the concept of dynamic memory allocation.
This can be done with the help certain library functions of the header file
“stdlib.h”
This statement will allocate space for 10 integers and return the pointer to the
first element of the array.
Free():
This function releases or makes the memory space free which is dynamically
allocated by the function malloc() or calloc()
For example:
free(p1);
This statement will free the space allocated for the pointer p1.
Realloc():
This function allocates the pointer with a new size of memory block size.
For example:
p1=realloc(p1, 100);
This statement will now allocate 100 bytes for the array pointed by the pointer
p1.