0% found this document useful (0 votes)
24 views46 pages

Computer Original Project

The document provides an overview of functions in C programming, detailing their types, structure, and advantages. It explains built-in and user-defined functions, along with function declaration, definition, and calling methods. Additionally, it covers parameters, best practices, recursion, and includes several example programs demonstrating various functionalities.

Uploaded by

anjusedhain7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views46 pages

Computer Original Project

The document provides an overview of functions in C programming, detailing their types, structure, and advantages. It explains built-in and user-defined functions, along with function declaration, definition, and calling methods. Additionally, it covers parameters, best practices, recursion, and includes several example programs demonstrating various functionalities.

Uploaded by

anjusedhain7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction to function:

Functions are a core component of the C programming language, enabling code reusability, better organization, and
modularity. A function is a block of code designed to perform a specific task. Using functions helps reduce
redundancy and makes the code easier to debug, maintain, and scale.

Types of Functions in C

Built-in Functions:
Predefined in libraries (eg, printf() from stdio.h).
Provide common functionality like input/output, mathematical operations, etc.

User-defined Functions:
Created by the programmer to perform specific tasks.
They are essential for modular programming.

Structure of a Function:
A typical function in C has the following structure:

return type function name(parameters) (


// Function body
Return value; // Optional, depends on return type

1. Return Type: Specifies the data type of the value the function returns. If no value is returned, the return typo is
void.
2. Function Name: A unique identifier for the function.
3. Parameters: Parameters: Variables passed into the function to provide input.
4. Function Body: Contains the code that defines what the function does.
5. Return Statement: Ends the function and optionally returns a value to the caller.

Function Declaration, Definition, and Call

Function Declaration:
Also called the "function prototype."
Informs the compiler about the function's name, return type, and parameters.
Example:
int add (int a, int b);

Function Definition:
The actual implementation of the function.
Example:
int add (int a, int b) {
return a + b;
}

Function Call:
Executes the function.
Example:
int result add (5, 3);
Advantages of Functions:

Code Reusability: Write once and reuse multiple times.


Modularity: Break down a program into smaller, manageable parts
Improved Readability: Makes the program more organized and easier to understand.
Easier Debugging: Problems can be isolated within specific functions.
Scalability: Simplifies adding new features.

Types of Parameters:

1. Pass by Value:
A copy of the actual value is passed to the function.
modifications in the function do not affect the original value.
Example:
void display (int num) (
num10; // Modifies only the local copy

2. Pass by Reference:
The address variable is passed, allowing the function to modify the original value.
Achieved using pointers in C.
Example:
void update Value (int *num) (
*num 10; // Modifies the original value

Best Practices
Use descriptive names for functions to improve code readability.
Keep functions focused on a single task.
Limit the use of global variables to avoid unintended side effects.
Document the purpose and parameters of the function.

Conclusion:
Functions are a fundamental concept in C programming that improve code organization and efficiency. By utilizing
built-in and user-defined functions effectively, developers can write more structured and maintainable programs.
Understanding functions is essential for mastering C and foundational for learning advanced programming concepts.
Programs:

User defined functions:


(No return value no passing argument)

P1-WAP to calculate the area of rectangle using user defined function.


#include<stdio.h>
#include<conio.h>
void area ();
int main ()
{
area ();
return 0;
}
void area ()
{
int l,b,a;
printf("Enter the value of length and breadth\n");
scanf("%d%d",&l,&b);
a=l*b;
printf("The area of rectangle is %d ",a);
}

P2-WAP to enter two different number and calculate the sum using defined function.
#include<stdio.h>
#include<conio.h>
void sum ();
int main ()
{
sum ();
return 0;
}
void sum ()
{
int a,b,add;
printf("Enter two number\n");
scanf("%d%d",&a,&b);
add=a+b;
printf("Sum of %d is",add);
P3-WAP to calculate the simple interest using user defined function.
#include<stdio.h>
#include<conio.h>
void SI ();
int main ()
{
SI ();
return 0;
}
void SI ()
{
int p,t,r,x;
printf("Enter the value of p,t,r\n");
scanf("%d%d%d",&p,&t,&r);
x=p*t*r;
printf("Simple interest is %d",x);
}

P4-WAP to enter a number and check whether it is positive or negative.


#include<stdio.h>
#include<conio.h>
void num ();
int main (){
num ();
return 0;
}
void num ()
{
int n;
printf("Enter the number\n");
scanf("%d",&n);
if (n>0)
{
printf("%d is positive number",n);
}
else if (n<0)
{
printf("%d is negative number",n);
}
else
{
printf("%d is zero",n);
}
}
P5-WAP to convert distance KM to meter using user defined function.
#include<stdio.h>
#include<conio.h>
void convert ();
int main ()
{
convert ();
return 0;
}
void convert ()
{
int kilometer, meter;
printf("Enter the number\n");
scanf("%d",&meter);
kilometer=1000*meter;
printf("The meter of given number is %d",kilometer);
}

P6-WAP to find out the largest number among three numbers using user define function.
#include<stdio.h>
#include<conio.h>
void num ();
int main (){
num();
return 0;
}
void num (){
int a,b,c;
printf("Enter the value of a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
{
printf("a is greater number");
else if(b>a && b>c)
{
printf("b is greater number");
}
else
{
printf("c is greater number");
P7-Wap to raise the power of B
#include<stdio.h>
#include<conio.h>
void sum ();
int main ()
{
sum ();
return 0;
}
void sum ()
{
int a,c=0,n;
printf("Enter a number\n");
scanf("%d",&n);
while(n>0)
{
a=n%10;
c=c+a;
n=n/10;
}
printf("The a raise power b is %d ",c);
}

P8-WAP to display the multiplication table of 'n' number using user define function.
#include<stdio.h>
#include<conio.h>
void num ();
int main ()
{
num ();
return 0;
}
void num ()
{
int n,i;
printf("Enter a number\n");
scanf("%d",&n);
for (i=1; i<=10; i++)
{
printf("%d*%d=%d\n",n,i,n*i);
}
P9-Wap To Sort the input ‘n’ numbers into ascending using function.
#include <stdio.h>
int sort (int num[], int n);
int main() {
int n, num[100];
printf("Enter how many numbers? ");
scanf("%d", &n);
printf("\nEnter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
sort(num, n);
return 0;
}
int sort(int num[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("\nThe sorted numbers in ascending order are:\n");
for (i = 0; i < n; i++) {
printf("%d\n", num[i]);
} return 0;
}

P10-To calculate the factorial of a given number using function.


#include<stdio.h>
int fact(int);
int main(){
int n,a;
printf("\n Enter any number: "),
scanf("%d", &n);
a=fact(n);
printf("\n factorial= %d", a);
return 0;
}
int fact(int n){
int i,f=1;
for(i=1;i<=n;i++){
f=f*i;
}
return 0;
}
P11-To sort integer variables in ascending order.
#include <stdio.h>
int main() {
int n, i, j, num[100], temp;
printf("Enter how many numbers? ");
scanf("%d", &n);
printf("\nEnter %d numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("\nThe sorted numbers in ascending order are:\n");
for (i = 0; i < n; i++) {
printf("%d\n", num[i]);
}
return 0;

To Display Series of Cubed Numbers.


#include <stdio.h>
int displayCubes(int );
int main() {
int n;
printf("Enter how many numbers you want to calculate the cubes for: ");
scanf("%d", &n);
displayCubes(n);
return 0;
}
int displayCubes(int n) {
printf("Cubes of the first %d numbers:\n", n);
for (int i = 1; i <= n; i++) {
int cube = i * i * i;
printf("%d^3 = %d\n", i, cube);
}
return n;
}
To Sort the input ‘n’ numbers into ascending using function.
#include <stdio.h>
int sort (int num[], int n);
int main() {
int n, num[100];
printf("Enter how many numbers? ");
scanf("%d", &n);
printf("\nEnter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
sort(num, n);
return 0;
}
int sort(int num[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (num[i] > num[j]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("\nThe sorted numbers in ascending order are:\n");
for (i = 0; i < n; i++) {
printf("%d\n", num[i]);
} return 0;
}

Sum of cubes
#include <stdio.h>
int Cubes(int);
int main() {
int n;
printf("Enter how many numbers you want to calculate the sum of
cubes for: ");
scanf("%d", &n);
printf("\nSum of cubes of the first %d numbers is %d\n", n,
Cubes(n));
return 0;
}
int Cubes(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i * i * i;
}
return sum;
}
Recursive function:
Recursion can be regarded as the ability of function defining an object in terms of a simpler case of itself. It is a
process by which a function calls itself repeatedly, until some specific condition has been satisfied. For the problem
to solve recursively two conditions must be satisfied:
1. The function should call itself.
2. The problem statement must include a stopping condition.

Factorial of a number using recursion


Here are the steps to perform factorial in C using recursion:
1. Define a function fact(n):
This function will take an integer n as input and return the factorial of n
2 Base Case:
If n is equal to 0, the factorial of 0 is defined as 1. The function should simply return 1 in this case.

Recursive Case

Center than 8, the factorial of n is equal tot multiplied by the factorial of -1. The function should call itself
recursively with n-1 as the argument.

4. Return the Result

In both the base and recursive cases, the function should return the calculated

value (either 1 or n* fact(n-1)).

Fibonacci series
Here are the steps to perform the Fibonacci series in C using recursion:
1. Define a function fibo (n):
This function will take an integer n as input and return the ith term of the
Fibonacci series.
2. Base Cases
The first two terms of the Fibonacci series are defined as 0 and 1. The function should handle these cases separately.
If n is equal to 0, the function should return 0.
If n is equal to 1, the function should return 1.
3. Recursive Case
If n is greater than 1, the nth term of the Fibonacci series is the sum of the (n-1) and (n-2)th terms. The function
should call itself recursively with n-1 and n-2as arguments and return the sum.
Recursive programs:
WAP to find the sum of even numbers upto nth using
recursive.
#include<Stdio.h>
int SumEven(int num1, int num2)
{
if(num1>num2)
return 0;
return num1+SumEven(num1+2,num2);
}
int main()
{
int num1=2,num2;
printf("Enter Your Limit:");
scanf("%d",&num2);
printf("Sum of all Even Numbers in the given range is: %d",SumEven(num1,num2))
}

To calculate the factorial of a number.


#include<stdio.h>
int fact(int);
int main() {
int n;
printf("Enter a positive integer:\t ");
scanf("%d",&n);
printf("\n Factorial of %d = %d", n, fact(n));
return 0;
}
int fact(int n) {
if (n>=1)
return n*fact(n-1);
else
return 1;
}
Wap To generate Fibonacci series
#include <stdio.h>
int fibo(int);
int main()
{
int n;
printf("Enter the number of terms\n");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (int i = 0; i < n; i++) {
printf("%d ", fibo(i));
}
return 0;
}
int fibo(int n)
{
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return (fibo(n-1) + fibo(n-2));

To calculate sum of n-natural number using recursion.


#include <stdio.h>
int sum (int);
int main()
{
int n,s;
printf("Enter any number \t");
scanf("%d",&n);
s = sum(n);
printf("Sum is %d\n",s);
return 0;
}
int sum (int n){
if (n<=0)
return 0;
else
return (n+sum(n-1));
}
To print multiples of entered number using recursion.
#include <stdio.h>
int multi(int,int,int);
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("The first 10 multiples of %d are:\n", n);
multi(n,n,1);
printf("\n");
return 0;
}
int multi(int n,int r,int count) {
if (count > 10) {
return count;
}
printf("%d ", r);
return multi(n, r + n, count + 1);
}

Check odd or even


#include <stdio.h>
int check(int n);
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (check(n)) {
printf("%d is even.\n", n);
} else {
printf("%d is odd.\n", n);
}
return 0;
}
int check(int n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 0;
}
return check(n - 2);
}
To print factors of entered number.
#include <stdio.h>
int factor(int);
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
factor(number);
return 0;
}
int factor(int num) {
printf("Factors of %d are: ", num);
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
printf("%d ", i);
}}
printf("\n");
return 0;
}

To find HCF of two numbers.


#include <stdio.h>
int hcf(int , int ) ;
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
int result = hcf(num1, num2);
printf("HCF of %d and %d is: %d\n", num1, num2, result);
return 0;
}
int hcf(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Structures and Union
Structure: Definition, Declaration, Initialization and Size of Structure

Definition of structure:
As we know that an array is the collection of homogeneous data items that means similar data type such as int or
float. It is not possible to hold different data items with different data types in an array, so structure is the best
solution to hold dissimilar data items as a single unit. It is just like record in database system. On the other hand, it
is defined as user-defined data type because users are capable to define their own data type.

Structure is collection of heterogeneous data items treated as a single unit. Each data item is called member of
structure. The keyword struct is used to declare structure variable and type of structure variable is defined by the
tag_name of the structure. The general syntax to define structure variable is given below.

Some major features of structure


It can be treated as record that is collection of interrelated data fields having different data types.
It is possible to copy one structure variable to another by simply assignment operator (=).
It allows nested structure that is one structure inside another structure.
It is possible to pass structure variable as parameter to any function.
It is possible to define structure pointer also known as linked list

Declaration of structure

Syntax for structure declaration

In this example, member1, member2,..memberN are the members of the structure and var1, var2 var3....varM are
M variables with data type tag_name.

struct tag_name
{
data_type member1;
data_type member2;
……………………
data_type memberN;
};
struct tag name var1, var2, var3....varM;

Example of structure variable


In this example, student is structure type and int roll_no, char fname[30] and char Iname[30] are the members of
the structure. s1,s2 and s3 are the structure variables with data type student.

struct student
{
int roll_no;
char fname[30];
char Iname[30];
};
struct student S1,S2,S3;
Initialization of structure:
Structure variable can be initialized quite similar to array. The following example shows the structure initialization
process.

struct student
{
int roll_no;
char fname[30];
char Iname[30];
}
S1={1, "Ram", "Rai"};
The alternate method to initialize structure variable as:

struct student S2={1, "Sita", "Devi");


struct student S3={2, "Hari", "Sharma");

Size of structure
The actual memory size of a variable in terms of bytes may vary from machine to machine. Therefore, the sizeof
operator helps us to determine memory size of a variable. In the following example, the memory size of the structure
variable S is 64.

Syntax
siezeof(struct variable);

EXAMPLE
struct student
int roll_no;
char fname[30];
char Iname[30];
}
S;
Structure programs:
WAP to enter ID, name and salary of n employee and display the information using structure.
#include<Stdio.h>
#include<conio.h>
int main()
{
struct employee
{
char name[50];
int id;
int salary;
};
struct employee e[100];
int i,n;
printf("Enter how many employees do you want:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
printf("Enter name, id, salary:");
scanf("%s%d%d",e[i].name,&e[i].id,&e[i].salary);
}
printf("The information you entered:");
for(i=1; i<=n; i++)
{
printf("name=%s\n id=%d\n salary=%d\n",e[i].name,e[i].id,e[i].salary);
}
return 0;
}
WAP a program that takes roll_no, fname, lname of 5 students and prints the same records in ascending
order on the basis of roll_no using structure.

#include<stdio.h>
int main()
struct student
{
int roll_no;
char fname[20];
char lname[20];
}
s[5];
{
struct student temp;
int i,j;
for(i=0;i<5;i++)
{
printf("\n Enter Roll Number");
scanf("%d",&s[i].roll_no);
printf("\n Enter First Name");
scanf("%s",s[i].fname);
printf("\n Enter Last Name");
scanf("%s",s[i].lname);
}
for (i=0; i<4; i++)
{
for (j=i+1; j<5; j++)
{
if(s[i].roll_no>s[j].roll_no)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
printf("\n Roll, Names and Addresses in Acending Order\n");
for(i=0; i<5; i++)
{
printf("\n %5d%10s%10s",s[i].roll_no,s[i].fname,s[i].lname);
}
WAP that takes name marks of 20 students. Sort data according to marks in descending order and display
them using structure.
#include<stdio.h>
int main(){
struct student{
char name[20];
float marks;
}s[20];
int i,n;
printf("\n How many records do you want to enter:");
scanf("%d",&n);
for(i=0; i<n; i++){
printf("\n Enter Name:");
scanf("%s",s[i].name);
printf("\n Enter Marks:");
scanf("%f",&s[i].marks);
}struct(n);
struct student temp;
int i,j;
for(i=0; i<n-1; i++){
for(j=i+1; j<n; j++){
if(s[i].marks<s[j].marks){
temp=s[i];
s[i]=s[j];
char name[50];
int id;
int salary;
};struct employee e[100];
int i,n;
printf("Enter how many employees do you want:");
scanf("%d",&n);
for(i=1; i<=n; i++){
printf("Enter name, id, salary:");
scanf("%s%d%d",e[i].name,&e[i].id,&e[i].salary);
}
printf("The information you entered:");
for(i=1; i<=n; i++){
printf("name=%s\n id=%d\n salary=%d\n",e[i].name,e[i].id,e[i].salary);
}
return 0;
}}
WAP to enter ID, name and salary of n employee and display the information whose salary is greater than
20000 using structure.
#include<stdio.h>
int main()
{
struct employee
{
char name[50];
int id;
int salary;
};
struct employee e[100];
int i,n;
printf("Enter how many employees do you want:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
printf("Enter name, id, salary:");
scanf("%s%d%d",e[i].name,&e[i].id,&e[i].salary);
}
printf("The information you entered:");
for(i=1; i<=n; i++)
{
if(e[i].salary>20000)
printf("name=%s\n id=%d\n salary=%d\n",e[i].name,e[i].id,e[i].salary);
}
return 0;
}
WAP to enter employee name, id and salary and print it out in asecending order according to the salary.
#include<stdio.h>
int main()
{
struct employees
{
char name[100];
int id;
float salary;
}e[50];
struct employees temp;
int i,j,n;
printf("enter how many times do you want to enter");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("enter the name id salary");
scanf("%s%d%f",e[i].name,&e[i].id,&e[i].salary);
}
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if (e[i].salary>e[j].salary)
{
temp=e[i];
e[i]=e[j];
e[j]=temp;
}
}
}
printf("the information of student in assending order");
for(i=0;i<=n;i++)
{
printf("name=%s\t id=%d\t salary=%f",e[i].name,e[i].id,&e[i].salary);
}
return 0;
}
To display name, age and marks of student using structure.
#include <stdio.h>
struct student
{
char name[50];
int age;
float mark;
}
s;
int main()
{
struct student s;
printf("Enter your name,age and mark \n");
scanf("%s \n %d \n %f",&s.name,&s.age,&s.mark);
printf(" \n Name : %s \n Age : %d \n Mark : %f",s.name,s.age,s.mark);
return 0;
}

To enter name, id and salary of 'n' employee and sort term them in ascending order on the basis of salary
using structure.
#include<stdio.h>
int main(){
struct employee{
char name[30];
int id;
int salary;
};struct employee e[100];
int n, i;
printf("enter a integer:\n");
scanf("%d",&n);
for (i=0;i<n;i++){
printf("enter name id and salary:\n");
scanf("%s%d%d",e[i].name,&e[i].id,&e[i].salary);
}
for (i=0;i<n-1;i++){
for (int j=i+1;j<n;j++){
if (e[i].salary>e[j].salary){
e[i]=e[j];
}
}
}
printf("\n Name id and salary in ascending order \n");
for (i=0 ;i<n; i++){
printf("%s\n %d\n %d\n",e[i].name,e[i].id,e[i].salary);
}
return 0;
}
Pointers:

Pointer is a variable which holds the address of another variable.

Advantage:
It is useful for accessing location valve from memory
reduce length of program code.
fast execution
Saves time for execution.
efficient handling of elements of Structure.

Disadvantage:
memory leakage
Complesc for understanding.
Comparatibly slower writing of program.
If incorrect value is passing chances memory corruption.

The address (&) and Indirection Operator.

the '$' is address operation.


represents the address of variable.
* Operator is the valve at address operator
It represent the valve at the specified address.

Declaration

before variable
eg-int age;
int age; Pointer Declaration

Call by valves and calls by Refrence.

Call by value

In call by value method value at the actual parameter is copied into formal parameter.
It cannot modify the valve of actual para meter.
different memory is allocated for actual and formal parameter
Call by refrence:

In call by refrence method the address of variable is passed into the function call as the actual parameter.
The value of the actual parameters can be modified by changing the formal parameters
The memory allocation formal and similar for both actual parameter.

#include<stdio.h>
#include<conio.h>
int swap (int *, int*);
int main ()
{
printf("enter value of a and b");
Scanf("%d%d", &a,&b);
printf("The valves of before swapping a=%d b=%d",a,b);
Swap(&a, &b)
Printf ("The values after swapping a=%d b=%d"a,b);
return 0;
}
int Swap (int *x, int *y)
int temp
temp = X
*X=*Y
*Y = temp;
}

Pointers programs:

Find the product of two numbers using pointers.


#include <stdio.h>
int main() {
int num1, num2, product;
int *ptr1, *ptr2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
ptr1 = &num1;
ptr2 = &num2;
product = (*ptr1) * (*ptr2);
printf("The product of %d and %d is: %d\n", *ptr1, *ptr2, product);
Print array of an elements
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr;
ptr = arr;
printf("Array elements are:\n");
for(int i = 0; i < 5; i++) {
printf("%d ", *ptr);
ptr++; }
return 0;

Swapping between two numbers


#include <stdio.h>
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);
swap(&num1, &num2);
printf("After swapping: num1 = %d, num2 = %d\n", num1, num2);
return 0;
}

Print value of pointer


#include <stdio.h>
int main() {
int *ptr = NULL;
printf("The value of the pointer is: %p\n", ptr);
if (ptr == NULL) {
printf("The pointer is NULL.\n");
} else {
printf("The pointer is not NULL.\n");
}
return 0;
}
Reverse a string using pointers.
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
char *start = str;
char *end = str + strlen(str) - 1;
char temp;
while (start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
} }
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}

Copy a string into another variable using pointers.


#include <stdio.h>
void copyString(char *source, char *destination) {
while (*source != '\0') {
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}
int main() {
char source[] = "Hello, Pointer!";
char destination[50];
copyString(source, destination);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
return 0;
}
Find the length of a string using pointers.
#include <stdio.h>
int stringLength(char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
int main() {
char str[] = "Hello, World!";
int len = stringLength(str);
printf("The length of the string is: %d\n", len);
return 0;
}

Find the sum of all elements in an array using pointers.


#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int sum = 0;
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
sum += *(ptr + i);
}
printf("The sum of the array elements is: %d\n", sum);
return 0;
}

Find the largest element in an array using pointers.


#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int size = sizeof(arr) / sizeof(arr[0]);
int largest = *ptr;
for (int i = 1; i < size; i++) {
if (*(ptr + i) > largest) {
largest = *(ptr + i);
}
}
printf("The largest element in the array is: %d\n", largest);
return 0;
}
Calculate the average of array elements using pointers.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
float average;
for (int i = 0; i < size; i++) {
sum += *(ptr + i);
}
average = (float)sum / size;
printf("The sum of the array elements is: %d\n", sum);
printf("The average of the array elements is: %.2f\n", average);
return 0;}

Demonstrate the use of a pointer to a pointer.


#include <stdio.h>
int main() {
int value = 5;
int *ptr = &value;
int **ptr2 = &ptr;
printf("Value: %d\n", value);
printf("Value using ptr: %d\n", *ptr);
printf("Value using ptr2: %d\n", **ptr2);
**ptr2 = 10;
printf("Modified Value: %d\n", value);
return 0;
}

Find the factorial of a number using pointers.


#include <stdio.h>
long long factorial(int *n) {
long long result = 1;
for (int i = 1; i <= *n; i++) {
result *= i; }
return result;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
long long result = factorial(&num);
printf("The factorial of %d is %lld\n", num, result);}
return 0;
}
Calculate the power of a number using pointers.
#include <stdio.h>
long long power(int *base, int *exponent) {
long long result = 1;
for (int i = 1; i <= *exponent; i++) {
result *= *base; }
return result;
}
int main() {
int base, exponent;
printf("Enter the base: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
if (exponent < 0) {
printf("Exponent should be a non-negative integer.\n");
} else {
long long result = power(&base, &exponent);
printf("%d raised to the power of %d is %lld\n", base, exponent, result);
}
return 0;
}

File Handling in C:
As we know, while program is in execution the content of variables are temporarily stored in main memory i.e.
RAM. Data reside temporarily in RAM only at the time of program execution. After the completion of execution
data gets erased away which means the data cannot be used for future references. To overcome this problem, file
handling comes into existence through which we can store data permanently in our secondary storage and
retrieve it whenever in future. Data are stored as datafile in our disk.

File handling in C
Opening a data file
Syntax:
FILE *fptr
Fptr = fopen (“filename” , ”mode”)
Where, File name can be “library.txt”, “student.dat” ..etc
Mode:
“w” to write/store data in a data file.
“r” to display/read/retrieve/access data from a datafile.
“a” to add/append data in existing datafile.
Store/write data
Syntax:
Fprintf(fptr , ”format specifiers” ,variables);

// suppose if we want to store name, disease, age and bed number of a patient then, it is written as
Fprintf(fptr , ”%s %s %d %d”, n, d, a, b);
Where, variable are initialized as:
Char n[10], d[10];
Int a, b;
Create and Write to a File
#include <stdio.h>
int main() {
FILE *file = fopen(“example.txt”, “w”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
fprintf(file, “Hello, World!\n”);
fclose(file);
printf(“File written successfully.\n”);
return 0;
}

Read from a File


#include <stdio.h>
int main() {
FILE *file = fopen(“example.txt”, “r”);
char buffer[100];
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
while (fgets(buffer, 100, file)) {
printf(“%s”, buffer);
}
fclose(file);
return 0;
}

Copy Content from One File to Another


#include <stdio.h>
int main() {
FILE *source = fopen(“example.txt”, “r”);
fILE *destination = fopen(“copy.txt”, “w”);
char ch;
if (source == NULL || destination == NULL) {
printf(“Error opening file.\n”);
return 1;
}
While ((ch = fgetc(source)) != EOF) {
Fputc(ch, destination);
}
Fclose(source);
Fclose(destination);
Printf(“File copied successfully.\n”);
return 0;
}
Check if a File Exists
#include <stdio.h>
Int main() {
FILE *file = fopen(“example.txt”, “r”);
If (file) {
Printf(“File exists.\n”);
Fclose(file);
} else {
Printf(“File does not exist.\n”);
}
Return 0;
}

Write program to write roll, name and Of 1 students from the file
#include <stdio.h>
Int main()
{
FILE *fp;
Int roll;
Char name [30];
Float per;
Int i=1;
Fp = fopen(“info .txt.”, “w”);
Do{
Printf(“\n Enter name:”);
Scanf(“%s”, name) ;
Printf(“\n Enter percentage:”);
Scanf(“%f”, &per) ;
Fprintf(fp,”\n%d%s%f”, roll, name, per);
I++;
} while (i<=1);
Fclose(fp);
Return 0 ;
}
Write a program to enter name ,post and salary of employee in a file “employee .txt.”
#include <stdio.h>
Int main()
{
Char n[30],p[30];
Float s;
FILE*fptr;
Fptr = fopen(“employee .txt.”, “w”);
Printf(“\n Enter name:”);
Scanf(“%s”, n) ;
Printf(“\n Enter post:”);
Scanf(“%s”, p) ;
Printf(“\n Enter salary:”);
Scanf(“%f”, &s) ;
Fprintf(fptr,”%s%s%f”,n, p,s);
Fclose(fptr);
Return 0 ;
}

Write a program in append mode in file handling in a data file name “abc.txt”
#include <stdio.h>
Int main() {
FILE *file;
File = fopen(“abc.txt”, “a”);
If (file == NULL) {
Printf(“Error opening file!\n”);
Return 1;
}
Fprintf(file, “This is a new line added in append mode.\n”);
Fclose(file);
Printf(“Data appended successfully to abc.txt!\n”);
Return 0;
}
Write a program to read existing data file information name “location.dat”
#include <stdio.h>
Int main() {
FILE *file;
Char ch;
File = fopen(“location.dat”, “r”);
If (file == NULL) {
Printf(“Error: File not found or cannot be opened!\n”);
Return 1;
}
Printf(“Contents of location.dat:\n”);
While ((ch = fgetc(file)) != EOF) {
Putchar(ch);
}
Fclose(file);
Return 0;
}

Write a program to write and read character


#include <stdio.h>
Int main() {
FILE *file;
Char ch;
File = fopen(“data.txt”, “w”);
If (file == NULL) {
Printf(“Error opening file!\n”);
Return 1;
}
Printf(“Enter a character to write to file: “);
Scanf(“ %c”, &ch);
Fputc(ch, file);
Fclose(file);
File = fopen(“data.txt”, “r”);
If (file == NULL) {
Printf(“Error opening file!\n”);
Return 1;
}
Ch = fgetc(file);
Printf(“Character read from file: %c\n”, ch);
Fclose(file);
Return 0 ;
}
Web technology:
Web technology helps us to allow different computers to communicate and helps to share resources among
different computer network systems across the internet. It has been simpler and user-friendly day by day from
users' side, on the other hand, it has been complex and huge from programmer perspective. Therefore, scientists
are trying make simple and manageable by using different tools and techniques. Web technology has started from
simple hyper text page technology and now it has been reached to the cloud computing and Al based expert
system. The primary concerns of web technology are to give us a way to interact with hosted information, such as
websites and how to secure this web-based information. The three main languages which helps to make the
World Wide Web are HTML, CSS, and JavaScript

Server Side and Client Side Scripting:

Client Side Scripting:

Mainly a website is classified into two types: static and dynamic. A static website has no interactive features and
it delivers the information to the user exactly as stored. Such website contains text, graphics, audio and video.
The audio and video are considered
as static content because they play automatically in webpage and have no interactive features. Such website is
periodically updated by manually editing text, graphics, audio and video. The static website is developed by
using client side scripting languages: HTML, CSS and JavaScript. Such scripts are also known as client end
(front end) scripts which require browser to run the scripts on client computer, but it does not interact with the
server.

Server Side Scripting:

On other hand, dynamic website is interactive website with capability to change the content each time they are
accessed. Mainly, such website is controlled by the server where it is stored. Such server runs special program
called webserver program which helps to manage website. The dynamic website also contains web application or
web app. The dynamic website can be easily updated and developed by using server-side scripting such as Perl,
ASP, PHP, JSP, Java, etc. Such scripts are also known as server end (back end) script

Adding Java Script to HTML Page:

As HIML is simple mark-up language for developing web documents. Such web documents contents static nature
of information because they do not respond to the user.
Such HTML documents do not make decisions, automate repetitive of tasks. In order to solve such problems,
scientist develops scripting language. A scripting language is a kind of web-based programming language for
solving web related problems. But it is not complete programming language because it cannot solve all kind of
problems. Scripting languages have simple syntax, can perform tasks with minimum number of commands and
interpreted by web browser. Scripting language cannot independently execute and it is embedded inside HTML
tags. Client site scripting languages execute in client site Imwser as per the user's responds. Examples of client
site scripts are JavaScript VBScript, etc. Consider the following example, it shows how to embed JavaScripts to
HTML
Java Script Fundamental:

JavaScript (JS) is one of the most popular scripting programming language. It is light weight and mostly used to
develop dynamic websites. It is implemented as client-side script in html to make dynamic pages. It is a case
sensitive interpreted programming language with object-oriented capabilities. It was developed by Netscape and
originally called LiveScript in 1995. Netscape changed its name to JavaScript language and later it has been also
supported by Internet Explorer and Mozilla Firefox. European Computer Manufacturers Association (ECMA) is a
standard organization for information and communication systems which standardized JavaScript as ECMA-262.
It is a general-purpose client side scripting language on the World Wide Web.

Major Features of JavaScript

It is a standard scripting language and supported by most of the browsers.


It is a lightweight and efficient interpreted programming language.
It is complementary to and integrated with HTML and Java.
It is object-oriented event driven programming language.
It is open source and cross platform (independent to OS)

Importance of JavaScript

It is designed for solving client-side application with prompt responds.


It can dynamically modify webpage as per requirements.
It can validate and respond user's input.
It can be used to create cookies. (A piece of information stored on the user's computer by the web browser while
browsing a website)
It does not require any interaction to web server while processing scripts on web browser.

Simple User Interaction Functions

JavaScript provides three built-in function to do simple user interaction.


alert(msg): It helps to make alerts to the user that something has happened.
EXAMPLE
Example: alert ("Don't touch it hot ");
confirm(msg): It helps to asks the user to confirm or cancel something.
Example: confirm (" Do you want to delete the file ");
prompt(msg, default value): It helps to ask user to enter some text value.
Example: prompt ("Enter your Name: ","Gems")
Sum of two number using java script
<html>
<head>
<title> sum of JS function</title>
</head>
<body>
<h3> sum of tow number using js function </h3>
<script>
function add() {
var a= parseInt(prompt("enter the first number "));
var b= parseInt(prompt("enter the srcound number "));
let sum =a+b;
document.write(“sum of two number =”+ sum);
}
Add();
Document.write(“<br>prepared by :sec t2 “);
</script>
</body>
</html>

Writer a java script code to calculate area of circle by using use define function:
<!DOCTYPE html>
<html>
<head>
<title> area of circle </title>
</head>
<body>
<h3> Area if circle using the no return type / value with parameter </h3>
<script>
Function area() {
var ar= parseInt(prompt("enter the radius of a circle “));
let ar = 3.141 *r*;
document.write(“Area of circle =+ar);
}
Area();
</script>
</body>
</html>
Write the java script code the find a the factorial number of any even positive number using user define
function :
<html>
<head>
<title>Factorial</title>
</head>
<body>
<h2>find the factorial of positive integer number entered by using user
for loop</h2>
<script>
function factorial()
{
var num=parseInt(prompt("enter any positive number"));
var fact=1;
for(var i=1;i<=num;i++)
{
fact=fact*i;
document.write("<h3>factoiral of "+num+"="+fact+"</h3>");
}}
factorial();
</script>
</body>
</html>

Write a java script code to display the multiplaction table of any given number by using function:
<html>
<head>
<title> Multiplication Table </title>
</head>
<body>
<h2> Display multiplication table of given number </h2>
<script>
function multi(){
var num=parseInt(prompt("enter any positive number"));
for(var i=1; i<=10; i++)
{
document.write(num + "x" + i + "=" +(num*i));
console.log("\n");
}}
multi();
</script>
</body>
</html>
Event Handling:
Even handling is one of the important features of object-oriented programming. It is an efficient and user-friendly
mechanism in graphical user interface (GUI) environment. Event is defined as an action of an application or user
such as mouse click, mouse over, pressing any key, open window, close window, etc that triggers an action
related to an object. In web programming, even is useful mechanism to communicate between HTML with
JavaScript. When a user accesses a webpage in browser the page loads on the browser, it is called an event, when
user clicks a button, it is also even. Events are a part of the Document Object Model (DOM) of JavaScript. Every
HTML event can communicate with JavaScript codes. Some of the popular HTML 5 standard events are listed
below.

Program To Display The Date And Time By Id :-

<!DOCTYPE html>
<html>
<head>
<title>date and time <title/>
<head/>
<body>
<button type="button"
onclick="document.getElementById('demo').innerHTML+Date()">
click me to display date and time </button>
<p id="demo"></p>
</body>
</html>

Program To Display The Content Using Event Handeling (Onmouseover) :-


<html>
<head>
<title>onmouseover event </title>
<script>
function over(){
document.write("Mouse over");
}
function out(){
document.write("Mouse out");
}
</script>
</head>
<body>
<p> Bring your mouse inside the divison to see the result </p>
<div onmouseover="over()"onmouseout="out()">
<h2>This is inside the divison </h2>
</div>
</body>
</html>
PHP:
PHP originally stood for Personal Home Pages, although the acronym is now understood to stand (somewhat
recursively) for PHP: Hypertext Preprocessor. When any person request for any PHP page in the address bar of
the browser that request is first sent to the server then server interpret PHP files and return back response in form
of Html. That's why it is called Hypertext Preprocessor.

PHP started out as a small open source project that evolved as more and more people found out how useful it
was. Rasmus Lerdorf released the first version of PHP way back in 1994.

Features of PHP:
This syntax of PHP is similar to C, so, it is easy to learn and use.
PHP runs efficiently on the server side.
PHP is free software under the PHP license. We can easily download it from the official PHP website.
PHP runs on various platforms like Windows, Linux, UNIX, Mac OS etc.
It is compatible with almost all servers used today like Apache, IIS, etc.
PHP supports a wide range of databases

Common uses of PHP:


By using PHP, you can create, open, read, write, and close files.
PHP can handle forms, i.e. gather data from files, save data to a file, through emailyou can send data, return data
to the user.
You add, delete, and modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data
First php program
<!DOCTYPE html>
<html>
<head>
<title>1.first</title>
</head>
<body>
<?php
echo"this is my first php program";
?>
</body>
<html>

Sum of two numbers


<!DOCTYPE html>
<html>
<head>
<title>1.first</title>
</head>
<body>
<?php
$num1=5;
$num2=30;
$sum=$num1+$num2;
echo"sum of two number is".$sum;
?>
</body>
<html

Simple intrest of the given number


<html>
<head>
<title>simple intrest</title>
</head>
<body>
<h3>calculate simple intrest using function</h3>
<?php
function simple()
{
$principle=10000;
$rate=12;
$time=10;
$intrest=($principle*$rate*$time)/100;
echo"simple intrest ".$intrest;
}
simple();
?>
</body>
</html>
Factorial of given number

<!DOCTYPE html>
<html>
<head>
<title>factorial</title>
</head>
<body>
<h3>calculate factorial using function</h3>
<?php
function factorial()
{
$num=5;
$fact=1;
for($i=1; $i<=$num; $i++)
{
$fact=$fact*$i;
}
echo"the factorial $num is".$fact;
}
factorial();
?>
</body>
<html

Multiplication of the given number


<!DOCTYPE html>
<html>
<head>
<title>multiplication</title>
</head>
<body>
<h3>calculate multiplication table using function</h3>
<?php
function multi()
{
$num=5;
for($i=1; $i<=10; $i++)
{
$mul=$num*$i;
echo"$num X $i = $mul <br>";
}
}
multi();
?>
</body>
<html
Form validation:
Form is useful interface to enter data to the system and form element can be implemented using HTML tag
<form>. While entering data in form, there may be chances of entering incorrect data or blank data for all the
mandatory fields which may lead data inconsistency in web start for validation process is also occurred at server
side, it is better to validate at cline side during data entering time. It improves efficiency of system by minimizing
server request from the client. In order to make more data consistence, JavaScript provides two levels of data
validation techniques: in basic level, the form must be checked to make sure all the mandatory fields are filled in,
in format validation the data that is entered must be checked for correct form and value. Consider the following
Example to validate a simple form.

Form validation
<html>
<head>
<title>form </title>
</head>
<body>
<h2> demo of simple login from validation </h2>
<form name="login">
<label for="username">username=</label>
<input type="text"name="username"><br><br>
<label for="password">password:</label>
<input type="password" name="password"><br><br>
<input type="submit"value="login" onclick="validate form()">
<input type="reset"value="reset">
</form>
<script>
function validate form(){
var user=document.login.username.value;
var pass=document.login.password.value;
if(user==null||user=="")
{
alert("blank username not allowed...please fill it first!!!");
}
else if(pass==null||pass=="")
{
alert("blank password not allowed...please fill it first!!!");
}
else if(pass.length<=6)
{
alert("password length must be above 6 chaaracters...");
}
else
{
alert("welcome"+user);
}
}
</script>
</body>
</html>
Insert data into mysql using mysqli
<html>
<head>
<title> </title>
</head>
<body>
<?php
include('connect.php');
if(isset($_POST['submit'])){
$fname=$_POST['fname'];
$address=$_POST['address'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];
$query=mysqli_query($con,"insert into student(fname,address,mobile,email)values('$fname' , '$address' ,
'$mobile' , '$email')")
if($query)
{
echo"<script>alert'data insert successfully'</script>"
}
else
{
echo"<script>alert'data insert error '</script>"
}
}
?>
<form>
<input type="text"name="fname" placeholder="enter your full name" required>
<br><br>
<input type="text" name="address" placeholder="enter your address" required>
<br><br>
<input type="number" name="mobile" placeholder="enter your valid number">
<br><br>
<input type="text" nsme="email" placeholder="enter your email">
<br><br>
<button type="submit" name="submit">submit</button>
</form>
</body>
</html>
DDL (Data Definition Language) and DML (Data Manipulation Language)
SQL is used to define the structure of data base SQL stands for Structured Query Language. It is an international
standard database query language for accessing and managing data in the database SQL was introduced and
developed by IBM in early 1970s. IBM was able to demonstrate SQL. which could be used to control relational
databases. SQL is not a complete programming languages, it is only used for communicating with database. It
provides platform which allows the user to query a database without getting depth knowledge of the design of the
underlying tables. SQL has statements for data definition, data manipulation and data control. A query is a
request to the DBMS for the retrieval, modification, insertion and deletion of the data from the database.

SQL (Structured Query Language) Pronounced as "See"-"Quell" is made of three sub languages DDL, DML. and
DCL

2. DML (Data Manipulation Language): DML is related with manipulation of records such as retrieval,
sorting, display and deletion of records or data. It helps user to use query and display reports of the table. So, it
provides techniques for processing the database. It includes commands to manipulate the information stored in
the databases. Examples of these Commands are Insert, Delete, Select and Update etc.

Structure of SQL
To create a table
Creation of table in MySQL (Create command)

The CREATE TABLE statement is used to create a new table in a database.

Syntax:

CREATE TABLE table_name (


columnl datatype,
column2 datatype,
column3 datatype,
);
where, columnl, column1, column3.. are columns of the table and data types are int, varchar, decimal, time, date.

Example:
CREATE TABLE student (
roll int.
first_name varchar(20),
last_name varchar(20),
age int );
INSERT Statement
The INSERT statement is used to add new records to an existing table from SQL database.
Syntax:
INSERT INTO table_name (column1, column2, column3,...) VALUES (valuel, val-ue2, value3,...);
where, column1, column2, coumn3......are fields and valul, value2, value3..... are string, number or date/time.
Example,
INSERT INTO student (roll, first_name, last_name, DateOfBirth) VALUES (1, 'Aay-ushi', 'Karn',

SELECT Statement
1. The SELECT statement is used to select data from a database. It is used to select from one or more tables. The
data returned is stored in a result table, called the result-set.
Syntax:
SELECT column_name(s) FROM table_name
Example,
a) SELECT roll FROM student;
It will display all roll numbers inserted in a table student.
b) SELECT * FROM student;
we can use the * character to select ALL columns from a table:
It will display all records from a table student.

ALTER statement
The ALTER TABLE statement is used to add, delete, modify or change data types of columns in an existing
table.

1. ALTER TABLE - ADD Column


The ALTER TABLE statement is used to add a column to an existing table from SQL database.
Syntax:
ALTER TABLE table_nam
ADD column_name datatype;
Example,
ALTER TABLE student
ADD DateOfBirth date;

Update Statement
The UPDATE statement is used to update existing records in a table.
Syntax:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE columnName = value
where columnName is column1, culumn2,....... and value is text or number or
date/time.
Example,
UPDATE student
SET first_name = 'Alok', last_name = 'Kumar'
WHERE roll = 1;
Table of Contents

Introduction to function .............................................................................................. 1


Advantages of Functions ............................................................................................ 2
Programs .................................................................................................................... 2
User defined functions................................................................................................ 3
Recursive function ...................................................................................................... 2
Recursive programs .................................................................................................... 3
Check odd or even ...................................................................................................... 5
Structures and Union .................................................................................................. 7
Structure programs ..................................................................................................... 8
Pointer program ......................................................... Error! Bookmark not defined.
File Handling in C .................................................................................................... 21
Web technology ........................................................................................................ 26
Event Handling......................................................................................................... 30
Php ........................................................................................................................... 31
Form validation ........................................................................................................ 34
DDL (Data Definition Language) and DML (DataManipulation Language) ............ 36

You might also like