You are on page 1of 171

First steps into the ‘C’

Programming.
Brief History of “C”.
“C” programming language was developed by
Dennis Ritchie and Brian Kernighan, at Bell
Telephone Laboratories (now AT&T
incorporation US) in 1972.
It was modified from BCPL (Basic Combined
Programming Language), which was
developed by Martin Richards.
Later modified by Ken Thompson as B
Language. Finally to C programming language.

By syed ilyas
ahamed,tumkur,karnataka.
“C” character sets
 C language can identify.
 A-Z : upper case Alphabets.
 a-z : lower case Alphabets.
 0-9 : Digits.
 +,-,*,/,% : 5 Basic mathematical
operators.
 ,,.,”,:,;,$,#,>,<,?,! etc. : Special
characters & punctuation symbols.
By syed ilyas
ahamed,tumkur,karnataka.
Keywords(Reserved words)
 “C” language has 32 keywords or reserved words.
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while

By syed ilyas
ahamed,tumkur,karnataka.
Constants
 Constants are those whose value is
fixed, and the value does not change.
 There are 2 types of constants.
 Integer constant and
 Real constant.

By syed ilyas
ahamed,tumkur,karnataka.
Variables
 Variables are those whose values can
be changed.
 In computer science, variables are place
holders, where a quantity can be
stored.

By syed ilyas
ahamed,tumkur,karnataka.
Identifiers
 Identifiers are the names given to the
program elements such as variables,
arrays, strings, functions, structures,
unions etc.

By syed ilyas
ahamed,tumkur,karnataka.
Rules for forming a “C”
identifier.

1. The first character must be an alphabet (both, upper


case or lower case) or an underscore.(_)
2. The succeeding character may be either letters or
digits.
3. Keywords or reserved words are not allowed as “C”
identifiers.
4. Upper case and lower case are different in “C”
language. (case sensitive).
5. No two successive underscores are allowed.
6. Punctuation symbols or special characters are not
allowed except the underscore.
By syed ilyas
ahamed,tumkur,karnataka.
Datatypes in “C” language
Datatype keyword Memory(Bytes)
1. Integer int 2
2. Real numbers float 4
3. Double precision real nos. double 8
4. Character char 1
5. Void or Null void 0

By syed ilyas
ahamed,tumkur,karnataka.
General format of a “C”
program.
Preprocessor statements.
Global declarations (if any)
main( )
{
local declarations;
executable statement/s;
}
user_defined functions ( )(if any)
By syed ilyas
ahamed,tumkur,karnataka.
My first “C” program
Program to display the statement.
“Programming is Fun”
#include<stdio.h>
void main( )
{
printf(“Programming is Fun”);
}
By syed ilyas
ahamed,tumkur,karnataka.
Compiling and Running the
program
1. Enter your program in the Turbo-C IDE.
2. Save your program code giving a relevant name with the
extension .c. This is called the source code.
3. Compile your program by selecting the This is called the
source code.
4. Compile your program by selecting the compile drop down
menu and click on compile. You get a dialog box and error
messages if any. After successful compilation, It creates an
object file with the extension .obj
5. Click on link in the compile drop down menu. After successful
linking, It creates an executable file with the extension .exe.
6. Now Run your program by selecting the run drop down menu
and click on run.

By syed ilyas
ahamed,tumkur,karnataka.
Escape sequences
 \n new line character
 \t horizontal tab
 \v vertical tab
 \a alarm
 \b backspace
 \” prints the double quote
 \’ prints the single quote.
 \\ prints the backslash character itself.
By syed ilyas
ahamed,tumkur,karnataka.
Program 3
Write a “C” program to add 200 and 300 and display the output as :
“THE SUM OF 200 AND 300 IS = 500.”
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum;
clrscr();
sum=200+300;
printf(“\n THE SUM OF 200 AND 300 IS = %d”,sum);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Program 4
Write a “C” program to add two integer numbers and display the result.
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,sum;
clrscr();
printf(“\nEnter the value of two integer numbers : “);
scanf(“%d %d”,&num1,&num2);
sum=num1+num2;
printf(“\nThe sum of %d and %d is = %d”,num1,num2,sum);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Program 5
Write a “C” program to accept the area of the circle, calculate the area of
the circle and display the result.
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
float area,radius;
clrscr();
printf(“\nEnter the radius of the circle : “);
scanf(“%f”,&radius);
area=3.14*radius *radius;
printf(“\nThe area of the circle is = %d”,area);
getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
Program to display the ASCII code of the symbol entered.
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
int code;
char symbol;
clrscr();
printf(“\nEnter a character from the keyboard: “);
scanf(“%c”,&symbol);
code=symbol;
printf(“\nThe ASCII code of the %c is = %d”,symbol,code);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
Unary Operators:
The operation done on the single operand is
called as a Unary operator.
The Unary operators available in “C” language
are:
Unary plus: ‘+’
Unary minus: ‘-’
Increment operator: ‘++’
Decrement operator: ‘--’
Size of operator: sizeof
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Increment Operator:
There are two types of increment operator:
1. Pre-increment Operator.
2. Post Increment Operator.
Pre-increment Operator:
If the operator is used before the operand, then it is
called as pre-increment operator.
Ex: ++a;
Here, If the value of a is initially, 5, then, the value is
first incremented by 1, and then the value 6 is
fetched.

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Program to illustrate the working of a Pre-increment operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=15;
clrscr();
printf(“\nThe initial value of a = %d”,a);
printf(“\nNow the value of a = %d”,++a);
printf(“\nLater the value of a = %d”,a);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Post-increment Operator:
If the operator is used after the operand,
then it is called as Post-increment
operator.
Ex: a++;
Here, If the value of a is initially, 5, then,
the value a i.e., 5 is first fetched and
later the value of a is incremented by 1.
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Program to illustrate the working of a Post-increment operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=25;
clrscr();
printf(“\nThe initial value of a = %d”,a);
printf(“\nNow the value of a = %d”,a++);
printf(“\nLater the value of a = %d”,a);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
sizeof Operator:
The sizeof operator returns the number of bytes allocated by the compiler for the
variables or the data type.
Ex: sizeof(int) will return 2.
Program to illustrate the sizeof operator:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“\nThe Size of \”int \” is = %d bytes”,sizeof(int));
printf(“\nThe size of \”float\” is = %d bytes”,sizeof(float));
printf(“\nThe Size of \”char \” is = %d bytes”,sizeof(char));
printf(“\nThe size of \”double\” is = %d bytes”,sizeof(double));
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Relational operators:
Less than : ‘<‘
Greater than : ‘>’
Less than or equal to : ‘<=‘
Greater than or equal to : ‘>=‘
If the value of the operation is true, then
the compiler, will return 1 else will
return 0.
By syed ilyas
ahamed,tumkur,karnataka.
Program to illustrate the relational operators:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
a=15;
b=20;
printf(“\nThe value of a>b is = %d”,a>b);
printf(“\nThe value of a<b is = %d”,a<b);
printf(“\nThe value of a>=b is = %d”,a>=b);
printf(“\nThe value of a<=b is = %d”,a<=b);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Equality operator:
Equal to : ‘==‘
Not equal to : ‘!=‘
If the value of the operation is true, then
the compiler, will return 1 else will
return 0.

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Logical Operators:
Logical AND: ‘&&’
Logical OR: ‘||’
Logical NOT: ‘!’
Logical AND: The expression will evaluate true
only if both the conditions are true.
Logical OR: The expression will evaluate true, if
at least one of the conditions is true.
Logical NOT: The expression will return true, if
the condition is false and vice versa.
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Assignment Operators:
Syntax:
Identifier= value of an expression.
Ex: A=10; Num=x;
Sum=a+b;
Multiple assignment operators:
identifier1=identifier2=expression;
Other assignment operators:
+=, -=, *=, /=, %=
identifier1+=identifier2;
identifier1=identifier1+identifier2;
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
If, i=5, j=7
Expression Equivalent value
expression
i+=5; i=i+5;
j*=(i-3);
i%=(j-2);

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
If, f=5.5, g=-3.25
Expression Equivalent value
expression
f+=g;
f-=g;
f*=g;
f/=g;
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Conditional Operators:
Identifier=(test expression)? Expr1 : expr2;
If a and b is 10 and 3 respectively.

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
If two integer numbers a and b are 10 and 3
respectively.
Expression value
a+b
a-b
a*b
a/b
a%b
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
If f1 and f2 are two floating point
variables with the value 12.5 and 2.0
respectively:
Expression value
f1+f2
f1-f2
f1*f2
f1/f2
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
If c1 and c2 are two character variables
with value ‘P’ and ‘T’ respectively.
Expression value
c1
c1+c2
c1+c2+5
c1+c2+’5’
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Absolute.c
#include<stdio.h>
#include<conio.h>
void main()
{
int num,abs;
clrscr();
printf(“\nEnter a signed number : “);
scanf(“%d”,&num);
abs=(num<0)?-num:num;
printf(“\nAbsolute value = %d”,abs);
getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Program to find the biggest of two numbers using ternary operator:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,large;
clrscr();
printf(“\nEnter the value of two numbers : “);
scanf(“%d %d”,&num1,&num2);
large=(num1>num2)?num1:num2;
printf(“\nThe largest of two numbers is = %d”,large);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
A C program to illustrate sizeof operator:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“\nSize of short int is %d”,sizeof(short int));
printf(“\nSize of int is %d”,sizeof(int));
printf(“\nSize of long int is %d”,sizeof(long int));
getch():
}
By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
#include<stdio.h>
#include<conio.h>
void main()
{
int i=25;
clrscr();
printf(“\nInitial value of i = %d”,i);
printf(“\n%d”,i++);
printf(“\n%d”,i-=4);
printf(“\n%d”,i+=7);
printf(“\n%d”,i--);
printf(“\n%d”,i+4);
printf(“\nNow i value = %d”,i);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Bitwise Operators:
Data stored in memory location is in the form of 0’s and 1’s. called
Binary digITS(BITS).
Manipulation of these bits, C provides 6 bitwise operators:
These operators work only with int and char datatypes.
Operator Symbol Meaning
& Ampersand Bitwise AND
| Pipeline Bitwise OR
^ Caret Exclusive-OR
~ Tilde 1’s complement
<< Double less than Left shifting of bits
>> Double greater than Right shifting of bits

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
int a=5,b=3;
Considering an 8-bit computer:
The equivalent binary number of 5= 0000 0101
The equivalent binary number of 3= 0000 0011
The result of bitwise ANDing of a and b is:
a = 0000 0101
b = 0000 0011
a&b = 0000 0001
The result of bitwise ORing of a and b is:
a = 0000 0101
b = 0000 0011
a|b = 0000 0111
The result of bitwise Exclusive-ORing of a and b is:
a = 0000 0101
b = 0000 0011
a^b = 0000 0110

By syed ilyas
ahamed,tumkur,karnataka.
Operators and Expressions
(Contd.)
Bitwise Complement:
If a=5; Binary equivalent is 0101
b=~a;
= 1010 which is 1’s complement of a.
Bitwise Left shifting:
Consider the Binary number 1001 1011
Before Left shifting by one bit: 1001 1011
After Left shifting by one bit : 0011 0110
Bitwise Right shifting:
Consider the Binary number 1010 0101
Before Right shifting by one bit : 1010 0101
After Right shifting by one bit : 0101 0010

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
Normally program statements gets executed one after
the other sequentially, from the first statement to the
last statement one after the other.
The statements which alter the sequence of execution
of the program are called control statements.
The control statements are classified as:
Conditional control statements:
if statement
if-else statement
nested if statements
switch statement

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
Unconditional control statements:
goto statement
break statement
continue statement
Looping/Repetitive/Iteration control statements:
for statement
while statement
do-while statement
By syed ilyas
ahamed,tumkur,karnataka.
The if statement
 The if statement:
 Syntax:
if(condition)
{
statement/s;
}
next statements(if any)

By syed ilyas
ahamed,tumkur,karnataka.
if statement (flow chart)

false
if(condition
)

true

Statement/s;

Next statements(if any)


By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
 Program to illustrate the simple if statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“\nEnter a positive number : “);
scanf(“%d”,&num);
if(num<0)
printf(“\n\aERROR IN INPUT VALUE !!”);
printf(“\nThe number entered is : %d”,num);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
Program to print the maximum number of days in February.
 #include<stdio.h>
 #include<conio.h>
 void main()
 {
 int month,day,year,feb_max;
 clrscr();
 printf("\nEnter month and year : ");
 scanf("%d %d",&month,&year);
 feb_max=28;
 if(month==2)
 {
 printf("\nMonth is February");

 if((year%4)==0)
 {
 printf("\nLeap year");
 feb_max=29;
 }
 }
 printf("\nMax days in February month in %d year is %d",feb_max,year);
 getch();
 }

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
 Program to find the biggest of three numbers using simple if statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int num1,num2,num3,large;
clrscr();
printf(“\nEnter the value of 3 numbers : “);
scanf(“%d %d %d”,&num1,&num2,&num3);
large=num1;
if(num2>large)
large=num2;
if(num3>large)
large=num3;
printf(“\nThe largest number is = %d”,large);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
The if-else construct:
Syntax:
if(condition)
{
statement1/s;
}
else
{
statement2/s;
}
Next statements (if any)

By syed ilyas
ahamed,tumkur,karnataka.
if-else construct (flow chart)
true false
if(condition
)

Statement1/s; Statement2/s;

Next statements(if any)

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
 Program to find whether the given number is odd or even.
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf(“\nEnter a number : “);
scanf(“%d”,&num);
if(num%2==0)
printf(“\nThe number %d entered is EVEN NUMBER”,num);
else
printf(“\nThe number %d entered is ODD NUMBER”,num);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
 Write a C program to check whether the entered character is an alphabet or not.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf(“\nEnter an alphabet : “);
ch=getchar();
if((ch>=‘a’ &&ch<=‘z’)||(ch>=‘A’&&ch<=‘Z’)
printf(“\n%c entered is an alphabet”,ch);
else
printf(“\n%c entered is not an alphabet”,ch);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
 The if-else-if construct : (nested if)
Syntax : if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else if(condition3)
statement3;
else
statement4;

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
The other forms of two-layer nesting:
1) if(condition1)
statement1;
else if(condition2)
statement2;
2) if(condition1)
statement1;
else if(condition2)
statement2;
else
statement3;
By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
3) if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
else
statement3;
4) if(condition1)
{
if(condition2)
statement1;
else
statement2;
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
Write a C program to accept a character and display the corresponding messages .
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf(“\nEnter a character : “);
ch=getchar();
if(ch>=‘a’ && ch<=‘z’)
printf(“\NLOWER CASE ALPHABET”);
else if(ch>=‘A’ && ch<=‘Z’)
printf(“\nUPPER CASE ALPHABET”);
else if(ch>=‘0’ && ch<=‘9’)
printf(“\nDIGITS”);
else if(ch==‘+’||ch==‘-’||ch==‘*’||ch==‘/’||ch==‘%’)
printf(“\nMATHEMATICAL OPERATOR”);
else
printf(“\nSPECIAL SYMBOL”);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
Write a C program to find whether an alphabet entered is a vowel or a consonant.
#include<stdio.h>
#include<conio.h>
Void main()
{
char ch;
clrscr();
printf(“\nEnter an alphabet : “);
ch=getchar();
if(ch>=‘A’ && ch<=‘Z’)
ch+=32;
if(ch==‘a’||ch==‘e’||ch==‘i’||ch==‘o’||ch==‘u’)
printf(“\nVOWEL”);
else
printf(“\nCONSONANT”);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Control Statements
The switch-case statement:
Syntax:
switch(expression)
{
case constant1 :
statement/s;
break;
case constant2 :
statement/s;
break;
….
….
….
case constantn :
statement/s;
break;
default :
statement/s;
break;
}

By syed ilyas
ahamed,tumkur,karnataka.
switch – case statement
(flowchart)
switch(expression)

Case 1:
Match ? Statement/s; break;

case 2:
Match ? Statement/s; break;

case n:
Match ? Statement/s; break;

default Statement/s;

By syed ilyas
Next statement
ahamed,tumkur,karnataka.
Looping:
Iteration: Iteration(looping) is repeated
execution of a group of statements until some
logical condition has been satisfied.
The while construct:
Syntax:
while(condition)
{
statement/s;
}
By syed ilyas
ahamed,tumkur,karnataka.
 Flowchart: false
while
(condition)

true

Statement/s;

Next statements (if any)

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
 Here, the condition is evaluated first. If
it is true (non-zero), statement is
executed and the condition is re-
evaluated. This cycle continues until the
condition becomes false (zero).

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
Write a C program to find the sum of the first 10 natural numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n=1;
clrscr();
while(n<=10)
{
sum+=n;
n++;
}
printf(“\nThe sum of the first 10 numbers is = %d”,sum);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
Write a C program to find the sum of the
first 50 even numbers.

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
The do-while loop construct:
Syntax:
do
{
statement/s;
}while(condition);
In a do-while loop, unlike the while statement, the
check is made at the bottom of the loop instead of at
the top. Therefore, the body of the loop always gets
executed at least once. The loop executes as long as
the condition remains true.

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
 Flowchart: do

Statement/s;

true
while
(condition);

false

Next statements(if any)

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
Write a C program to print the first 10 multiples of 5 one below the other.
#include<stdio.h>
#include<conio.h>
void main()
{
int n=1;
clrscr();
printf(“\nThe first 10 multiples of 5 is as follows :”);
do
{
printf(“\n%d”,5*n);
n++;
}while(n<=10);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
Write a C program to find the average of n numbers:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
float num,sum=0,avg;
clrscr();
printf(“\nEnter the value of n: “);
scanf(“%d”,&n);
do
{
printf(“\nEnter the value of %d number : “,i);
scanf(“%f”,&num);
sum+=num;
i++;
}while(i<=n);
avg=sum/n;
printf(“\nThe average is = %f”,avg);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
 The for loop:
Syntax:
for (initialization expression; test
expression; update expression)
{
statement/s;
}
By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
Initialization expression
Flowchart:

false
Test expression

true

Body of the loop Next statements (if any)

Update expression

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
The for loop is useful while executing the statement/s a number of
times. For example, a program that displays the first 10
multiples of 3 on a single line, is given below:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
printf(“\t%d”,3*i);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
The for keyword is followed by three components within
round braces, ( and ). These three components are
separated by semicolons. In the above example, the
three components are:
i=1
i<=10
i++
The first component, i=1 is executed only once prior to
the statements within the for loop. This is called the
initialization expression.

By syed ilyas
ahamed,tumkur,karnataka.
Looping(contd.)
The second component i<=10 is evaluated
once before every execution of the
statements within the loop. It is called the
test expression. If this expression is true,
the statements within the loop executes. If it
is false, the loop terminates and the control
of execution is transferred to the statement
following the for loop.
The third component i++ is executed once after
every execution of the statements within the
loop. It is called as Update expression.
By syed ilyas
ahamed,tumkur,karnataka.
break statement:
break:
This control statement can be used in loops and
switch statements. It is used to terminate the
loop when a specified condition is satisfied.
The control comes out of the loop and the
following statements are executed. In switch
statements, the control comes out of the
switch statements and the following
statements are executed.
By syed ilyas
ahamed,tumkur,karnataka.
continue statement:
continue:
This control statements are used in the loops.
During execution if a continue statement is
encountered all the following statements will
be terminated and the control will go the next
iteration of the loop without executing the
following statements in the loop. In the while
and do-while the test condition is executed
and in the for loop, the control goes to the
update expression.
By syed ilyas
ahamed,tumkur,karnataka.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
while(i<=10)
{
if(i==6)
break;
printf("\n%d",i);
}
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0,num;
clrscr();
printf("\nEnter a number : ");
scanf("%d",&num);
while(i++<num)
{
if(i%3!=0)
continue;
else
printf("\n%d",i);
}
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
goto:
This is an unconditional control statement
to tell the compiler from where the next
statements has to be executed. (It is
not a good programming practice to use
goto statements).

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to reverse a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
long int num,rev=0;
int r;
clrscr();
printf("\nEnter a number : ");
scanf("%ld",&num);
while(num!=0)
{
r=num%10;
rev=rev*10+r;
num=num/10;
}
printf("\nReversed number = %ld",rev);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to check whether a given number is a palindrome or not.
#include<stdio.h>
#include<conio.h>
void main()
{
long int num,temp,rev=0;
int r;
clrscr();
printf("\nEnter a number : ");
scanf("%ld",&num);
temp=num;
while(num!=0)
{
r=num%10;
rev=rev*10+r;
num=num/10;
}
printf("\nReversed number = %ld",rev);

By syed ilyas
ahamed,tumkur,karnataka.
if(rev==temp)
printf("\n%ld IS PALINDROME",temp);
else
printf("\n%ld IS NOT A PALINDROME",temp);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the GCD and LCM of two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,a,b,gcd,lcm,prod;
clrscr();
printf("\nEnter two numbers : ");
scanf("%d %d",&a,&b);
m=a;
n=b;
prod=n*m;
while(n!=m)
if(n>m)
n-=m;
else
m-=n;

By syed ilyas
ahamed,tumkur,karnataka.
gcd=n;
lcm=prod/gcd;
printf("\nGCD of %d and %d is = %d",a,b,gcd);
printf("\nLCM of %d and %d is = %d",a,b,lcm);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the factorial of a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
long int fact=1;
clrscr();
printf("\nEnter the number whose factorial has to be found : ");
scanf("%d",&n);
for(i=n;i>0;i--)
fact=fact*i;
printf("\nThe factorial of %d is = %ld",n,fact);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to check whether a given number is a prime or not.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i,h,flag;
clrscr();
printf("\nEnter a number : ");
scanf("%d",&num); i=2; flag=1; h=num/2;
while(i<=h)
{
if(num%i==0)
{
flag=0;
printf("\nNumber %d is not a prime number",num);
break;
}
i++;
}

By syed ilyas
ahamed,tumkur,karnataka.
if(flag)
printf("\n%d is a prime number",num);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the largest, smallest and second largest of three numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,lar,small,seclar;
clrscr();
printf("\nEnter the value of 3 numbers : ");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
lar=a;
small=b;
}
else
{
lar=b;
small=a;
}

By syed ilyas
ahamed,tumkur,karnataka.
if(lar<c)
lar=c;
else if(small>c)
small=c;
printf("\nLargest number is = %d",lar);
printf("\nSmallest number is = %d",small);
seclar=(a+b+c)-(lar+small);
printf("\nSecond largest number = %d",seclar);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to generate prime numbers between the range of two numbers.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int m,n,k,i,flag,count=0;
clrscr();
printf("\nEnter the range of numbers to generate prime numbers : ");
scanf("%d %d",&m,&n);
printf("\nPrime numbers between %d and %d\n",m,n);
for(k=m;k<=n;k++)
{
flag=1;
for(i=2;i<=sqrt(k);i++)

By syed ilyas
ahamed,tumkur,karnataka.
if(k%i==0)
{
flag=0;
break;
}
if(flag)
{
count++;
printf("\t%d",k);
}
}
printf("\nNumber of prime numbers between %d and %d is %d",m,n,count);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS
One Dimensional Array:
An array is a group of elements (data items) that have common
characteristics (Ex. Numerical data, character data etc.) and
they share a common name.
The elements of an array are differentiated from one another by
their positions within the list of items.
Each array element (i.e., each individual data item) is referred to
by specifying the array name followed by the subscript enclosed
in square brackets.
The subscript indicates the position of a particular element with
respect to the rest of the elements. The subscript must be a
non negative integer.
For ex., in the n element array, x, the array elements are
x[1], x[2], x[3], x[4], ….. x[n-1], x[n].

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Single and multi dimensional arrays are available in the C
language. The number of subscripts determines the
dimensionality of the array.
Declaration of an Array:
An array must be declared in the same manner as an ordinary
variables, except that each array name must be accompanied
by a size specification. This is necessary because the compiler
will have to know how much memory to reserve for this array. A
single dimensional array is declared as follows:
datatype array_name[n]; size of an array must be an integer
constant.
The integer array declaration int x[100]; creates an array that is
100 elements long with the first element being 0 and the last
being 99.
Ex: int i[100]; char text[80]; float n[12];
By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
An individual element in an array can be
referred to by means of the subscript, the
number in brackets following the array name.
A subscript is the number that specifies the
element’s position in an array.
i[20]=1234;
Note: i[2] is not the second element of the
array I but the third.
The following program illustrates how to enter
data into an array and also reading data from
an array.
By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5],n;
clrscr();
printf("\nEnter 5 numbers : ");
/*Input the 5 integer numbers into array "arr" */
for(n=0;n<5;n++)
{
printf("\nEnter integer # %d : ",n+1);
scanf("%d",&arr[n]);
}
/*Print out the integer stored in array "arr" */
for(n=0;n<5;n++)
printf("\nInteger # %d = %d",n+1,arr[n]);
/* n+1 because the C subscript starts from 0 */
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
When an array of certain data type is declared, initially they are stored as
a contiguous set of these data types. The following program illustrates
this:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, arr[5];
clrscr();
printf("\nSize of int is = %d",sizeof(int));
printf("\nSize of \"arr\" is = %d",sizeof(arr));
for(i=0;i<5;i++)
printf("\n&arr[%d] = %u",i,&arr[i]);
getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Initializing array:
An array can be initialized when declared by specifying
the values of some or all of its elements. Arrays can
be initialized at the time of declaration when their
initial values are known in advance. The values to
initialize an array must be constants – never
variables or function calls.
The array can be initialized as follows:
int array[5]={4,6,5,7,2};
float x[6]={0,0.25,23.45,-0.9,456.3,12.34};

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
The array size need not be specified explicitly when initial values
are included as a part of an array declaration. With a numerical
array, the array size will automatically be set equal to the
number of initial values included within the declaration.
int digits[]={1,2,3,4,5,6}; six element integer array
float x[]={0,0.25,-56.34,78.45}; four element real array.
Array overflow:
It is illegal to access a non-existent element of the array. C
language will not check for array overflow. It is programmers
responsibility to ensure that any subscripting performed does not
cross the upper as well as the lower bounds of the array.
int array[5];
array[5]=105; /* Illegal */
Some other variables that the program uses are being over written.

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Processing an Array:
Single operations involving entire arrays are not permitted in C. If a and b are two
similar arrays of the same data type, same dimensionality and same size,
assignment operations, comparison operations etc., must be carried out on an
element-by-element basis.
This is done within a loop, where each pass through the loop is used to process
each element of an array. The number of passes through the loop will therefore
be equal to the number of array elements to be processed and the value of the
index (subscript) should be incremented from 0 to n-1.

Write a C program to find the largest element in an array and position of it’s
occurrence.
#include<stdio.h>
#include<conio.h>
void main()
{

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
int a[100], lar,pos,n,i;
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
lar=a[0]; pos=0;
for(i=1;i<n;i++)
{
if(lar<a[i])
{
lar=a[i];
pos=i;
}
}
printf("\nLargest element in the array is %d",lar);
printf("\nLargest element position in the array is %d",pos+1);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Write a C program to read N student marks and find the class Average using arrays.
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[100],i,n;
float avg,sum=0;
clrscr();
printf("\nEnter the number of students in the class : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&marks[i]);
sum+=marks[i];
}
avg=sum/n;
printf("\nClass Average = %.2f",avg);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Write a C program to find the largest and smallest elements in an array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,n,lar,small;
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
lar=a[0]; small=a[0];
for(i=0;i<n;i++)
{
if(lar<a[i]) lar=a[i];
if(small>a[i]) small=a[i];
}
printf("\nThe largest element in the array is = %d",lar);
printf("\nThe smallest element in the array is = %d",small);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
ARRAYS (Contd.)
Write a C program to generate N Fibonacci numbers using arrays.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,n;
clrscr();
printf("\nEnter the number of elements in the series : ");
scanf("%d",&n);
a[0]=0;
a[1]=1;
for(i=2;i<n;i++)
a[i]=a[i-2]+a[i-1];
printf("\nFibonaci numbers are \n\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Sorting
Sorting:
Sorting is the technique of arranging elements either in ascending or descending
order.
BUBBLE SORT
In Bubble sort each element is compared with the adjacent element. If the first
element is larger than the second then the position of the elements are
interchanged, otherwise it is not changed. Then next element is compared with
the adjacent element and same process is repeated for all the elements in the
array. During the first pas, the largest element occupies the last position. During
the next pass the same process is repeated leaving the largest element.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,t;
clrscr();

By syed ilyas
ahamed,tumkur,karnataka.
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements of the array : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
printf("\nArray in the sorted order is : \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Selection sort:
The selection sort is based on the minimum/maximum technique, By
means of a nest of for loops, a pass through the array is made to
locate the minimum vale. Once this is found, it is placed in the first
position of the array (position 0). Another pass through the remaining
elements is made to the next smallest element, which is placed in the
second position (position 1), and so on. Once the next-to-last element
has been compared with the last one, all the elements of the array
have been sorted into ascending order.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,t;
clrscr();

By syed ilyas
ahamed,tumkur,karnataka.
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements of the array : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("\nArray in the sorted order is : \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Linear search
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,item,loc=-1;
clrscr();
printf("\nEhter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements into the array : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the number to be searched : ");
scanf("%d",&item);
for(i=0;i<n;i++)
if(item==a[i])
{
loc=i;
break;
}

By syed ilyas
ahamed,tumkur,karnataka.
if(loc>=0)
printf("\nSEARCH SUCCESSFUL!! %d is found in position %d",item,loc+1);
else
printf("\nSEARCH UNSUCESSFUL!!");
getch();
}

BINARY SEARCH
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,item,n,beg,end,mid;
clrscr();
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nEnter the elements into the array in descending order :\n ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

By syed ilyas
ahamed,tumkur,karnataka.
printf("\nEnter the item to be searched : ");
scanf("%d",&item);
beg=0;
end=n-1;
mid=(beg+end)/2;
while(item!=a[mid]&&beg<=end)
{
if(item>a[mid])
end=mid-1;
else
beg=mid+1;
mid=(beg+end)/2;
}
if(item==a[mid])
printf("\nSearch is Successful, %d is found in position %d",item,mid+1);
else
printf("\nSearch Unsucessful!!!");
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
#include<stdio.h>
#include<conio.h>
void main()
{
int A[10][10],B[10][10],C[10][10],i,j,m,n,p,q,k;
clrscr();
printf("\nEnter the number of rows and columns of mat-A : ");
scanf("%d %d",&m,&n);
printf("\nEnter the number of rows and columns of mat-B : ");
scanf("%d %d",&p,&q);
if(n==p)
{
printf("\nMatrices can be multiplied !!");
printf("\nEnter the elements of mat-A :\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&A[i][j]);
printf("\nEnter the elements of mat-B :\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&B[i][j]);

By syed ilyas
ahamed,tumkur,karnataka.
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
C[i][j]=0;
for(k=0;k<n;k++)
C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
printf("\nResultant of A and B matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",C[i][j]);
printf("\n");
}

By syed ilyas
ahamed,tumkur,karnataka.
printf("\nThe Transpose of the resultant matrix is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d\t",C[j][i]);
printf("\n");
}
}
else
printf("\nMatrices cannot be multiplied !!!");

getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
Strings
Strings: Strings are arrays that contain ASCII characters. In a character
array each element may be a character constant or a string constant.
One dimensional Array:
The string is a one-dimensional array of characters.
For ex: “Computer”, is a string of 8 characters.

C o m p u t e r \0

contains (n+1) array elements.


Each one-dimensional character array (string) ends with a null
character(\0).

By syed ilyas
ahamed,tumkur,karnataka.
String handling functions:
1) Length (number of characters in a string)
2) Concatenation (Adding two or more strings)
3) Comparing two strings
4) Substring (extract sub string from the given string).
5) Copy (copies one string over another).

strlen( ) function:
This function counts and returns the number of characters in a
string. The length does not include the NULL character.
Syntax:
n=strlen(string);
where n is an integer variable which receives the value of the length
of the string.

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the length of a string using strlen() function.
#include<stdio.h>
#include<conio.h>
void main()
{
char text[40];
int length;
clrscr();
printf(“\nEnter a string : “);
gets(text);
length=strlen(text);
printf(“\nThe length of the string is %d”,length);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the length of a string without using strlen() function.
#include<stdio.h>
#include<conio.h>
void main()
{
char text[40];
int length i=0;
clrscr();
printf(“\nEnter a string : “);
gets(text);
while(text[i]!=‘\0’)
i++;
length=i;
printf(“\nThe length of the string is %d”,length);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the frequency of occurrence of a specified character.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[40] ,ch;
int i,length,count=0;
clrscr();
printf(“\nEnter a string : “);
gets(text);
printf(“\nEnter a character to be searched : “);
ch=getchar();
length=strlen(text);
for(i=0;i<length;i++)
if(text[i]==ch)
count++;
if(count)
printf(“\n%c is found %d times”,ch,count);
else
printf(“\n%c does not exist in the text”,ch);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
strcat() function:
When you combine two strings, you add the characters of one string to
the end of another string. The process is called concatenation. The
strcat() function joins two strings together.
Syntax:
strcat(string1,string2);
String2 is appended to string1, string2 remains unchanged.

Write a C program to concatenate two strings using built-in string function.


Write a C program to concatenate two strings without using string built-in
function.
#include<stdio.h>
#include<conio.h>
#include<string.h>

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
char str1[40],str2[40];
int i,len1,len2;
clrscr();
printf(“\nEnter the first string : “);
gets(str1);
printf(“\nEnter the second string : “);
gets(str2);
len1=strlen(str1);
len2=strlen(str2);
for(i=0;i<len2;i++)
str1[len1+i]=str2[i];
str1[len1+len2]=‘\0’;
printf(“\nConcatenated string is %s”,str1);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
strcmp() function
You cannot directly compare the value of 2 strings in a condition like this:
if(string1==string2)
Instead, strcmp() function is used, which returns a zero if 2 strings are
equal, a non-zero number if the strings are not the same.
Syntax:
strcmp(string1,string2)
returns a negative number if the string1 is alphabetically “less than”, the
second string.
returns a positive number if the first string is greater than the second.
strcmpi() function
This function is same as strcmp(), which compares 2 strings but not case
sensitive.

strcmpi(“THE”,”the”) will return 0.

By syed ilyas
ahamed,tumkur,karnataka.
strcpy() function
C does not allow you to assign characters to a string directly, as in the statement.
name=“Sachin”;
Instead , use the strcpy() function.
Syntax: strcpy(string1,string2);
It assigns the contents of string2 to string1. String2 may be a character array or a string
constant.
Write a C program to copy one string to another without using library function.
#include<stdio.h>
#include<conio.h>
void main()
{
char src[30],dst[30];
int i=0;
clrscr();
printf(“\nEnter a string : “);
gets(src);

By syed ilyas
ahamed,tumkur,karnataka.
while(src[i]!=‘\0’)
{
dst[i]=src[i];
i++;
}
dst[i]=‘\0’;
printf(“\nDestination string is %s”,dst);
getch();
}

strlwr() function
This function converts all characters in a string from uppercase to lowercase.
Syntax: strlwr(string);

Write a C program to accept a string and convert all characters in a string from uppercase to
lowercase without using library function.

By syed ilyas
ahamed,tumkur,karnataka.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[40];
int i=0;
clrscr();
printf(“\nEnter the string : “);
gets(str);
while(str[i]!=‘\0’)
{
if(str[i]>=‘A’ && str[i]<=‘Z’)
str[i]=str[i]+32;
i++;
}
printf(“\nConverted string in lowercase is %s”,str);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
strrev() function:
This function reverses the characters in the string.
Syntax:
strrev(string);
Write a C program to accept a string and print it in the reverse order without using library function.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[40],revstr[40];
int i, length;
clrscr();
printf(“\nEnter a string : “);
gets(str);
length=strlen(str);
for(i=0;i<length;i++)
revstr[i]=str[length-i-1];
revstr[length]=‘\0’;
printf(“\nReversed string is %s”,revstr);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
strupr() function
This function converts all characters in a string from lowercase to uppercase.
Syntax:
strupr(string);
Write a C program to convert all the lowercase characters into the uppercase
characters in the given string using library function.

Write a C program to convert all the lowercase characters into the uppercase
characters in the given string without using library function.
Write a C program to extract a substring from the given string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()

By syed ilyas
ahamed,tumkur,karnataka.
{
char str[40];
int i,len,pos,n;
clrscr();
printf("\nEnter a string : ");
gets(str);
len=strlen(str);
printf("\nEnter the position of the substring to be extracted : ");
scanf("%d",&pos);
printf("\nEnter number of characters to be extracted : ");
scanf("%d",&n);
if(pos+n-1>len)
printf("\nInvalid position");
else
{
printf("\nSubstring : ");
for(i=pos-1;i<pos+n-1;i++)
printf("%c",str[i]);
}
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to check whether a given word is a palindrome or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("\nEnter a word : ");
gets(str1);
strcpy(str2,str1);
strrev(str2);
if(strcmp(str1,str2)==0)
printf("\n%s is a palindrome",str1);
else
printf("\n%s is not a palindrome",str1);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Other string functions: <ctype.h>
isalnum()
isalpha()
isascii()
iscntrl()
isdigit()
islower()
isprint()
isspace()
isupper()
isxdigit()
toascii()
tolower()
toupper()
_tolower()
_toupper()

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to accept a string and find the number of numeric characters, lowercase, uppercase
characters and any other characters.
void main()
{
char str[30];
int upalpha=0,lowalpha=0,digit=0,special=0,length,i;
clrscr();
printf("\nEnter a string : ");
gets(str);
length=strlen(str);
for(i=0;i<length;i++)
if(isupper(str[i])) upalpha++;
else if(islower(str[i])) lowalpha++;
else if(isdigit(str[i])) digit++;
else special++;
printf("\nNumber of uppercase = %d",upalpha);
printf("\nNumber of lowercase = %d",lowalpha);
printf("\nNumber of digits = %d",digit);
printf("\nNumber of special characters = %d",special);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
FUNCTIONS
Functions
The basic philosophy of functions is “divide and Conquer” by which a
complicated tasks are successively divided into smaller subprograms
that can be developed and tested separately. This is called a modular
design approach.
A subprogram is a complete and independent program which can be used
(or invoked) by the main program or other sub programs. A sub
program receives values (called arguments) from a calling (original)
program, performs calculations, and then sends back (RETURNs) the
result or results to the calling program.
Purpose and use of sub programs
1. Repetition – Avoid rewriting the same sequence of code.
2. Universal use – can be used by more than one program.
3. Modularity – Independency, ease in readability, testing and debugging.
4. Team work.

By syed ilyas
ahamed,tumkur,karnataka.
Function Definition:
datatype function_name(argument list)
Argument declaration;
{
local variable declaration;
executable statement/s;
return(expression);
}
By syed ilyas
ahamed,tumkur,karnataka.
The following function product, finds the product of two integer numbers.
#include<stdio.h>
#include<conio.h>
int product(x,y)
int x,y;
{
int p;
p=x*y;
return (p);
}
void main()
{
int a,b,res;
clrscr();
printf("\nEnter the value of two numbers : ");
scanf("%d %d",&a,&b);
res=product(a,b);
printf("\nThe product of %d and %d is = %d",a,b,res);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Argument declaration can also be written in function header, as
int product(int x, int y)
Calling a function:
As the function is an independent unit (with its own declarations, type body etc). It establishes
link with the calling program unit through the use of formal parameters. These parameters
also serve to supply input values to the body of the function. A function invocation requires
that the order and datatype of the actual parameters match exactly with the order and
datatype of the formal parameters.
#include<stdio.h>
#include<conio.h>
int sum(int a, int b)
{
int s;
s=a+b;
return (s);
}

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
int x,y,res;
clrscr();
printf("\nEnter the value of two numbers : ");
scanf("%d %d",&x,&y);
res=sum(x,y);
printf("\nThe sum of %d and %d is = %d",x,y,res);
getch();
}
The variables a & b defined in function definition, are known as formal parameters or dummy
parameters or place holders.
The variables x & y are actual parameters, they specify the values that are passed to the
function sum. x & y are arguments in the function call.

The return statement:


Information will be passed to the function via special identifiers called arguments (also called
actual parameters) and returned via the return statement. Some functions, however, accept
information but do not return anything, where as some functions returns value of the
expression.

By syed ilyas
ahamed,tumkur,karnataka.
The return statement can take one of the following forms.
return;
or
return(expression);
The first return does not return any value. The return statement simply returns control to the point from
where it was called from, in the calling program. The second form of the return with an expression
returns the value of the expression.
Note: No separate return statement is necessary to send back the control. When the closing brace (}) of the
called function is encountered the control is returned to the calling function.
Types of functions:
A function may belong to one of the following categories.
1. Function with no arguments and no return values.
2. Function with arguments and no return values.
3. Function with no arguments and with return values.
4. Function with arguments and with return values.
Write a C program to illustrate functions with no arguments and no return values.
#include<stdio.h>
#include<conio.h>
void msg1()
{
printf("\nHello, This is the first function call\n");
}

By syed ilyas
ahamed,tumkur,karnataka.
void msg2()
{
printf("\nHi, This is the second function call\n");
}
void lineprint()
{
int i;
for(i=1;i<60;i++)
printf("_");
printf("\n");
}
void main()
{
clrscr();
msg1();
lineprint();
msg2();
lineprint();
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to illustrate functions with arguments and no return values.
#include<stdio.h>
#include<conio.h>
void largest(int a, int b)
{
if(a>b)
printf(“\nLargest element is = %d”,a);
else
printf(“\nLargest element is = %d”,b);
}
void main()
{
int x,y;
clrscr();
printf(“\nEnter the values of x and y : “);
scanf(“%d %d”,&x, &y);
largest(x,y);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to illustrate functions with no arguments and with return values.
#include<stdio.h>
#include<conio.h>
int largest()
{
int a,b;
printf(“\nEnter the values of a and b : “);
scanf(“%d %d”,&a, &b);

if(a>b)
return a;
else
return b;
}
void main()
{
int large;
clrscr();
large=largest();
printf(“\nThe largest number is = %d”,large);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a function big to find the largest of two numbers. Using big function write a C program to find the
largest of three numbers.
#include<stdio.h>
#include<conio.h>
int big(int a, int b)
{
if(a>b)
retrun a;
else
return b;
}
void main()
{
int x,y,z,large;
clrscr();
printf(“\nEnter the values of x, y and z : “);
scanf(“%d %d %d”,&x, &y,&z);
large=big(big(x,y),z);
printf(“\nThe largest of %d, %d and %d is = %d”,x,y,z,large);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
C provides two mechanisms to pass arguments to a function.
• Pass arguments by value, and
• Pass arguments by address or by pointers.
An argument may take the form of a constant, variable, expression, pointer, structure etc.
Passing arguments by value:
Passing arguments by value means that the contents of the arguments in the calling function
are not changed, even if they are changed in the called function. This is because the
contents of the variables is copied to the formal parameters of the function definition, thus
preserving the contents of the arguments in the calling function.
#include<stdio.h>
#include<conio.h>
void modify(int Num)
{
printf(“\nThe value of Num in modify function is : %d”,Num);
Num=Num+250;
printf(“\nThe value of Num in modify function later is : %d”,Num);
}

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
int Num=100;
clrscr();
printf(“\nThe value of Num in main function before is : %d”,Num);
modify(Num);
printf(“\nThe value of Num in main function after is : %d”,Num);
getch();
}
Write a C program to swap two numbers using Pass by value.
#include<stdio.h>
#include<conio.h>
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
}

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
int a,b;
clrscr();
printf(“\nEnter the value of two numbers : “);
scanf(“%d %d”,&a,&b);
printf(“\nBefore swapping the value of a = %d, b= %d”,a,b);
swap(a,b);
printf(“\nAfter swapping the value of a = %d, b = %d”,a,b);
getch();
}
Write a C program to swap two numbers using Pass by address.
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
int a,b;
clrscr();
printf(“\nEnter the value of two numbers : “);
scanf(“%d %d”,&a,&b);
printf(“\nBefore swapping the value of a = %d, b= %d”,a,b);
swap(&a,&b);
printf(“\nAfter swapping the value of a = %d, b = %d”,a,b);
getch();
}
Instead of passing two integers to the swap function, we can pass the addresses of the integers
that we want to swap. For this, two changes are required.
First, the function definition must be changed to accept, the addresses of the two integers. This
is done by specifying.
void swap(int *a, int *b)
instead of
void swap(int a, int b)

By syed ilyas
ahamed,tumkur,karnataka.
Inside the function, instead of using a, which now means memory address of an integer, we have to access the
value that is addressed by a. This is done by using *a instead of a and *b instead of b.
Second, the call in the main function must be changed to pass the addresses of I and j instead of their values.
This is done by calling
swap(&a,&b);
instead of
swap(a,b);
Write a C program to find the factorial of a number using functions.
#include<stdio.h>
#include<conio.h>
long fact(unsigned int n)
{
long Fact=1;
int i;
if(n==0)
return Fact;
else
for(i=2;i<=n;i++)
Fact=Fact*i;
return Fact;
}

By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
unsigned int Num;
long factorial;
clrscr();
printf(“\nEnter a number whose factorial has to be found : “);
scanf(“%u”,&Num);
factorial=fact(Num);
printf(“\nThe factorial of %u is = %ld”,Num,factorial);
getch();
}
Write a C program to generate Fibonacci series using iteration.
#include<stdio.h>
#include<conio.h>
void Fib(unsigned int Num)
{
unsigned int fnum=1,snum=0;
unsigned int curnum;
printf(“\nFibonacci numbers :”);
printf(“\n0”);

By syed ilyas
ahamed,tumkur,karnataka.
do
{
curnum=fnum,snum;
printf(“\n%u”,curnum);
snum=fnum;
fnum=curnum;
num--;
}while(num>1);
return;
}
void main()
{
unsigned int n;
clrscr();
printf(“\nProgram to generate Fibonacci Numbers : “);
printf(“\nEnter the total number to be generated : “);
scanf(“%u”,&n);
Fib(n);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to print the sum of first 20 numbers using function
sum20() which computes the sum of first 20 numbers.
Recursion:
Expressing an entity in terms of itself is called recursion.
In C, a function can call any function that has been defined, including
itself.
#include<stdio.h>
#include<conio.h>
long fact(unsigned int num)
{
if(num==0)
return 1;
else
return fact(num-1)*num;
}
By syed ilyas
ahamed,tumkur,karnataka.
void main()
{
unsigned int n;
clrscr();
printf(“\nEnter an integer whose factorial has to be
found : “);
scanf(“%u”,&n);
printf(“\nThe factorial of %u is %l”,n,fact(n));
getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to find the GCD of two numbers using recursion.
#include<stdio.h>
#include<conio.h>
unsigned gcd(unsigned m,unsigned n)
{
if(n>m)
return gcd(n,m);
if(n==0)
return m;
else
return gcd(n,m%n);
}
void main()
{
unsigned int a,b,GCD;
clrscr();
printf("\nEnter the value of two numbers whose GCD has to be found : ");
scanf("%u %u",&a,&b);
GCD=gcd(a,b);
printf("\nThe GCD of %u and %u is = %u",a,b,GCD);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Write a C program to generate Fibonacci series using recursion.
#include<stdio.h>
#include<conio.h>
long int fibo(int k)
{
if(k==1) return 0;
else if(k==2) return 1;
else return (fibo(k-1)+fibo(k-2));
}
void main()
{
long int i,n;
clrscr();
printf("\nEnter number of elements to be generated in the series : ");
scanf("%ld",&n);
printf("\nFibonacci numbers : \n");
for(i=1;i<=n;i++)
printf("%ld\t",fibo(i));
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
POINTERS
The significance of pointers in C is the flexibility it offers in programming. In C, a
pointer is a variable that points to, or references, a memory location in which
data is stored. Each memory cell in the computer has an unique address that
can be used to access that location. So a pointer variable points to a memory
location.
We can access and change the contents of this memory location via the pointer.
The other uses of pointers are:
Accessing array elements.
Passing arguments to functions by references (i.e., the arguments can be
modified).
Passing arrays and strings to functions.
Creating data structures such as linked lists, trees, graphs, and so on.
Obtaining memory from the system dynamically.
For example, for reading the marks of a set of students and processing them, an
array can be declared with the statement:
float marks[100];

By syed ilyas
ahamed,tumkur,karnataka.
But this limits the maximum number of students to 100. We are fixing the
maximum number while writing the program, We are aware that
memory is allocated to variables in a program block at the time when
the block execution is to begin. Moreover, it remains in existence as
long as the block is executing. Such variables are called as static
variables. Static variables are referenced by user-defined names.
Storage assigned for such variables cannot be altered during execution
of the program.
This has the disadvantage that if the number of students is very few, say
10 or 20, then the excess memory that has been assigned in the
beginning, most of the memory will remain unutilized, On the other
hand if the number of students is greater than 100, then the memory
assigned will be less, the program will have to be recompiled after
deciding the appropriate size of the memory, or else by using dynamic
memory allocation, we can design the program such that the limit for
the maximum number of students is restricted only by the amount of
available memory.

By syed ilyas
ahamed,tumkur,karnataka.
Variables can be created and defined when the program is being executed. Memory can be
obtained from the system, if available, and allocated for the creation of a new variable or
data structure. This is called dynamic memory allocation. Dynamic variables so created can
only be accessed by the use of pointers.
Pointers offer tremendous flexibility in creation of dynamic variables, accessing and
manipulating the contents of memory locations, and releasing the memory occupied by the
dynamic variables which are no longer needed.
Pointer declaration:
Syntax: datatype *variable_name;
datatype  variable type being pointed to.
*  Asterisk denotes a pointer.
variable_name  pointer variable name.
A pointer operator can be represented by the combination of * with a variable.
Ex: int *ptr;
Creates a pointer type variable(indicated by the asterisks) named ptr that will contain the
address of an integer type variable.
float *radius;
Creates a pointer named radius that will contain the address of a float variable.

By syed ilyas
ahamed,tumkur,karnataka.
Address operator:

int num; 24560 75


num is in address 24560

int *ptr; 24568 24560 ptr is here

ptr = &num;
24560 is placed here

By syed ilyas
ahamed,tumkur,karnataka.
A program to illustrate pointer declaration:
#include<stdio.h>
#include<conio.h>
void main()
{
int *ptr, num;
num=45;
ptr=&num;
clrscr();
printf("\nNum is %d and the address of num is %u",num,&num);
printf("\nThe num pointer holds %u and the value the pointer addressed
to is %d",ptr,*ptr);
printf("\nThe address of the pointer is %u",&ptr);
getch();
}
By syed ilyas
ahamed,tumkur,karnataka.
Pointer expressions and pointer arithmetic:
Pointers are variables. They are not integers, but they can usually be displayed as
unsigned integers. The conversion specifier for a pointer is added or subtracted.
For example: int ptr; ptr++; causes the pointer incremented, but not by 1, but with
2 because int holds two bytes(address)
The general rule about pointer arithmetic is, an arithmetic operation of pointer
performs the operation in bytes of the appropriate storage class.
If ptr1 and ptr2 are declared as pointer variables.
Valid operations Invalid operations
*ptr1 = *ptr1 + *ptr2; ptr1 + ptr2;
sum=*ptr1 + 10; ptr1/ptr2;
sum+= *ptr2; ptr1*ptr2;
result = 10 * - *ptr1/*ptr2;
ptr1>ptr2;
ptr2!=ptr1;

By syed ilyas
ahamed,tumkur,karnataka.
A program to illustrate the pointer expression and pointer arithmetic.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,x,y,z;
int *ptr1, *ptr2;
a=30,b=6;
ptr1=&a; ptr2=&b;
x=*ptr1 + *ptr2 - 6;
y=6 - *ptr1 / *ptr2 + 30;
clrscr();
printf("\nAddress of a = %u",ptr1);
printf("\nAddress of b = %u",ptr2);
printf("\na = %d, b = %d",a,b);
printf("\nx = %d, y = %d",x,y);
*ptr1=*ptr1+70;
*ptr2=*ptr2 * 2;
printf("\na = %d, b = %d",a,b);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Pointers and Functions:
The usage of pointers in a function definition may be
classified into two groups:
1. Call by value.
2. Call by reference.

Program to illustrate call by value


(Refer Functions chapter)
Program to illustrate call by reference
(Refer Functions chapter)
Pointers and Arrays:
By syed ilyas
ahamed,tumkur,karnataka.
Structures
Structures :
Structures are collection of unlike data types, just as arrays are collection of like data types.
A structure is a collection of one or more variables, possibly of different types, grouped together under a
single name for convenient handling. The individual structure elements are referred to as members.
Structures help to organize complicated data, particularly in large programs, because they permit a group
of related variables to be treated as a unit instead of separate entities.
Structure definition:
A structure within a C program is defined as follows:
struct struct_type(tag)
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
………
……..
};
In this declaration,
struct is a required keyword,
struct_type is a name(tag) that identifies structures of this composition
member_type1 member_name1, member_type2 member_name2 …. Are individual member declarations.

By syed ilyas
ahamed,tumkur,karnataka.
The individual members can be ordinary variables, pointers, arrays, or other structures.
The member names within a particular structure must be distinct from one another, though a
member name can be the same as the name of a variable defined outside the structure.
A storage class cannot be assigned to an individual member, and individual member cannot be
initialized within a structure type declaration.
Unlike the declaration of a variable or array, defining a structure causes no storage to be
reserved. By defining a structure, the programmer derives a new data type composed of a
collection of already known data types and their names.
For example, Suppose that the information about 10,000 business accounts has to be
maintained. Te information is mixed in type, for each account the following are required
Account number (int)
Account type (int)
Name (30 character array)
Street address (50 character array)
Balance (long)
Last payment date (long)

Each account will have one of the structures, defined as follows

By syed ilyas
ahamed,tumkur,karnataka.
struct acount
{
int act_no;
int acct_type;
char name[30];
char address[50];
long balance;
long last_payment;
};
Once the composition of the structure has been defined, individual structure
variables can be declared as follows:
struct struct_type(tag) variable1, variable2, ….variablen;
A variable of the above type is declared like this:
struct account customer;
Where the variable name is customer and the data type is struct account.
It is also possible to define a structure and declare a variable of that type at the
same time.
By syed ilyas
ahamed,tumkur,karnataka.
struct student
{
int regno;
char name[30];
char course;
float fees;
float fees_paid;
float balance;
}stud1,stud2,stud3;
Structure initialization:
Structures can be initialized similarly to arrays. When initializing structures, the initial value of each
member of the structure must be listed and must appear in the order in which they will be assigned
to their corresponding structure members, enclosed in braces and seperated by comma as follows:
struct sample
{
int x;
char y;
float z;
};
Struct sample temp={123, ‘a’, 123.45};

By syed ilyas
ahamed,tumkur,karnataka.
Referencing structure members:
Individual structure members can be referenced with the dot(.)
operator. For example in the previous declaration of the variable
stud1 can be referenced to as:
stud1.regno;
On its left, the dot operator expects the name of a declared
structure and on its right the name of one of the members of
that structure. The three parts combine to form an expression
whose value is the value of the structure member.
The dot operator is a member of highest precedence group, and its
associativity is left to right. This operator takes the precedence
over the unary operators as well as the various arithmetic,
relational, logical and assignment operators.

By syed ilyas
ahamed,tumkur,karnataka.
A C program to illustrate the definition of a structure, the declaration of a structure variable,
and referencing of a member of the declared structure variables.
#include<stdio.h>
#include<conio.h>
void main()
{
struct account

{ int acct_no;
int acct_type;
char name[30];
char address[50];
long balance;
long last_payment;
};
struct account vendor={1001,1,”Aneesh”,”No.123, 4th main, Vijaynagar, B’lore”, 54603,5000};
printf(“\nEnter account number : “);
scanf(“%d”,&acct_no);

By syed ilyas
ahamed,tumkur,karnataka.
if(acct_no==vendor.acct_no)
{
printf(“\nThe previous balance : %ld”,vendor.balance);
printf(“\nEnter the payment amount : “);
scanf(“%ld”,&vendor.last_payment;
vendor.balance-=vendor.last_payment;
printf(“\nThe latest balance : %ld”,vendor.balance);
}
else
printf(“\nInvalid account number !!”);
getch();
}
Array of structures:
It is possible to define an array of structures that is, an array in which each element is a
structure. The array of structures is declared:
struct account vendors[10];
In this declaration vendor is a 10 element array of structures. Hence, each element of vendor is
a separate structure of type account.

By syed ilyas
ahamed,tumkur,karnataka.
An array of structures can be assigned initial value just as any other array can.
Each array element is a structure and must be assigned a corresponding set of initial values.
The following is an example of initializing an array of structures.
struct sample sarray[3]={
{123,’a’,123.45},
{234,’b’,234.56},
{345.’c’345.67}
};
If an array of structure is declared.
struct account vendors[10];
Then the account number in the third structure can be referenced through the following
expression.
vendors[2].acct_no
Where the name of the structure is: vendors[2]
and the member name is: acct_no
#include<stdio.h>
#include<conio.h>
void main()
{

By syed ilyas
ahamed,tumkur,karnataka.
struct employee
{
char name[30];
int sal;
int emp_id;
};
struct employee a[]=
{
{"Arun",20000,101},
{"Mohan",15000,102},
{"Sheela",18000,103}
};
int i;
clrscr();
printf("\nEMPLOYEE ID \tNAME \tSALARY");
for(i=0;i<3;i++)
printf("\n%d\t\t%s\t%d",a[i].emp_id,a[i].name,a[i].sal);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.
Nested structures (structures within structures):
The C language allows one structure to be included inside another, these are known as nested
structures.
Nested structures usually exist in more complicated programs or systems where the size of structures
can be very large, or where an array of structures is desired inside one structure definition.
To illustrate this, extend the structure type account to include information about the last three
payments made to this vendor. The following information is included in each of the transactions:
Invoice number (int)
Invoice date (int)
Amount of purchase (long)
Date paid (long)
This information can be added to the account structure as follows:
struct history
{
int inv_no;
long inv_date;
long inv_amt;
long inv_paid;
};

By syed ilyas
ahamed,tumkur,karnataka.
struct account
{
int acct_no;
int acct_type;
char name[30];
char address[50];
long balance;
long last_payment;
struct history payments[3];
};
To access one of the members inside one of the payments structures, first, the proper structure
has to be addressed and then the proper member of that structure.
If a variable of type struct account with the name vendors, is defined as follows:
struct account vendors;
The invoice number of the most recent invoice can be accessed by the following expression:
Vendors.payments[0].inv_no
Passing structures to Functions:
It is possible to pass entire structure to functions as well as supply them as return values. It is
also possible to make structure assignments.

By syed ilyas
ahamed,tumkur,karnataka.
The individual structure members can be passed the same way as ordinary, single valued
variables.
A complete structure can be transferred to a function by passing a structure directly or by
passing structure_type pointer as an argument.

By syed ilyas
ahamed,tumkur,karnataka.
#include<stdio.h>
#include<conio.h>
void main()
{
union record
{
int regno;
char name[40];
float avg;
}rec1;
rec1.regno=101;
clrscr();
printf("\nThe student details are : ");
printf("\nRegno = %d",rec1.regno);
printf("\nName = %s",rec1.name);
printf("\nAverage = %f",rec1.avg);
getch();

By syed ilyas
ahamed,tumkur,karnataka.
clrscr();
strcpy(rec1.name,"ANEESH");
printf("\nThe student details are : ");
printf("\nRegno = %d",rec1.regno);
printf("\nName = %s",rec1.name);
printf("\nAverage = %f",rec1.avg);
getch();
clrscr();
rec1.avg=84.50;
printf("\nThe student details are : ");
printf("\nRegno = %d",rec1.regno);
printf("\nName = %s",rec1.name);
printf("\nAverage = %f",rec1.avg);
getch();
}

By syed ilyas
ahamed,tumkur,karnataka.

You might also like