Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

C Notes

Uploaded by

sirilkanuri01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C Notes

Uploaded by

sirilkanuri01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 85

C Language

Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”.
Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon
in order to get the expected results.

Advantages of Algorithms:

It is easy to understand.

Algorithm is a step-wise representation of a solution to a given problem.

In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it
into an actual program.

Disadvantages of Algorithms:

Writing an algorithm takes a long time so it is time-consuming.

Branching and Looping statements are difficult to show in Algorithms.

Flowcharts

What is a Flowchart?

Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a
problem. It makes use of symbols which are connected among them to indicate the flow of information and
processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.

Basic Symbols used in Flowchart Designs

Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a
program logic under some error conditions. Terminal is the first and last symbols in the flowchart.

Input/Output: A parallelogram denotes any function of input/output type. Program instructions that take input from input
devices and display output on output devices are indicated with parallelogram in a flowchart.

Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting, multiplication
and division are indicated by action or process symbol.

Diamond : It represents a decision point. Decision based operations such as yes/no question or true/false are indicated
by diamond in flowchart.

Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors
to avoid any confusions. It is represented by a circle.
Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction of
flow of control and relationship among different symbols of flowchart.

Advantages of Flowchart:

Flowcharts are better way of communicating the logic of system.

Flowcharts act as a guide for blueprint during program designed.

Flowcharts helps in debugging process.

With the help of flowcharts programs can be easily analyzed.

It provides better documentation.

Flowcharts serve as a good proper documentation.

Disadvantages of Flowchart:

It is difficult to draw flowchart for large and complex programs.

In this there is no standard to determine the amount of detail.

Difficult to reproduce the flowcharts.

It is very difficult to modify the Flowchart.


Introduction:

C is one of the foundations for information technology and computer science.

We use system in Computer architecture, Operating system, Networking communication, Database, graphics……..etc.,

C is most commonly use programming language in industries.

Most of the web browsers and word process are writer in c language.

C language is a base for almost all programming language.

Ex: C++,JAVA, Python, Perl, PHP, Ruby…….etc.,

History of language.

According to c….

In 1960 ALGOL(Algorithmic language) it is developed by international committee.

In 1963 CPL(Combined programming Language) it is developed by Cambridge university.

In 1967 BCPL(Basic combined programming Language) it is developed by Martin Richard at Cambridge university.

In 1970 B language Ken Thomson at AT&T Bell Lab’s.

In 1972 C language was introduced by Dennis Ritche at AT&T Bell Lab’s.

How c used in other languages:

C++:

C with classes in objects is known as C++.

JAVA:

In java we used in those language like C, C++.

C#:

It is a .net subject in this one of the package class based on c language.

PHP(Personal home page):

In this php we used scripting language is based on c language.

JAVA Script:

In this java script the syntax is same as c language.

Applications of C:

OS(operating Systems):

These are like Unix, Linux, window XP……etc…. In this operating systems are used in c coding.

ES(Embedded System):

These are nothing but the combination of software and hardware is known as c in embedded systems.

Ex: Computers, Phones, Laptops, TV…..etc.,

DD(Device Drivers):

In every software we can use device drivers. In this device driver it stores audios/videos configuration etc….,

Ex: Phones, printer…..,

Compiler:

These are nothing but the program to check the errors in program

Ex: C language, C++, java….,

Types of language:

They are two types of levels of language.


High level language:

Use English word to develop programs. These are easy to learn and use like COBOL, PHP or java. C also uses English word
in its programs and hence it is called high level programming language.

Low level language:

Use machine code instructions to developed programs. These instructions directly interact with the CPU. Machine language
and assembly language are called low level languages.

C tokens

Character sets :

These are nothing but the set of alphabets, digits are some specials characters. That is valid in c language.

Alphabets:

Upper Case: A to Z

Lower Case: a to z

Digits

0 to 9

Specials Characters:

These are the special characters are ~,!,@,#,$,%,^,&,*,(,),_,,+,=,|,\,{,},[,],:,;,”,’,< ,>,.,?,/.

Separators

Separators are symbols that indicate the division and arrangement for groups of codes.

parentheses ( )

Used to define precedence in expressions, to enclose parameters in method definitions, and enclosing cast types.

braces { }

Used to define a block of code and to hold the values of arrays.

brackets [ ]

Used to declare array types.

semicolon ;

Used to separate statements.

comma ,

Used to separate identifiers in a variable declaration in statement.

period (.)

Used to separate package names from classes and subclasses, for separate a variable or a method from reference
variable.

Keywords:

These are the reserved words used in programming each key word has a fixed meaning that can’t be changed by
a key words.

auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, go to, if, int, long, register,
return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while

Input and Output functions:

Input function:

scanf(“-----“); it is an input function. This is the function which can be used to read an input from the command
prompt.

Output function:

printf(“-----“); it is a output function. In this function which can be used to write the function an output from the
command prompt.
Sample Program Syntax:

#include<stdio.h>

main()

printf(“Welcome to ISAN”);

#include: is a folder called as preprocessor directive.

stdio.h – Standard input output.header. It can store the printf & scanf functions.

main()- Heart of the program.

Data types:

These are 3 types:

int (0 to 9)

float (decimal value)

char(A to Z, 0 to 9 or symbols within the single code(‘ ‘)

Data types Sizes

Short <2 bytes

Int 2 bytes

Long 8 bytes

Char 1 byte

Float 4 bytes

Double 8 bytes

Long Double 16 bytes

Formats:

int  %d

float  %f , %g

double  %lf

char  %c

string %s

short  %h

long int  %ld

unsigned  %u

#include<stdio.h>

main()

char ch='A';

char str[] = "ISAN Computer Education";

char ch1[5] = {'I','S','A','N'};

printf("The given character is %c\n",ch);


printf("The given string is %s\n",str);

printf("The given name is %s",ch1);

Escape sequences:

\nnew line

\ttab space

//double slash

#include<stdio.h>

main()

printf("My name is Meghana\n");

printf("\t\t I am learning C language \n");

//printf("\t\t In ISAN \n");

/*printf("\t\t I m very good girl\n");*/

#include<stdio.h>

main()

int a=1;

float b=2.0;

char g=’k’;

printf(“The value of g is %c \n",g);

printf(“The value of a is %d \n",a);

printf(“The value of b is %f \n",b);

printf("The values of a,b,g are %d %f %c",a,b,g);

#include<stdio.h>

main()

int a;

float b;

char g;

printf("the value of g is \n");

scanf("%c",&g);

printf("the value of a is \n");

scanf("%d",&a);

printf("the value of b is \n");

scanf("%f",&b);
printf("the values of a,b,g are %d %f %c",a,b,g);

If you want to give more than one characters in c program do this

#include<stdio.h>

main()

int a;

float b;

char ch[3]={'a','k','g'};

printf("the value of a is \n");

scanf("%d",&a);

printf("the value of b is \n");

scanf("%f",&b);

printf("the values of a,b,g,h,e are %d %f %c %c %c",a,b,ch[0],ch[1],ch[2]);

Operators

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.

C has a wide range of operators to perform various operations.

Several types of operators are

Arithmetic operators

Relational Operators

Assignment Operators

Increment and Decrement Operators

Logical Operators

Comma Operator

Sizeof Operator

Bitwise Operators

C Arithmetic Operators

An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on
numerical values (constants and variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)

#include <stdio.h>

main()

{
int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;

printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

c = a/b;

printf("a/b = %d \n",c);

c = a%b;

printf("Remainder when a divided by b = %d \n",c);

C Relational Operators

A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is
false, it returns value 0.

Relational operators are used in decision making and loops.

Operator Meaning of Operator

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

#include <stdio.h>

main()

int a = 5, b = 5, c = 10;

printf("%d == %d is %d \n", a, b, a == b);

printf("%d == %d is %d \n", a, c, a == c);

printf("%d > %d is %d \n", a, b, a > b);

printf("%d > %d is %d \n", a, c, a > c);

printf("%d < %d is %d \n", a, b, a < b);

printf("%d < %d is %d \n", a, c, a < c);

printf("%d != %d is %d \n", a, b, a != b);

printf("%d != %d is %d \n", a, c, a != c);

printf("%d >= %d is %d \n", a, b, a >= b);

printf("%d >= %d is %d \n", a, c, a >= c);

printf("%d <= %d is %d \n", a, b, a <= b);

printf("%d <= %d is %d \n", a, c, a <= c);

}
C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b

#include <stdio.h>

main()

int a = 5, c;

c = a;

printf("c = %d\n", c);

c += a;

printf("c = %d\n", c);

c -= a;

printf("c = %d\n", c);

c *= a;

printf("c = %d\n", c);

c /= a;

printf("c = %d\n", c);

c %= a;

printf("c = %d\n", c);

C Increment and Decrement Operators:

C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or
variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary
operators, meaning they only operate on a single operand.

#include <stdio.h>

main()

int a = 10, b = 100;

float c = 10.5, d = 100.5;

printf("++a = %d \n", ++a);

printf("--b = %d \n", --b);

printf("c++ = %f \n", c++);


printf("d-- = %f \n", d--);

printf("%f\n",c);

printf("%f",d);

C Logical Operators:

Operator Meaning

&& Logical AND. True only if all operands are true

|| Logical OR. True only if either one operand is true

! Logical NOT. True only if the operand is 0

An expression containing logical operator returns either 0 or 1 depending upon whether

#include <stdio.h>

main()

int a = 5, b = 5, c = 10, result;

result = (a == b) && (c < b);

printf("(a == b) && (c < b) is %d \n", result);

result = (a == b) && (c >b);

printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) || (c <b);

printf("(a == b) || (c < b) is %d \n", result);

result = (a != b) || (c < b);

printf("(a != b) || (c < b) is %d \n", result);

result = !(a != b);

printf("!(a != b) is %d \n", result);

result = !(a == b);

printf("!(a == b) is %d \n", result);

Comma Operator

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;

sizeof Operator

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

#include <stdio.h>

main()

{
int a;

float b;

double c;

char d;

printf("Size of int=%lu bytes\n",sizeof(a));

printf("Size of float=%lu bytes\n",sizeof(b));

printf("Size of double=%lu bytes\n",sizeof(c));

printf("Size of char=%lu byte\n",sizeof(d));

C – Bit wise Operators

In arithmetic-logic unit (which is within the CPU), mathematical operations like: addition, subtraction, multiplication and
division are done in bit-level. To perform bit-level operations in C programming, bitwise operators are used.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise complement

Bitwise AND operator &

The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.

Let us suppose the bitwise AND operation of two integers 12 and 25.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bit Operation of 12 and 25

00001100

&00011001

________

00001000 = 8 (In decimal)

#include<stdio.h>

int main()

int a =12, b =25;

printf("Output = %d", a&b);

return0;

Bitwise OR operator |

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator
is denoted by |.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)


Bitwise OR Operation of 12 and 25

00001100

|00011001

________

00011101 = 29 (In decimal)

#include<stdio.h>

int main()

int a =12, b =25;

printf("Output = %d", a|b);

return0;

Bitwise XOR (exclusive OR) operator ^

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25

00001100

^00011001

________

00010101 = 21 (In decimal)

#include<stdio.h>

int main()

int a =12, b =25;

printf("Output = %d", a^b);

return0;

Output

Output = 21

Bitwise complement operator ~

Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted
by ~.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35

~ 00100011

________

11011100 = 220 (In decimal)

Type casting and type conversion:


Type casting in program is used to modifies a variables from new data types should be mentioned before a variable name
and values in “()”.

It changes the value in one data type to another data type.

If we give numbers and ask the character data type of that given number , it gives the ASCII value of that given number.

ASCII value is something which is having a fixed value for each and every character, digit, symbol and every input from
the keyboard.

#include<stdio.h>

main()

int a;

printf("Enter any number");

scanf("%d",&a);

printf("%c",(char)a);

Control Statements

Loops are three types. They are

Decision control statements

Loop control statements

Case control statements or Jump controls statements

Decision controls statements:

In this statements we have if, if else, nested if else., statements are presents.

In this statements groups of statements are executed where condition becomes true. If condition false then else
statements will be printed.

if statements:

In this statements check whether the condition and text expression inside parenthesis “()” is true are not.

If the text expression is true statements inside the condition is executed. If it is false it ignores.

Syntax:

if(expression)

Statements;

#include<stdio.h>

main()

int a=10,b=20;

if(a==b)

printf("apple");

}
If_else statements:

In this statements when the if condition becomes false when the else part is printed.

When the if condition is true then the else part is not printed.

Syntax:

if(condition)

statements;

else

statement;

#include<stdio.h>

main()

int a=10,b=20;

if(a==b)

printf("banana");

else

printf("orange");

Nested if_else statements:

In this statements if condition one is false then the condition true is checked and statements are executed if it is
true. When condition is true is also false when else part will be executed.

Syntax:

if(condition)

Stmts;

else if(condition)

Stmts;

else

Stmts;

}
#include<stdio.h>

main()

int a=10,b=10;

if(a>b)

printf("apple");

else if(a<b)

printf("asdf");

else

printf("jkl");

Loop control statements:

In this statements in c are used to perform looping operation until the given condition is true.

Control comes out of the loop statements one’s condition becomes is false.

In this loop control statements are 3 types.

for loop

while loop

do while loop

For loop:

In programming, a loop is used to repeat a block of code until the specified condition is met.

Syntax:

for(Initialization;condition checking;Increment/decrement)

Statements;

#include<stdio.h>

main()

int a;

for(a=20;a>10;a--)

{
printf("%d \n",a);

While loop:

In this statements loop is executed until condition becomes false.

Syntax:

while(condition)

Stmts;

Increments or decrements;

#include<stdio.h>

main()

int i=1;

while(i<10)

printf("%d \n",i);

i++;

Do while loop:

In this loop is executed for the first time it ignores the condition after execution the while loop for the first time the
condition will be checked.

Syntax:

do

Stmts;

Increment or decrement;

while(condition);

#include<stdio.h>

main()

int i=0;

do
{

printf("%d \n",i);

i++;

while(i<=10);

#include<stdio.h>

main()

int a;

printf("enter the value of a");

scanf("%d",&a);

do

printf("%d \n",a);

a++;

while(a<=10);

Case control statements:

In this statements which are used to executed only specific block of statements is a series of block are called case
control statements.

Switch case

break

continue

goto

Switch case:

In this statements which are used to executed only specific block of statements is a series of block are called case
control statements.

Syntax:

Switch(condition)

Case 1:statements;

Case 2:statements;

Case 3:statemtents;

--------
--------

default: stmts;

Break case:

It mainly used in 2 ways in c programming.

The first one is used to terminate the loop, the second one is used to true condition in the switch.

Syntax:

break;

#include<stdio.h>

main()

int num=2;

switch(num)

case 1:

printf("hello");

break;

case 2:

printf("rams");

break;

case 3:

printf("raja");

break;

default:

printf("none of the above");

Continue:

In continue statements is used to continue the next iteration for loop, while loop and so to the remaining
statements are striked with in the loop for the particle interaction.

Syntax: Continue;

#include<stdio.h>

main()

int a=15;

do

if(a==20)

a=a+1;
continue;

printf("value of a: %d \n", a);

a++;

while(a<25);

Goto statements:

In this statements is used to transform a normal flow of a program to specific table program.

Syntax:

goto label

stmts;

stmts;

------

------

label

#include<stdio.h>

main()

int number;

printf("WWW.");

goto x;

y:

printf("expert");

goto z;

x:

printf("c programming");

goto y;

z:

printf(".com");

Extra Programs on Loops:

// C program to find the greatest of two numbers

#include<stdio.h>

int main()

int num1, num2;

scanf(“%d %d”,&num1,&num2);
if(num1 > num2)

printf(“%d is greater”,num1);

else

printf(“%d is greater”,num2);

return 0;

// C program to find the greatest of three numbers

#include<stdio.h>

int main()

int num1, num2, num3;

scanf(“%d %d %d”,&num1,&num2,&num3);

if(num1 > num2 && num1 > num3)

printf(“%d is greater”,num1);

else if(num2 > num1 && num2 > num3)

printf(“%d is greater”,num2);

else

printf(“%d is greater”,num3);

return 0;

//Prime or Not

#include<stdio.h>

int main()

int n,i,m=0,flag=0;

printf("Enter the number to check prime:");

scanf("%d",&n);

m=n/2;

for(i=2;i<=m;i++)

{
if(n%i==0)

printf("Number is not prime");

flag=1;

break;

if(flag==0)

printf("Number is prime");

return 0;

//Even or Odd

#include <stdio.h>

int main()

int num;

printf("Enter an integer: ");

scanf("%d", &num);

if(num % 2 == 0)

printf("%d is even.", num);

else

printf("%d is odd.", num);

return 0;

//Print first 10 natural numbers

#include <stdio.h>

void main()

int i;

printf("The first 10 natural numbers are:\n");

for (i=1;i<=10;i++)

printf("%d ",i);

printf("\n");

// Print first 10 even numbers

#include<stdio.h>

int main(void)

{
int n=0,i=0;

for(i=2;i<=20;i=i+2)

printf("%d ",i);

return 0;

// Print first 10 odd numbers

#include<stdio.h>

int main(void)

int n=0,i=0;

for(i=1;i<=20;i=i+2)

printf("%d ",i);

return 0;

// Sum of Even numbers in Given Range

#include<stdio.h>

int main()

int m,n,i,sum=0;

printf("Enter starting and ending even numbers:");

scanf("%d %d",&m,&n);

for(i=m;i<=n;i=i+2)

sum=sum+i;

printf("The sum of even numbers in given range is : %d",sum);

return 0;

// Sum of given odd numbers

#include<stdio.h>

int main()

int m,n,i,sum=0;

printf("Enter starting and ending odd numbers:");

scanf("%d %d",&m,&n);
for(i=m;i<=n;i=i+2)

sum=sum+i;

printf("The sum of even numbers in given range is : %d",sum);

return 0;

//Sum of all numbers in given range

#include<stdio.h>

int main()

int m,n,i,sum=0;

printf("Enter starting and ending numbers:");

scanf("%d %d",&m,&n);

for(i=m;i<=n;i=i++)

sum=sum+i;

printf("The sum of even numbers in given range is : %d",sum);

return 0;

// Palindrome (For strings java is necessary , C is not compatible for Strings)

#include<stdio.h>

int main()

int n,r,sum=0,temp;

printf("enter the number=");

scanf("%d",&n);

temp=n;

while(n>0)

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum)

printf("palindrome number ");

else

printf("not palindrome");
return 0;

//Armstrong or not

#include<stdio.h>

int main()

int n,r,sum=0,temp;

printf("enter the number=");

scanf("%d",&n);

temp=n;

while(n>0)

r=n%10;

sum=sum+(r*r*r);

n=n/10;

if(temp==sum)

printf("armstrong number ");

else

printf("not armstrong number");

return 0;

//Reverse of a number

#include<stdio.h>

int main()

int n, reverse=0, rem;

printf("Enter a number: ");

scanf("%d", &n);

while(n!=0)

rem=n%10;

reverse=reverse*10+rem;

n/=10;

printf("Reversed Number: %d",reverse);

return 0;

//Switch Case for Arthemetic Operations

#include<stdio.h>
main()

int a,b,c,j;

printf("enter two values \n");

scanf("%d %d",&a,&b);

printf("case 1:Add\n case 2:sub\n case 3:mul\n case 4:div\n case 5:mod\n");

printf("enter the case user want \n");

scanf("%d",&j);

switch(j)

case 1:c=a+b;

printf("the value of c is %d \n",c);

break;

case 2:c=a-b;

printf("the value of c is %d \n",c);

break;

case 3:c=a*b;

printf("the value of c is %d \n",c);

break;

case 4:c=a/b;

printf("the value of c is %f \n",c);

break;

case 5:c=a%b;

printf("the value of c is %d \n",c);

break;

default:

printf("there is no values \n");

//Vowel Program

#include<stdio.h>

main()

char i;

printf("Enter the charcter \n");

scanf("%c",&i);

switch(i)

case 'a':
printf("It is vowel");

break;

case 'e':

printf("It is vowel");

break;

case 'i':

printf("It is vowel");

break;

case 'o':

printf("It is vowel");

break;

case 'u':

printf("It is vowel");

break;

default:

printf("It is not a vowel");

//Find ASCII value of a character

#include<stdio.h>

int main()

char c;

printf("Enter a character : ");

scanf("%c" , &c);

printf("\n\nASCII value of %c = %d",c,c);

return 0;

//Eligibility to Vote

#include<stdio.h>

int main()

int a ;

printf("Enter the age of the person: ");

scanf("%d",&a);

if (a>=18)

printf("Eigibal for voting");

else
{

printf("Not eligibal for voting\n");

return 0;

//Swapping of two numbers

#include<stdio.h>

void main()

int x, y, temp;

printf("Enter two numbers");

scanf("%d %d",&x,&y);

printf("Before Swap\n");

printf("x = %d and y = %d", x, y);

temp = x;

x = y;

y = temp;

printf("\nAfter Swap");

printf("\nx = %d and y = %d", x, y);

//Leap Year or Not

#include <stdio.h>

main()

int year;

printf("Enter a year:\n");

scanf("%d",&year);

if (year % 4 == 0)

printf("%d is a leap year", year);

else

printf("%d is not a leap year", year);

// Factorial of a number

#include<stdio.h>

int main()

int i,fact=1,number;

printf("Enter a number: ");

scanf("%d",&number);

for(i=1;i<=number;i++)
{

fact=fact*i;

printf("Factorial of %d is: %d",number,fact);

return 0;

//GCD of two numbers

#include <stdio.h>

int main()

int n1, n2, i, GCD_Num;

printf ( " Enter any two numbers: \n ");

scanf ( "%d %d", &n1, &n2);

for( i = 1; i <= n1 && i <= n2; ++i)

if (n1 % i ==0 && n2 % i == 0)

GCD_Num = i;

printf (" GCD of two numbers %d and %d is %d.", n1, n2, GCD_Num);

return 0;

//LCM of two numbers

#include <stdio.h>

void main()

int num1, num2, max_div, flag = 1;

printf( " Enter any two positive numbers to get the LCM \n ");

scanf(" %d %d", &num1, &num2);

max_div = (num1 > num2) ? num1 : num2;

while (flag)

if (max_div % num1 == 0 && max_div % num2 == 0)

printf( " The LCM of %d and %d is %d. ", num1, num2, max_div);

break;

++max_div;
}

//Count no.of digits in a string

#include <stdio.h>
int main()
{
char s[1000];
int c=0,j;
printf("Enter string: ");
gets(s);
for(j = 0; s[j] != '\0'; j++)
{
if(s[j]=='0' || s[j]=='1'|| s[j]=='2'||s[j]=='3'|| s[j]=='4'|| s[j]=='5'||s[j]=='6'|| s[j]=='7'|| s[j]=='8'|| s[j]=='9')
c++;
}
printf("\nNumber of digits in string = %d", c);
return 0;
}

//Power of a Number

#include <stdio.h>

int main()

int base, exp, result = 1;

printf("Enter a base number: ");

scanf("%d", &base);

printf("Enter an exponent: ");

scanf("%d", &exp);

while (exp != 0)

result *= base;

--exp;

printf("Answer = %d", result);

return 0;

// Fibonacci Series

#include<stdio.h>

int main()

int n1=0,n2=1,n3,i,n;

printf("Enter the number of elements:");

scanf("%d",&n);

printf("\n%d %d",n1,n2);

for(i=2;i<n;++i)

n3=n1+n2;

printf(" %d",n3);
n1=n2;

n2=n3;

return 0;

//Print Factors of a Number

#include <stdio.h>

int main()

int num, i;

printf("Enter a positive integer: ");

scanf("%d", &num);

printf("Factors of %d are: ", num);

for (i = 1; i <= num; ++i)

if (num % i == 0)

printf("%d ", i);

return 0;

//Print n prime numbers

#include<stdio.h>

void main()

int i,j,n;

printf("Enter the number till which you want prime numbers\n");

scanf("%d",&n);

printf("Prime numbers are:-\n");

for(i=2;i<=n;i++)

int c=0;

for(j=1;j<=i;j++)

if(i%j==0)

c++;

}
if(c==2)

printf("%d ",i);

// Area of a circle and Circumference of a Circle

#include<stdio.h>

main()

int r;

float C,A;

printf("Enter the radius of circle:");

scanf("%d",&r);

C= 2*3.14*r;

A=3.14*r*r;

printf("Circumference of a circle with given radius %d is %f\n",r,C);

printf("Area of a circle with given radius %d is %f\n",r,A);

//Area Of Triangle

#include<stdio.h>

main()

int b,h;

float area;

printf("Enter breadth:\n");

scanf("%d",&b);

printf("Enter Height:\n");

scanf("%d",&h);

area=0.5*b*h;

printf("Area of Triangle: %f\n",area);

// Roots of Quadratic Equation

#include<stdio.h>

#include<math.h>

main()

int a,b,c;

float x,y;

printf("Give Values for a,b,c in Qudratic Equation:\n");


scanf("%d %d %d",&a,&b,&c);

x= (-b+sqrt(b*b-4*a*c))/4*a;

y= (-b-sqrt(b*b-4*a*c))/4*a;

printf("Roots of Quadratic Equation are : %f , %f",x,y);

//Check Perfect Square

#include<stdio.h>

int main()

int i, n;

printf("Enter a number: ");

scanf("%d", &n);

for(i = 0; i <= n; i++)

if(n == i*i)

printf("%d is a perfect square",n);

return 0;

printf("%d is not a perfect square",n);

return 0;

// 111

222

333

#include<stdio.h>

main()

int i,j;

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

printf("%d\t",i);

printf("\n");

}
// 123

123

123

#include<stdio.h>

main()

int i,j;

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

printf("%d\t",j);

printf("\n");

//1

22

333

#include<stdio.h>

main()

int i,j;

for(i=1;i<=3;i++)

for(j=1;j<=i;j++)

printf("%d\t",i);

printf("\n");

}
//1

12

123

1234

#include<stdio.h>

main()

int i,j;

for(i=1;i<=4;i++)

for(j=1;j<=i;j++)

printf("%d\t",j);

printf("\n");

}
// $

$$

$$$

#include<stdio.h>

main()

int i,j;

for(i=1;i<=3;i++)

for(j=1;j<=i;j++)

printf("$");

printf("\n");

}
// $

$ $

$$ $

#include<stdio.h>

main()

int i,j,k;

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

if(i==j)

printf("$");

else

printf(" ");

printf("\n");

// $

#include<stdio.h>

main()

int i,j;

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

if(i==j)

printf(" $ ");

printf(" ");

}
printf("\n");

// $

$ $

#include<stdio.h>

main()

int i,j,k;

for(i=1;i<=3;i++)

for(j=1;j<=3;j++)

if((i-j)==1 || (j-i)==1)

printf("$");

else

printf(" ");

printf("\n");

}
Arrays:

An array is a data structure containing loop data values which have the same type.

These values are known as elements. It can be individuals sections by their position within the array.

An array is a variable which is capable of holed by many values where as that are older variables can hold a single value at
a time.

An array is a data structure in c that can store a fixed size and sequential collection of elements of same data type.

For example if u want to store 10 members then instead of defining 10 variables its easy to define an array of 10
length.

But array can store multiple values in single variables.

In array we have two types:

One dimensional arrays

 Multi dimensional arrays

Declaration of an array:

Datatype array name [array size];

Ex: int a[10];

One dimensional arrays:

This is a simple kind of array as just One dimensional array. The elements are One dimensional array of continuously
arranged one after another in a single row and columns.

#include<stdio.h>

main()

int sai[5]={10,20,30,40};

printf("sai[0]=%d \n",sai[0]);

printf("sai[1]=%d \n",sai[1]);

printf("sai[2]=%d \n",sai[2]);

printf("sai[3]=%d \n",sai[3]);

#include<stdio.h>

main()

int i,a[5];

printf("Enter the 5 elements \n");

for(i=0;i<5;i++)

scanf("%d",&a[i]);

printf("The entered details are \n");

for(i=0;i<5;i++)

printf("%d \n",a[i]);
}

#include<stdio.h>

main()

int i,a[5]={1,2,3,4,5};

for(i=0;i<5;i++)

printf("a[%d]=%d \n",i,a[i]);

#include<stdio.h>

main()

int i,a[10],b[10],j=0;

printf("Enter array elements\n");

for(i=0;i<10;i++)

scanf("%d",&a[i]);

if(a[i]%2==0)

b[j] = a[i];

j++;

printf("Display even numbers\n");

for(i=0;i<j;i++)

printf("%3d",b[i]);

Multi-dimensional array:

When the data must be stored in the form of a matrix. We use the two dimensional array.

Declaration of two dimensional array:

Data type array name[row size][column size];

Ex: int a[2][2];

Initialization of two dimensional array:


int a[2][2];

a[0][0]=10;

a[0][1]=20;

a[1][0]=30;

a[1][1]=40;

An above declaration in two dimensional array consisting of two rows and two columns. So that total no of
elements are four.

#include<stdio.h>

main()

int i,j,e[2][2]={11,12,13,14};

for(i=0;i<2;i++)

for(j=0;j<2;j++)

printf("e[%d][%d]=%d \t",i,j,e[i][j]);

printf("\n");

#include<stdio.h>

#include<conio.h>

main()

int a[2][2],b[2][2],c[2][2],i,j;

printf("Enter array A elements\n");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

scanf("%d",&a[i][j]);

printf("\nEnter Array B elements\n");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

scanf("%d",&b[i][j]);

}
}

for(i=0;i<2;i++)

for(j=0;j<2;j++)

c[i][j]=a[i][j]+b[i][j];

printf("\nThe addition of two by two matrix is\n");

for(i=0;i<2;i++)

for(j=0;j<2;j++)

printf("%3d",c[i][j]);

printf("\n");

Extra Programs On Arrays:

// Initialize and Display array of 10 elements

#include <stdio.h>

void main ()

int num[20];

int i, j, a, n;

printf("enter number of elements in an array\n");

scanf("%d", &n);

printf("Enter the elements\n");

for (i = 0; i < n; ++i)

scanf("%d", &num[i]);

printf("Elements of array are:\n");

for (i = 0; i < n; ++i)

printf("%d ", num[i]);

// Array Sorting

#include <stdio.h>

void main ()
{

int num[20];

int i, j, a, n;

printf("enter number of elements in an array\n");

scanf("%d", &n);

printf("Enter the elements\n");

for (i = 0; i < n; ++i)

scanf("%d", &num[i]);

for (i = 0; i < n; ++i)

for (j = i + 1; j < n; ++j)

if (num[i] > num[j])

a = num[i];

num[i] = num[j];

num[j] = a;

printf("The numbers in ascending order is:\n");

for (i = 0; i < n; ++i)

printf("%d\n", num[i]);

//Print first two largest numbers in array

#include <stdio.h>

void main ()

int num[20];

int i, j, a, n;

printf("enter number of elements in an array\n");

scanf("%d", &n);

printf("Enter the elements\n");

for (i = 0; i < n; ++i)

scanf("%d", &num[i]);

for (i = 0; i < n; ++i)

for (j = i + 1; j < n; ++j)


{

if (num[i] > num[j])

a = num[i];

num[i] = num[j];

num[j] = a;

printf("The first largest number is: %d \n",num[n-1]);

printf("The second largest number is: %d \n",num[n-2]);

//Display 4 rows and 4 columns in 2D array

#include<stdio.h>

main()

int i,j,m,n,a[10][10];

printf("Enter no.of rows:");

scanf("%d",&m);

printf("Enter no.of columns:");

scanf("%d",&n);

printf("Enter elements:");

for(i=1;i<=m;i++)

for(j=1;j<=n;j++)

scanf("%d",&a[i][j]);

for(i=1;i<=m;i++)

for(j=1;j<=n;j++)

printf("%d\t",a[i][j]);

printf("\n");

//Matrix multiplication

#include<stdio.h>
#include<stdlib.h>

int main(){

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;

printf("enter the number of row=");

scanf("%d",&r);

printf("enter the number of column=");

scanf("%d",&c);

printf("enter the first matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&a[i][j]);

printf("enter the second matrix element=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

scanf("%d",&b[i][j]);

printf("multiply of the matrix=\n");

for(i=0;i<r;i++)

for(j=0;j<c;j++)

mul[i][j]=0;

for(k=0;k<c;k++)

mul[i][j]+=a[i][k]*b[k][j];

for(i=0;i<r;i++)

for(j=0;j<c;j++)

printf("%d\t",mul[i][j]);
}

printf("\n");

return 0;

//Matrix Addition

#include <stdio.h>

main()

int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter the number of rows (between 1 and 100): ");

scanf("%d", &r);

printf("Enter the number of columns (between 1 and 100): ");

scanf("%d", &c);

printf("\nEnter elements of 1st matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j)

printf("Enter element a%d%d: ", i + 1, j + 1);

scanf("%d", &a[i][j]);

printf("Enter elements of 2nd matrix:\n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j)

printf("Enter element b%d%d: ", i + 1, j + 1);

scanf("%d", &b[i][j]);

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j)

sum[i][j] = a[i][j] + b[i][j];

printf("\nSum of two matrices: \n");

for (i = 0; i < r; ++i)

for (j = 0; j < c; ++j)

printf("%d ", sum[i][j]);

if (j == c - 1)

{
printf("\n\n");

//Reverse elements in Array

#include<stdio.h>

int main()

int n,arr[n],i;

printf("Enter no.of elements:\n");

scanf("%d",&n);

printf("Enter elements of an array:\n");

for(i = 0; i < n; i++)

scanf("%d",&arr[i]);

printf("Reversed array is:\n");

for(i = n-1; i >= 0; i--)

printf("%d\n",arr[i]);

return 0;

//Sum of n numbers using Array

#include<stdio.h>

int main()

int sum=0,n,arr[n],i;

printf("Enter no.of elements:\n");

scanf("%d",&n);

printf("Enter elements of an array:\n");

for(i = 0; i < n; i++)

scanf("%d",&arr[i]);

sum += arr[i];

printf("Sum of elements in array: %d\n",sum);

return 0;

// Remove duplicate elements in an array


#include<stdio.h>

#include<stdlib.h>

int main()

int a[50],i,j,k, count = 0, dup[50],n;

printf("Enter size of the array\n");

scanf("%d",&n);

printf("Enter Elements of the array:\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("Entered element are: \n");

for(i=0;i<n;i++)

printf("%d ",a[i]);

for(i=0;i<n;i++)

for(j = i+1; j < n; j++)

if(a[i] == a[j])

for(k = j; k <n; k++)

a[k] = a[k+1];

j--;

n--;

printf("\nAfter deleting the duplicate element the Array is:\n");

for(i=0;i<n;i++)

printf("%d ",a[i]);

}
Strings:

Strings are nothing but array of character and entered with null characters[‘\0’].

This null character indicate the end of the string.

String are always enclosed by (“---”) double equations were as character is enclosed by string single quotation (‘----‘).

Declaration:

Data type stringname [string size];

Ex: char s[10];

Initialization of string:

char s[10]={‘H’,’E’,’L’,’L’,’O’};

char s[6]=”hello”;

char s[]=”hai”;

Difference between above Declaration when we declare char is s[10] 10 bytes memory space is allocated for holding the
string.

When we declare as s[] memory space will be allocated as per the required during for the program.

#include<stdio.h>

main()

char s1[10]=”hello”;

printf(“s1=%s \n”,s1);

String functions:

strcat

 strncat

strcpy

 strncpy

strlen

strupr

strlwr

strrev

strcmp

strset

String concatenation:

In this function concatenation the position of one string at the end of the other string.

Syntax:

strcat(s1,s2);

#include<stdio.h>

#include<string.h>

main()

char s1[10]="hello ";


char s2[10]="every one";

strcat(s1,s2);

printf("s1=%s \n",s1);

String unconcatenation:

It is also same as String concatenation but it will declare the length of the s1 or s2. So it will prints the length position.

Syntax:

strncat(s1,s2,5);

#include<stdio.h>

#include<string.h>

main()

char s1[10]="hello";

char s2[10]="every one";

strncat(s1,s2,5);

printf("s1=%s \n",s1);

String copy function:

It copies the s1 content to the s2 content. In this s1 content has 30 bytes of memory and s2 has declared 20 bytes of
memory only means. It will only print 20 characters.

Syntax:

strcpy(s1,s2);

#include<stdio.h>

#include<string.h>

main()

char s1[10]="hello";

char s2[10]="lucky";

strcpy(s1,s2);

printf("s1=%s \n",s1);

String strncpy function:

In this it will be copy the lengthened position which will be mentioned in the function.

Syntax:

strncpy(s2,s3,3);

#include<stdio.h>

#include<string.h>

main()
{

char s1[10]="hello";

char s2[10];

strncpy(s2,s1,3);

printf("s2=%s \n",s2);

String length:

It will show the length of your given string

Syntax:

len=strlen(s);

#include<stdio.h>

#include<string.h>

main()

char s1[10]="hello";

char s2[10]="hello";

int len;

len=strlen(s1);

printf("len=%d \n",len);

String reverse:

It reverses the word which is given in a string.

Syntax:

strrev(s);

#include<stdio.h>

#include<string.h>

main()

char s1[10]="apple";

printf("s1=%s \n",strrev(s1));

String lower:

In this string lower it will print the higher level language to the lower level language.

Syntax:

strlwr(s);
#include<stdio.h>

#include<string.h>

main()

char s1[10]="HELLO";

printf("s1=%s \n",strlwr(s1));

String upper:

In this function it will change lower case to upper case.

Syntax:

strupr(s)

#include<stdio.h>

#include<string.h>

main()

char s1[10]="hello";

printf("s1=%s \n",strupr(s1));

String compare:

In this function s1 and s2 are same It will print 0. If s1 is less than s2 it will print -1. If s1 is greater than s2 it will print 1.

Syntax:

strcmp(s)

#include<stdio.h>

#include<string.h>

main()

char s1[10]="apple";

char s2[10]="app";

int x,y,z;

x=strcmp(s1,s2);

y=strcmp(s2,"app");

z=strcmp(s1,"apples");

printf("x=%d \n",x);

printf("y=%d \n",y);

printf("z=%d \n",z);

String set:
In this program of string “ hello” is set to ‘&’ using string set function and output will be display like ‘&&&&&’ .

Syntax:

strset(s)

#include<stdio.h>

#include<string.h>

main()

char s1[7]="orange";

strset(s1,'&');

printf("s1=%s \n",s1);

Extra Programs on Strings:

//Frequency of Character in a String

#include<stdio.h>

#include<string.h>

main()

int c=0;

char s[10]="Meghana",Ch,i;

//printf("Enter a String: ");

//scanf("%s",&s);

// If u give like this second character Ch will take enter as argument

// and doesnot ask character to calculate Frequency

printf("Enter a character to find frequency: ");

scanf("%c",&Ch);

for (i=0;i<strlen(s);i++)

if(s[i]==Ch)

c++;

printf("Frequency of character is %d",c);

//Calculate no. of Vowels, Consonants, Digits and White Spaces in String

#include <stdio.h>

int main()

char line[150];

int vowels, consonant, digit, space,i;

vowels = consonant = digit = space = 0;


printf("Enter a line of string: ");

fgets(line, sizeof(line), stdin);

for (i = 0; line[i] != '\0'; ++i)

if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||

line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||

line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||

line[i] == 'U')

++vowels;

else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z'))

++consonant;

else if (line[i] >= '0' && line[i] <= '9')

++digit;

else if (line[i] == ' ')

++space;

printf("Vowels: %d", vowels);

printf("\nConsonants: %d", consonant);

printf("\nDigits: %d", digit);

printf("\nWhite spaces: %d", space);

return 0;

//Reverse a string using Recursion

#include <stdio.h>

int main()

char x[1000], r[1000],s;

printf("Input a string\n");

gets(x);

reverse(x);

return 0;

}
int reverse(char *s)

int begin, end, count = 0;

char r[1000];

while (s[count] != '\0')

count++;

end = count - 1;

for (begin = 0; begin < count; begin++)

r[begin] = s[end];

end--;

r[begin] = '\0';

printf("%s\n", r);

return 0;

// Remove all Characters in a String except Vowels

#include <stdio.h>

#include<string.h>

int main()

int index, str_length;

char str[50];

printf("\nEnter string: ");

scanf("%s", str);

str_length = strlen(str);

for(index = 0; index < str_length; index++)

if(str[index] == 'a' || str[index] == 'e' ||

str[index] == 'i' || str[index] == 'o' ||

str[index] == 'u' || str[index] == 'A' ||

str[index] == 'E' || str[index] == 'I' ||

str[index] == 'O' || str[index] == 'U')

printf("%c",str[index]);

return 0;

//Count No.of Vowels in a String


#include <stdio.h>

#include<string.h>

int main()

int index, str_length,count=0;

char str[50];

printf("\nEnter string: ");

scanf("%s", str);

str_length = strlen(str);

for(index = 0; index < str_length; index++)

if(str[index] == 'a' || str[index] == 'e' ||

str[index] == 'i' || str[index] == 'o' ||

str[index] == 'u' || str[index] == 'A' ||

str[index] == 'E' || str[index] == 'I' ||

str[index] == 'O' || str[index] == 'U')

count++;

printf("%d",count);

return 0;

//Sort elements in Lexographic order

#include <stdio.h>

#include <string.h>

int main()

int i,j;

char str[5][50], temp[50];

printf("Enter 5 words: ");

for (i = 0; i < 5; ++i)

fgets(str[i], sizeof(str[i]), stdin);

for (i = 0; i < 5; ++i)

for (j = i + 1; j < 5; ++j)

if (strcmp(str[i], str[j]) > 0)


{

strcpy(temp, str[i]);

strcpy(str[i], str[j]);

strcpy(str[j], temp);

printf("\nIn the lexicographical order: \n");

for (i = 0; i < 5; ++i)

fputs(str[i], stdout);

return 0;

Functions:

A function is a self contained block are a program of one or more statements. That perform a special task when that
is called as function.

In this function we have 2 types:

In built function

User define function

Built-in function:

In this function is also called as library function.These function can not be changed by a user.

Example: printf();, scnaf();,main()……………

User defined function:

In this function user can give the unique name to a function and to create a function by using functional elements.

Example:variables , constants………

Uses of function:

If we want to perform a task continuously then it is not necessary to rewrite the program again and again. If we
shift the particular statements in a user define function. So it can be used many no of times.

Elements of user define function:

They are 3 types:

Declaration function.

Called function.

Define function.

Declaration function:

They are 4 types:

Function type

Function name

Parameter list

Semicolon(;)
Function type:

They are 2 types:

Return type

Non return type

Return type:

int, float, char, double in this it only return one value at a time is known as return type.

Non return type:

void is a non return type.It does not return a any value.

Function name:

In this function name user can give a name to the function.

Ex: int square();

Parameter list:

It means how many input user giving are receiving is known as parameter list.

This parameter list we also called as arguments.

They are 2 types of parameters:

Actual parameters

Formal parameters

Actual parameter list:

The arguments of calling function are known as Actual arguments.

Example : actual(10,20);

Formal parameter list:

The arguments are called function is known as formal parameter list but it copies the actual arguments values is
also known as formal arguments.

Example: formal(int a,int b)

Semicolon:

The terminating is used to terminate the function.

Function declaration:

int hello();

int hello(int a,int b);

void hello();

void hello(int a); semicolon

parameter list and arguments

function type function name

Called function:

In function we have two types:

call function

calling function

Call function:

This function which is calls the calling function is known as called function.

Example:hello()
Calling function:

This function receives the called function is known as calling function.

Example: hello();

Functions are 4 types

function with no arguments and no return types

 function with arguments and no return types

function without arguments function with return types

function with arguments with return types

Function with no arguments and no return types:

There are the function in which no parameters are passed from calling function to the called function. In values are
return from called function to the calling function.

#include<stdio.h>

#include<string.h>

main()

clzname();

function();

rollno();

avg();

void clzname()

printf("the clz name is fdahs: \n");

void function()

char name[10]="abdul";

printf("name=%s \n",name);

void rollno()

int rollno=12345;

printf("roll no=%d \n",rollno);

void avg()

float avg=000;

printf("avg=%f \n",avg);

Function with arguments without return type:


There are the function in which arguments are passed from calling function to called function but no values are
return from called function to calling function.

#include<stdio.h>

void sai(int a,int b)

int c;

c=a+b;

printf("c=%d \n",c);

main()

sai(10,20);

sai(10,30);

Function without arguments and with return types:

In this function category no arguments are passing from calling function to called function but values are a return
from called function to the calling function.

#include<stdio.h>

int r()

int a,b;

printf("enter the two values \n");

scanf("%d %d",&a,&b);

return(a+b);

main()

int c;

c=r();

printf("c=%d \n",c);

Function with arguments with return types:

These are the function in which parameter are passed from calling function to the called function and values are
return from function to be calling function.

#include<stdio.h>

int square(int i)

return i*i;
}

main()

int a;

printf("Enter any number");

scanf("%d",&a);

printf("%d",square(a));

#include<stdio.h>

int getValue()

int a;

printf("Enter any value\t");

scanf("%d",&a);

return a;

int square(int n)

return n * n;

int cube(int m)

return m *square(m);

main()

printf("The square of given number is %d\n",square(getValue()));

printf("The cube of given number is %d",cube(getValue()));

Function Calling:

Calling a function can be done in 2 ways. They are

Call By Value

Call By Reference

Call By Value:

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made
to the parameter inside the function have no effect on the argument. In Call By Value method, the value of the actual
parameters is copied into the formal parameters.

We cannot modify the value of actual parameter by the formal parameter.


Different memory location is allocated for actual and formal parameters

Here , the parameter which is used in the function call is called actual parameter and the parameter which is used in the
function definition is called formal parameter.

//Write a program referring Call By Value

#include<stdio.h>

void change(int num)

printf("Before adding value inside function num=%d \n",num);

num=num+100;

printf("After adding value inside function num=%d \n", num);

int main()

int x=100;

printf("Before function call x=%d \n", x);

change(x);

printf("After function call x=%d \n", x);

return 0;

//Write a program for Swaping of two numbers using Call By Value

#include <stdio.h>

void swap(int , int); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

swap(a,b);

printf("After swapping values in main a = %d, b = %d\n",a,b);

void swap (int a, int b)

int temp;

temp = a;

a=b;

b=temp;

printf("After swapping values in function a = %d, b = %d\n",a,b);

Call By Reference:
This method copies the address of an argument into the formal parameter.

Inside the function, the address is used to access the actual argument used in the call. This means that changes made to
the parameter affect the argument.

In Call By Reference, The address of the variable is passed into the function call as actual parameter.

The value of the actual parameters can be modified by changing the formal parameters since the address of the actual
parameters is passed.

In Call By Reference, the memory location is similar for both actual parameters and formal parameters. All the operations
in the function are performed on the value stored at the address of the actual parameters, and the modified value
gets stored at same address.

// Write a program referring Call By Reference

#include<stdio.h>

void change(int *num)

printf("Before adding value inside function num=%d \n",*num);

(*num) += 100;

printf("After adding value inside function num=%d \n", *num);

int main()

int x=100;

printf("Before function call x=%d \n", x);

change(&x);

printf("After function call x=%d \n", x);

return 0;

//Write a program for Swaping of two numbers using Call By Reference

#include <stdio.h>

void swap(int *, int *); //prototype of the function

int main()

int a = 10;

int b = 20;

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

swap(&a,&b);

printf("After swapping values in main a = %d, b = %d\n",a,b);

void swap (int *a, int *b)

int temp;

temp = *a;

*a=*b;
*b=temp;

printf("After swapping values in function a = %d, b = %d\n",*a,*b);

Extra Programs On Functions:

//Greatest of Two Numbers using Functions

#include<stdio.h>

int findLargest(int a, int b)

if (a > b)

return a;

else

return b;

int main()

int a, b, large;

printf("Enter two numbers:");

scanf("%d%d", &a, &b);

large = findLargest(a, b);

printf("Largest is:%d", large);

return 0;

//Prime number or Not using Functions

#include<stdio.h>

main()

int n, result;

printf("Enter an integer to check whether it is prime or not.\n");

scanf("%d",&n);

result = check_prime(n);

if ( result == 1 )

printf("%d is prime.\n", n);

else

printf("%d is not prime.\n", n);

return 0;

}
int check_prime(int a)

int c;

for ( c = 2 ; c <= a - 1 ; c++ )

if ( a%c == 0 )

return 0;

return 1;

// Palindrome or Not Using Functions

#include<stdio.h>

int Palindrome(int n)

int temp, r, rev=0;

temp = n;

while( n!=0 )

r = n % 10;

rev = rev*10 + r;

n /= 10;

if ( rev == temp ) return 0;

else return 1;

int main()

int n;

printf("Enter the number: ");

scanf("%d", &n);

if(Palindrome(n) == 0)

printf("%d is a palindrome number.\n",n);

else

printf("%d is not a palindrome number.\n",n);

return 0;

//ArmStrong or Not

#include<stdio.h>

int Armstrong(int n)

{
int l = 0;

int p = 0;

int sum = 0;

int x = n;

while(x!=0)

l = x % 10;

p = l*l*l;

sum += p;

x /= 10;

if(sum == n)

return 0;

else

return 1;

int main()

int n;

printf("Enter number: ");

scanf("%d",&n);

if(Armstrong(n) == 0)

printf("%d is an Armstrong number.\n", n);

else

printf("%d is not an Armstrong number.", n);

return 0;

//Call Functions Add(), Subtract(), Multiply(), Division() and Do Calculations

#include<stdio.h>

main()

int ch,a,b,c;

printf("Enter two Numbers:\n");

scanf("%d %d",&a,&b);

printf("Menu:\n 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n");

printf("Enter a option to do calculation:\n");

scanf("%d",&ch);

switch(ch)

case 1: c=a+b;
printf("%d + %d = %d",a,b,c);

break;

case 2: if (a>b)

c=a-b;

printf("%d + %d = %d",a,b,c);

else

c=b-a;

printf("%d - %d = %d",b,a,c);

break;

case 3: c=a*b;

printf("%d * %d = %d",a,b,c);

break;

case 4: c=a/b;

printf("%d / %d = %d",a,b,c);

break;

default:printf("Please enter right option");

break;

//Swaping of two numbers using Swap Function

#include<stdio.h>

void swap(int *,int *);

int main()

int n1,n2;

printf("\n\n Function : swap two numbers using function :\n");

printf("------------------------------------------------\n");

printf("Input 1st number : ");

scanf("%d",&n1);

printf("Input 2nd number : ");

scanf("%d",&n2);

printf("Before swapping: n1 = %d, n2 = %d ",n1,n2);

swap(&n1,&n2);

printf("\nAfter swapping: n1 = %d, n2 = %d \n\n",n1,n2);

return 0;

}
void swap(int *p,int *q)

int tmp;

tmp = *p;

*p=*q;

*q=tmp;

//Factorial without using Functions

#include<stdio.h>

int main()

int i,fact=1,number;

printf("Enter a number: ");

scanf("%d",&number);

for(i=1;i<=number;i++)

fact=fact*i;

printf("Factorial of %d is: %d",number,fact);

return 0;

//Factorial with using functions

#include<stdio.h>

int factorial(int n)

if (n == 0)

return 1;

else

return(n * factorial(n-1));

void main()

int number;

long fact;

printf("Enter a number: ");

scanf("%d", &number);

fact = factorial(number);

printf("Factorial of %d is %ld\n", number, fact);

return 0;

}
//LCM and GCD of two numbers using Functions

#include <stdio.h>

int gcd(int x, int y);

int main()

int num1, num2, GCD, lcm;

printf("Enter two integer Values:\n");

scanf("%d %d", &num1, &num2);

GCD = gcd(num1, num2);

printf("GCD: %d",GCD);

printf("\nLCM: %d", (num1 * num2) / GCD);

return 0;

int gcd(int x, int y)

if (y == 0)

return x;

else

return gcd(y, x % y);

//Array Sorting using sort() function

#include <stdio.h>

int sort(int *a,int n)

int i,j,temp;

for(i=0; i<n-1; i++)

for(j=0; j<n-i-1; j++)

if(a[j]>a[j+1])

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}
}

int main()

int a[100],i,n,key;

printf("Enter size of the array : ");

scanf("%d", &n);

printf("Enter elements in array : ");

for(i=0; i<n; i++)

scanf("%d",&a[i]);

sort(a,n);

printf("Elements after Sort\n");

for(i=0; i<n; i++)

printf("%d ",a[i]);

// Calculate n
pr and n
cr

#include <stdio.h>

long factorial(int);

long find_ncr(int, int);

long find_npr(int, int);

int main()

int n, r;

long ncr, npr;

printf("Enter the value of n and r\n");

scanf("%d%d",&n,&r);

ncr = find_ncr(n, r);

npr = find_npr(n, r);

printf("%dC%d = %ld\n", n, r, ncr);

printf("%dP%d = %ld\n", n, r, npr);

return 0;

long find_ncr(int n, int r)

long result;

result = factorial(n)/(factorial(r)*factorial(n-r));
return result;

long find_npr(int n, int r)

long result;

result = factorial(n)/factorial(n-r);

return result;

long factorial(int n)

int c;

long result = 1;

for (c = 1; c <= n; c++)

result = result*c;

return result;

Storage classes:

A function can access a variable when it declared in a specific block other function(outside) cannot be accessed.
The space of a variable depends upon it’s storage classes.They are 4 types:

Auto (Automatic)

External variable

Static variable

Register variable

Automatic variable (auto):

The space of this variable is within the function only it is quaintly to local variable all local variables are auto
variable by default.

#include<stdio.h>

void sai()

auto float a=4.2;

printf("%f \n",a);

a++;

main()

sai();

sai();

}
Static variable:

It retains the value of the variable between different function calls.

When a variable is define static its garbage value is removed and it is initialized to null values.

The content store in this variable remains content throughout the program.

A static variable is initialized only one it can’t be reinitialized.

#include<stdio.h>

void fun1()

static int a=4;

printf("%d \n",a);

a--;

main()

fun1();

fun1();

fun1();

External variable:

The scope of the variable thought out the program it is the equitant to globalvariable definition for external variable
may be any were the program.

#include<stdio.h>

main()

extern int pravi;

printf("the value of pravi is %d \n",pravi);

int pravi=20;

Register variable:

It is also local variable but stored in the register memory were as auto variable are stored in the main memory.

Register variable will be accessed very faster the normal variable. Since they are stored in register memory rather
then main memory. But only limited variable can be used as a register memory since it can used register size is
very low.

#include<stdio.h>

int main()

int num1,num2;

register int sum;

printf("\nEnter the Number 1 : ");


scanf("%d",&num1);

printf("\nEnter the Number 2 : ");

scanf("%d",&num2);

sum = num1 + num2;

printf("\nSum of Numbers : %d",sum);

return(0);

Pointers:

A pointer is a variable that stores the address of another variable. C pointer is used to allocate memory dynamically
that is run time.

The pointer variable might be belong to the data type. Such as int, float, char, double.

About the pointer:

Normal variable store the value were as pointer variable store the address of the variable.

The content of the ‘C’ pointer always be a whole number that is address.

Always c pointer is initialized to null that is int *p= null.

The null pointer is zero ‘0’.

Reference operator(&) or addresser operator:

If (isan) name is the variable &name is the address of the variable.

Values of a operator:

Pointer variable are the special type of the variable that holds the memory address rather then the data that is a
variable that holds address value is called a pointer variable.

Addresses of values:

%u

%x

#include<stdio.h>

main()

int a=10,*p;

p=&a;

printf("a=%d \n",a);

printf("&a=%u \n",&a);

printf("p=%u \n",p);

printf("*p=%u \n",*p);

printf("&p=%p \n",&p);

Point of pointers:

We already know that a pointer points to a location in memory and thus used to store address of variables. So,
when we define a pointer to pointer. The first pointer is used to store the address of second pointer. That is why
they are also known as double pointers.

How to declare a pointer to pointer in C?


Declaring Pointer to Pointer is similar to declaring pointer in C. The difference is we have to place an additional ‘*’
before the name of pointer.
Syntax:

int *a,**b;

#include<stdio.h>

main()

int a=15,*p,**p1;

p=&a;

p1=&p;

printf("a=%d \n",a);

printf("&a=%u \n",&a);

printf("p=%u \n",p);

printf("*p=%u \n",*p);

printf("&p=%p \n",&p);

printf("p1=%x \n",p1);

printf("*p1=%p \n",*p1);

printf("**p1=%u \n",**p1);

printf("&p1=%p \n",&p1);

Array of pointer:

Arrays are closed related to the pointer in the c programming but the important difference between that is the a
pointer variable can take a address of then values were as array as a fixed value.

#include<stdio.h>

main()

int a[4]={10,20,30,40};

printf("a[0]=%d \n",*a);

printf("a[1]=%d \n",*(a+1));

printf("a[2]=%d \n",*(a+2));

printf("a[3]=%d \n",*(a+3));

Swapping of two numbers by using pointers:

#include<stdio.h>

int main()

int x,y,*a,*b,temp;

printf("Enter the value of x and y\n");

scanf("%d%d",&x,&y);

a= &x;
b= &y;

temp= *b;

*b = *a;

*a = temp;

printf("After Swapping\nx = %d\ny = %d\n",x,y);

return 0;

Pointer with function:

#include<stdio.h>

swap(int*, int *);

int main()

int n1,n2;

printf("Input 1st number :");

scanf("%d",&n1);

printf("Input 2nd number :");

scanf("%d",&n2);

printf("Before swapping : n1 = %d, n2 = %d",n1,n2);

swap(&n1,&n2);

printf("\nAfter swapping n1 = %d,n2 = %d \n\n",n1,n2);

swap(int *p, int *q)

int tmp;

tmp=*p;

*p=*q;

*q=tmp;

return 1;

Extra Programs on Pointers:

// Concatenate two Strings Using pointers

#include <stdio.h>

int main()

char aa[100], bb[100];

printf("Enter the first string:\n");

gets(aa);

printf("Enter the second string to be concatenated:\n ");

gets(bb);
char *a = aa;

char *b = bb;

while(*a)

a++;

while(*b)

*a = *b;

b++;

a++;

*a = '\0';

printf("The string after concatenation is:%s", aa);

return 0;

//Reverse a string using Pointer

#include <stdio.h>

#include <string.h>

void reverseString(char* str)

int l, I;

char *begin_ptr, *end_ptr, ch;

l = strlen(str);

begin_ptr = str;

end_ptr = str;

// Move the end_ptr to the last character

for (i = 0; i < l - 1; i++)

end_ptr++;

// Swap the char from start and end index using begin_ptr and end_ptr

for (i = 0; i < l / 2; i++)

ch = *end_ptr;

*end_ptr = *begin_ptr;

*begin_ptr = ch;

begin_ptr++;

end_ptr--;

int main()
{

char str[50];

printf("Enter a string:\n");

scanf("%s",str);

reverseString(str);

printf("Reverse of the string: %s\n", str);

return 0;

// Swaping using Pointers

#include <stdio.h>

void swap(int *x,int *y)

int t;

t = *x;

*x = *y;

*y = t;

int main()

int num1,num2;

printf("Enter value of num1: ");

scanf("%d",&num1);

printf("Enter value of num2: ");

scanf("%d",&num2);

printf("Before Swapping: num1 is: %d, num2 is: %d\n",num1,num2);

swap(&num1,&num2);

printf("After Swapping: num1 is: %d, num2 is: %d\n",num1,num2);

return 0;

//Pointer to a Function

#include <stdio.h>

int add(int,int);

int main()

int a,b;

int (*ip)(int,int);

int result;

printf("Enter the values of a and b : ");

scanf("%d %d",&a,&b);

ip=add;
result=(*ip)(a,b);

printf("Value after addition is : %d",result);

return 0;

int add(int a,int b)

int c=a+b;

return c;

Structure:

Structure is a collection of different data type which grouped together and each in a structure is called member.

Structure is a user define data type.

If you want access a structure member in c. Structure variable should be declared.

Many structure variable can be declaredfor some structure and memory with the allocated for each separately.

A structure is a collection of one or more variable of different data type grouped together under a single name.

Syntax:

struct structer_name

Datatype variable;

Datatype variable;
Datatype variable;

};

Declaration of structure:

Object creating for Structures struct student s1;

struct student

char name[20];

int roll_no;

float avg;

};

All the members of a structure are the related to the structure variable members are s1.name.

The dot(.) sign is used to access the structure member.

#include<stdio.h>

#include<string.h>

struct student

char name[20];

int rollno;

float avg;

};
main()

struct student a={"asdf",0521,92.3};

struct student s1={"hjkl",0522,95.3};

printf("name=%s \n rollno=%d \n avg=%f \n",a.name,a.rollno,a.avg);

printf("name=%s \n rollno=%d \n avg=%f \n",s1.name,s1.rollno,s1.avg);

Structure with pointer:

In c language pointer can also be applied to structure that is we can have pointers pointing to the structure in such
the same way we have pointer pointing to int, float, char, double……….., in such that pointer are known as
structure pointer. Structure elements can be accessed by structure variable and a dot operator are by using
structure in arrow operator is used.

#include<stdio.h>

#include<string.h>

struct student

char name[20];

int rollno;

float avg;

};

main()

struct student s={"sai",45,92.3};

struct student *p;

p=&s;

printf("name=%s \n rollno=%d \n avg=%f \n",s.name,s.rollno,s.avg);

printf("name=%s \n rollno=%d \n avg=%f \n",p->name,p->rollno,p->avg);

printf("name=%x \n rollno=%u \n avg=%x \n",&s,&s,&s);

Nested structure:

A structure itself having another structure is called nested structure.

#include<stdio.h>

#include<string.h>

struct address

char sn[10];

int hn;

};
struct student

char name[20];

int rollno;

struct address addr;

};

main()

struct student rama={"anu",1234,"Lucky",4567};

printf("%s \n %d \n %s \n %d \n",rama.name,rama.rollno,rama.addr.sn,rama.addr.hn);

Array of structure:

Array is a collection of similar data type grouping structure variable in to one array is a referred to as on array of
structure c permits us to declare of structure.

We know that structure is a collection of dissimilar data types. So, by using both array and structure we can add
more students details.

#include<stdio.h>

#include<string.h>

struct student

char name[10];

int rollno;

float avg;

};

main()

int i;

struct student st[3]={{"sai",150,95.8},{"apple",152,982.5},{"sree",454,865.8}};

for(i=0;i<3;i++)

printf("\n %s %d %f \n",st[i].name,st[i].rollno,st[i].avg);

#include <stdio.h>

int main()

struct student

int rollno;
char name[25];

int totalmark;

}stud[100];

int n,i;

printf("Enter total number of students\n\n");

scanf("%d",&n);

for(i=0;i<n;i++)

printf("Enter details of %d-th student\n",i+1);

printf("Name:\n");

scanf("%s",&stud[i].name);

printf("Roll number:\n");

scanf("%d",&stud[i].rollno);

printf("Total mark:\n");

scanf("%d",&stud[i].totalmark);

printf("STUDENTS DETAILS:\n");

for(i=0;i<n;i++)

printf("\nRoll number:%d\n",stud[i].rollno);

printf("Name:%s\n",stud[i].name);

printf("Totel mark:%d\n",stud[i].totalmark);

return 0;

Structure padding:

In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left) empty between memory
addresses which are allocated for other structure members while memory allocation. This concept is called
structure padding.

Unions:

A union is a special data type available in C that enables you to store different data types in the same memory location.
You can define a union with many members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multi-purpose.

Syntax:

union [union tag]

member definition;

member definition;

...

member definition;

} [one or more union variables];


#include <stdio.h>

union test {

int x, y;

};

int main()

union test t;

t.x = 2;

printf("After making x = 2:\n x = %d, y = %d\n\n",

t.x, t.y);

t.y = 10;

printf("After making y = 10:\n x = %d, y = %d\n\n",

t.x, t.y);

return 0;

How is the size of union decided by compiler?

Size of a union is taken according the size of largest member in union.

#include<stdio.h>

union Test1

int x;

int y;

};

union Test2

int x;

char y;

};

main()

union Test1 t1;

union Test2 t2;

printf("sizeof(test1) = %u, sizeof(test2) = %u ", sizeof(t1), sizeof(t2));

Pointers to unions

Like structures, we can have pointers to unions and can access members using the arrow operator (->). The
following example demonstrates the same.

#include <stdio.h>

union test {
int x;

char y;

};

int main()

union test p1;

p1.x = 65;

// p2 is a pointer to union p1

union test* p2 = &p1;

// Accessing union members using pointer

printf("%d %c", p2->x, p2->y);

return 0;

Files:

A file is a container in computer storage devices used for storing data

Why Files Are Needed?

When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program
terminates.

If you have to enter large number of data, it will take a lot of time to enter them all. However, if you have a file containing
all the data, you can easily access the contents of the file using a few commands in C

You can easily move your data from one computer to another without any changes.

Types Of Files:

Files are of two types

Text Files

Binary Files

Files Operations

Operations on files are done as follows

Creating a new file

Opening an existence file

Closing a File

Reading from and writing information to a file

Working with files:

When working with files, you need to declare a pointer of type file. This declaration is needed for communication between
the file and the program.

FILE *fptr;

Opening of Files:

This is used for creation and editing of a file

Opening a file is performed using the fopen() function defined in the stdio.h header file

Syntax:

ptr = fopen(“Filename”,”mode”);
File Opening Mode Meaning of Opening Mode Operation

r Open for reading

rb Open for reading in binary mode

w Open for writing

wb Open for writing in binary mode

a Open for appending

ab Open for appending in binary mode

r+ Open for reading and writing

rb + Open for reading and writing in binary mode

w Open for reading and writing

wb + Open for reading and writing in binary mode

a Open for reading and appending

ab + Open for reading and appending in binary mode

Closing of files:

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function

Syntax: fclose(fptr)

fptr is a file pointer associated with the file to be closed.

Reading/Writing to a text file

For reading and writing to a text file,we use the functions fprintf() and fscaf()

They are just file versions of printf() and scanf().


The only difference is that fprintf() and fscanf() expects a pointer to the structure file

//Program for writing text to a file

#include <stdio.h>

#include <stdlib.h>

int main()

int num;

FILE *fptr;

fptr = fopen("E:\\Program.txt","w");

if(fptr == NULL)

printf("Error!");

exit(1);

printf("Enter num: ");

scanf("%d",&num);

fprintf(fptr,"%d",num);

fclose(fptr);

return 0;

//Write a program to read from file

#include <stdio.h>

#include <stdlib.h>

int main()

int num;

FILE *fptr;

if ((fptr = fopen("E:\\Program.txt","r")) == NULL)

printf("Error! opening file");

exit(1);

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);

fclose(fptr);

return 0;

//Write a program to append some text for existing file


#include <stdio.h>

int main()

FILE *fp;

char ch;

char *filename = "file_append.txt";

char *content = " are learning C programming.";

fp = fopen("E:\\Program.txt", "r");

printf("\nOld Content is ");

while ((ch = fgetc(fp) )!= EOF)

printf ("%c", ch);

fclose(fp);

fp = fopen("E:\\Program.txt", "a");

fprintf(fp, "%s\n", content);

fclose(fp);

fp = fopen("E:\\Program.txt", "r");

printf("New Content is \n");

while ((ch = fgetc(fp) )!= EOF)

printf ("%c", ch);

fclose(fp);

return 0;

You might also like