0% found this document useful (0 votes)
10 views

Computer Project

The document is a project submission by Mukesh Kumar Sah for his class 12 computer science practical exam. It contains an acknowledgment section thanking those who helped with the project. The table of contents lists that the project covers JavaScript, PHP, and C programming languages over 11, 22, and 34 pages respectively.

Uploaded by

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

Computer Project

The document is a project submission by Mukesh Kumar Sah for his class 12 computer science practical exam. It contains an acknowledgment section thanking those who helped with the project. The table of contents lists that the project covers JavaScript, PHP, and C programming languages over 11, 22, and 34 pages respectively.

Uploaded by

Abhinai Adhikari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

MITHILA INSTITUTE OF

TECHNOLOGY
Bishara Chowk, Janakpurdham-4
Project Work of Computer Science

For the Fulfillment of Practical Exam 2078 B.S.


Submitted By:- Submitted To:-
Name: Mukesh Kumar Sah National Examination Board (NEB)

Class: Twelve (XII) Submission Date: 2079/01/15

Roll No.: 231


Registration No.: 782170170401 Signature
Registration No.: 782170170401

ACKNOWLEDGEMENT

I have taken efforts in this project. However, it would not have been
possible without the kind support and help of many individuals. I would
like to extend my sincere thanks to all of them.
I would like to express a deep sense of thanks and gratitude to my
subject teacher Mr. Sanjeev Kumar Yadav for guiding me immensely
through the course of the project. He always evinced keen interest in my
work. His constructive advice and constant motivation have been
responsible for the successful completion of this project.
My sincere thanks go to Mr. Raja Ram Yadav , our principal sir, for
his co-ordination in extending every possible support for the completion of
this project.
I also thanks to my parents for their motivation and support. I must
thanks to my classmates for their timely help and support for completion
of this project.
Last but not the least, I would like to thank all those who had
helped directly or indirectly towards the completion of this project.

Divakar Yadav
Class: XII ''C"

By: Divakar Yadav


Registration No.: 782170170401

Table of Contents

S.N. Contents Page


1. JavaScript 1 - 11
2. PHP 12 - 22
C
3. Programming 23 - 34
Language - II

By: Divakar Yadav


Registration No.: 782170170401

JavaScript
JavaScript
JavaScript is a dynamic scripting language (website development environment). It is
lightweight and mostly used as a part of web pages. JavaScript code can be inserted into any HTML
page, and it can be executed by all types of web browsers. JavaScript is used to make web pages
interactive. It runs on your visitor's computer and doesn't require constant downloads form your
website.
JavaScript Syntax
JavaScript can be implemented using JavaScript statement that are placed within the <script>
….. </script> HTML tags in a web page. We can place the <script> tags, containing our JavaScript,
anywhere within our web page, but it is normally recommended that we should keep it within the
tags.
The <script> tags alert the browser program to start interpreting all the text between these tags as a
script. A simple syntax of our JavaScript will appear as follows.
<script…>
JavaScript code
</script>
JavaScript Control Structures
A control structure refers to the flow of execution of the program. These control structures
enable us to specify the order in which the various instructions in a program are to be executed. The
types of control structure are:
1. Selection Control structure
• If
• If else
• If else if
• Switch case
2. Looping Control structure
• For loop
• While loop
• Do while loop

a. If statement:
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally. If statement is the simplest decision-making
statements will be executed or not. That is, if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
If (expression) {
Statement (s) to be executed if expression is true
}

By: Divakar Yadav 1


Registration No.: 782170170401

The if statement evaluates the conditions first and then, if the value of the condition is true, it execute
the statement within this black. Otherwise, it skips the statements within its block and continues from
the first statement outside the if block.
Example:
<html>
<body>
<script type= "text/javascript">
var age = 20;
if (age >18) {
document.write("<b>Qualifies for driving</b>");
}
</script>
</body>
</html>
Output:
Qualifies for driving

b. If… else statement:


The 'if…else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way. If else statement is an either/or statement. If a specified
condition is true. JavaScript perform certain statements. If the condition is false, JavaScript might
perform other statements.
Syntax:
If (expression) {
Statement (s) to be executed if expressions is true
}
else {
statement (s) to be executed if expression is false
}
The condition can be any JavaScript expression that evaluates to true or false. The conditional
statements can be any JavaScript statements, including further nested if statements. Multiple must
be enclosed in braces.

Example:
<html>
<body>
<script type= "text/javascript">
var age = 16;
if (age > 18) {
document.write ("<b>Qualifies for driving</b>");
}
else {
document.write ("<b>Does not qualifies for driving</b>");
}
</script>
</body>
</html>
Output:

By: Divakar Yadav 2


Registration No.: 782170170401

Does not qualifies for driving

c. If… else if…statement:


The if…else if statement is an advanced form of if…. else that allows JavaScript to make a
correct decision out of several conditions. This is a type of new nesting in which there is an if… else
statement in every else part except the last else part. This type of nesting is frequently used in
programs and also known as an else if ladder. This construct is if-else-if ladders because of its
appearance.
Syntax:
If (expression 1) {
Statement (s) to be executed if expression 1 is true
}
else if (expression 2) {
Statement (s) to be executed if expression 2 is true
}
else if (expression 3) {
Statement (s) to be executed if expression 3 is true
}
else (expression 4) {
Statement (s) to be executed if expression 4 is true
}

The conditions are evaluated from the top downward. As soon as a true condition is found,
the statement associated with it is executed and the rest of the ladder is bypassed. If none of the
conditions are true, the final else is executed. If the final else is not present, no actions take place if all
other conditions are false.

Example:
<html>
<body>
<script type="text/javascript">
Var book = "maths";
if (book == "history") {
document.write ("<b> History Book </b>");
}
else if (book == "maths") {
document.write ("<b> Maths Book</b>");
}
else if (book == "economics") {
document.write ("<b> Economics Book</b>");
}
else {
document.write ("<b> Unknown Book</b>");
}
</script>
</body>
</html>

d. Switch Statement

By: Mukesh Kumar Sah 3


Registration No.: 782170170401

The objective of the switched statement is to give expression to evaluate several different
statements to execute based on the value of the expression. The interpreter checks each case against
the value of the expression until a match is found. If nothing matches, a default condition will be used.
Syntax:
switch (expression)
{
case condition 1: statement (s)
break;
……….
case condition n: statement (s)
break;
default: statement (s)
}
Example:
<html>
<body>
<script type="text/javascript">
var grade = 'A';
document.write ("Entering switch block</br>");
switch (grade)
{
case 'A' : document.write("Good job<br/>");
Break;
case 'B' : document.write("Pretty Good<br/>");
Break;
case 'C' : document.write("Passed<br/>");
Break;
case 'D' : document.write("Not so good<br/>");
Break;
case 'F' : document.write("Failed<br/>");
Break;
}
document.write ("Exiting switch block");
</script>
</body>
</html>
Output:
Entering switch block
Good job

Looping Control Structure:


Looping control structures are used when we want to execute a block of statement
repeatedly. A loop executes the sequence of statements many times until some condition becomes
false. There are different types of loops supported by JavaScript like other programming languages.
a. for loop:
For loop is commonly used loop. For loop is an entry control loop because it checks the
condition at entry point. Hence, it does not execute even a single statement if the termination
condition is set false. It includes the following three important parts:

1. The loop initialization where initialize our counter to starting value. The initialization statement is
executed before the loop begins.

By: Mukesh Kumar Sah 4


Registration No.: 782170170401

2. The test statement which test is given condition is true or not. If the condition is true, then the code
given inside the loop will be executed, otherwise, the control will come out of the loop.
3. The iteration statement where we can increase or decrease our counter.

Syntax:
For (initialization; test condition; iteration statement) {
Statement (s) to be executed if the test condition is true
}
Example:
<html>
<body>
<script type="text/javascript">
var i;
for (i=0; i<5; i++)
{
document.write("Computer Science</br>");
}
</script>
</body>
</html>
Result:
Computer Science
Computer Science
Computer Science
Computer Science
Computer Science

b. While Loop
While loop is an entry-controlled loop. In while loop, condition is evaluated first and if it
returns true then the statements inside the while loop execute. When condition return false, the
control comes out of loop and jumps to the next statement after while loop. When using while you
need to use increment or decrement statement inside the while loop so that the loop variable gets
changed on each iteration and at some point, condition returns false. This way you can end the
execution of while loop otherwise the loop will execute indefinitely.
Syntax:
While (expression) {
Statement (s) to be executed if expression is true
}
Example:
<html>
<body>
<script type="text/javascript">
var count=0;
document.write ("Starting Loop <br/>");
while (count <=5) {
document.write ("Current Count: "+ count +"<br/>");
count ++;
}
document.write ("Loop stopped!");
</script>
</body>

By: Mukesh Kumar Sah 5


Registration No.: 782170170401

</html>
Output:
Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Current Count: 5
Loop Stopped!

c. The do … while loop:


The do … while loop is similar to the while loop expected that the condition check happens at
the end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax:
do {
Statement (s) to be executed;
increment / decrement;
} while (condition)
Example:
<html>
<body>
<script>
var count=1;
document.write ("Starting Loop<br/>");
do {
document.write("Current Count: " + count + " <br/>");
count ++;
} while (count < 5);
document.write (" Loop stopped !!");
</script>
</body>
</html>
Output:
Starting Loop
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Loop stopped !!

Loop control
JavaScript provides full control to handle loops and switch statements. There may be a
situation when we need to come out of a loop without reaching its bottom. There may also be a
situation when we want to skip a part of our code block and start the next iteration for the loop.
a. The break statement
The break statement is used to exit all loop early, breaking out of the enclosing curly braces.
Example
<html>

By: Mukesh Kumar Sah 6


Registration No.: 782170170401

<body>
<script type="text/javascript">
var x = 0;
document.write ("Entering the loop<br/>");
while (x<20)
{
if (x == 5) {
break;
}
x = x + 1;
document.write (x + "<br />");
}
document.write ("Exiting form the loop! <br />");
</script>
</body>
</html>
The continue statement
The continue statement tells the interpreter to immediately start the next iteration of the loop and
skip the remaining code block.
When a continue statement is encountered, the program flow moves to the loop check expression
immediately and if the condition remains true, then it starts the next iteration, otherwise the control
comes out of the loop.
Example

<html>
<body>
<script type="text/javascript">
var x= 0;
document.write ("Entering the loop<br />");
while (x < 9)
{
x=x+1;
if (x==5) {
continue;
}
document.write (x + "<br/>");
}
document.write ("Exiting from the loop!<br/>");
</script>
</body>
</html>
Output:
Entering the loop
1
2
3
4
6
7
8
9

By: Mukesh Kumar Sah 7


Registration No.: 782170170401

Exiting from the loop!

The return Statement


A JavaScript function can have an optional return statement. This is required if we want to
return a value from a function. This statement should be the last statement in a function. For
example, we can pass two numbers in a function and then we can accept the function to return their
multiplication in our calling program.
Syntax:
Function function_name(para1,para2, ….)
{
block of statement;
return(expression);
}
Example:
<html>
<body>
<script type="text/javascript">
function add(a,b) {
return(a+b);
}
var x= add (10,20);
document.write(x);
</script>
</body>
</html>
Output:
30

Dialog Boxes/ Popup Boxes:


JavaScript supports three important types of dialog boxes.
a. Alert Dialog Box:
Alert dialogue box is mostly used to give a warning message to users. For example, if one input
field requires to enter some text but the user does not provide any input, then as a part of the
validation, we can use an alert box to give the warning message.
Nonetheless, an alert box can be still be used for friendlier messages. The alert box gives only
one button ‘OK’ to select and proceed.
Example:
<html>
<script type="text/javascript">
function warn() {
alert ("This is a warning message!");
}
</script>
<body>
<p> Click the following button to see the result: </p>
<form>
<input type= "button" value="Click me" onclick="warn(): "/>
</form>
</body>
</html>

By: Mukesh Kumar Sah 8


Registration No.: 782170170401

b. Confirmation Dialog Box


A confirmation dialog box is mostly used to take the user's consent on any option. It displays
a dialog box with two buttons: OK and Cancel.
Example:
<html>
<head>
<script type="text/javascript">
function getConfirmation() {
var ret Val = confirm ("Do you want to continue?");
if (ret Val == true) {
document.write("User wants to continue!");
return true;
}
else {
document.write("User does not want continue!");
return false;
}
}
</script>
</head>
<body>
<p> Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick= "getComfirmation():"/>
</form>
</body>
</html>

c. Prompt Dialog Box


The prompt dialog box is very useful when we want to pop-up a text box to get user input. It enables
us to interact with the user. The user needs to fill in the field and then click on OK.
This dialogue box is displayed using a method called prompt() which takes to parameters:
1. A label which we want to display in the textbox
2. A default string to display in the text box.
Example:
<html>
<head>
<script type = "text/javascript">
function getvalue() {
var ret Val = prompt ("Enter your name:", "Your name here");
document.write ("You have entered:" + ret Val);
}
</script>
</head>
<body>
<p> Click the following button to see the result: </p>
<form>
<input type = "button" value= "Click Me" onclick= "getvalue();"/>
</form>
</body>

By: Mukesh Kumar Sah 9


Registration No.: 782170170401

</html>

Form Validation
Form validation is a process of verifying whether the data entered by the user on the web
page its complete or not.
The data given by the user be sent to the server to check accuracy. If any mistake persists,
that has to be sent back to the user for correction. As this is a time taking process, the data will be
checked by JavaScript before submitting. This will save a lot of time.
Efficient web programming is possible only by making the information secure. JavaScript
forms authentication is defined as a process of validating the user credentials against some
authority. When the form is submitted without providing the data in the form field, JavaScript to show
a pop-up message restricting the form submission.
Example
<html>
<head>
<script>
function validateData()
{
var name=document. form1.user_name.value;
var password=document. form1.user_password.value;
if (name == null||name==")
{
alert ("Name can't be blank");
return false;
}
elseif (password. Length < 6) {
alert ("Password must be at least 6 character long.");
return false;
}
}
</script>
</head>
<body>
<form name="form 1" method="post" action="valid.php" onsubmit="return validateData()">
Username: <input type="text" name="user_name"><br><br>
Password: <input type="password" name="user_passsword"><br>
<input type="submit" value="register">
</form>
</body>
</html>
Output:

By: Mukesh Kumar Sah 10


Registration No.: 782170170401

Password retype validation using JavaScript


While registering or changing a password, we have to retype the password before
confirmation. Hence, our page should match the retype password. The following example shows the
validation process of retyped password using JavaScript.
Example:
<html>
<head>
<script type="text/javascript>
function matchPassword()
{
var pass1 = document. form1.password1.value;
var pass2 = document. form1.password2.value;
if (pass1 == pass2) {
return true;
}
else
{
alert ('password must be same!');
return false;
}
}
</script>
</head>
<body>
<form name="form1" method="post" action="match_password.php" onsubmit="return
matchPassword()">
Password: <input typr="password" name="password1"> <br><br>
Re-enter Passsword: <input type="password" name="password2">
</form>
</body>
</html>
Output:

By: Mukesh Kumar Sah 11


Registration No.: 782170170401

PHP
PHP
The PHP Hypertext Preprocessor is a programming language that allows web developers to
create dynamic content that interacts with databases. PHP is basically used for developing web-based
software applications. The product was initially named Personal Home Page. It is used to create web
applications in combining with the web server, such as Apache. PHP has nothing to do with layout,
events, and nothing about the look and feel of a web page. In fact, most of what PHP does invisible to
the user.
• PHP is an acronym for “PHP: Hypertext Preprocessor”.
• PHP is a widely used, open-source scripting language.
• PHP scripts are executed on the server.
• PHP is free to download and use.
• PHP 8 is used currently.
• PHP is free to use.
• PHP is easy to learn and write.
• Returns simple output to the client.
• PHP files have a file extension of “.php”.
• PHP runs on different platforms (Windows, Linux, Unix, etc.).

Variables:
Variables are containers for storing information. PHP variables are case sensitive. PHP is a
Loosely Typed Language. PHP automatically converts the variable to the correct data type, depending
on its value. In other languages such as C++, C and Java programmers must declare the name and type
of variable before using it.
In PHP, a variable is start with the sign $ followed by the name of the variable.
Example:
<?php
$txt = "Hello world!";
$x =5;
$y =10.5;
?>
PHP Variables Scope:
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part
where the variables can be referenced/used.
PHP has three different variable scopes:
a. Global Scope:
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Example:
Variable with a global scope:
<?php
$x=5;
function myTest() {
echo "<p> Variable x inside function is: $x</p>";

By: Mukesh Kumar Sah 12


Registration No.: 782170170401

}
myTest();
echo"<p> Variable x outside function is: $x </p>
?>
b. Local Scope
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that
function:
Example:
Variable with local scope:
<?php
function myTest();
$x =5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside this will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
PHP The global Keyword:
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x=5;
$y=10;
function myTest() {
global $x, $y;
$y=$x+$y;
}
myTest();
echo $y;
?>
Output
15

PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job. Example:
<?php
function myTest() {
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

PHP Constants:
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).

By: Mukesh Kumar Sah 13


Registration No.: 782170170401

Create a PHP constant


To create a constant, use the define () function.
Syntax
define (name, value, case sensitive)
Example:
<?php
define("GREETING", "Welcome to MIT!");
echo GREETING;
?>
PHP Constant Arrays
Example:
<?php
define("cars",[
"Alfa Romeo",
"BMW",
"Toyota"]);
echo cars[0];
?>
PHP String Function:
strlen() -- return the length of a string
Example:
<?
echo strlen("Hello World");
?>
Output:
12
str_word_count() -- count word in a string
<?php
echo str_word_count("Hello world!");
?>
Output:
2
PHP Math:
PHP pi() Function: -- The pi() function returns the value of PI.
Example:
<?php
echo(pi());
?>
Ouput:
3.1215926535898
PHP min() and max() Function: -- used to find the lowest or highest value in a list of arguments.
Example:
<?php
echo(min(0, 150, 30, 20, -8, -200);
echo(max(0, 150, 30, 20, -8, -200);
?>
Output:
-200
150
PHP abs() Function: -- PHP abs() Function returns the absolute (positive) value of a number.
Example:

By: Mukesh Kumar Sah 14


Registration No.: 782170170401

<?php
echo(abs(-607));
?>
Output:
6.7
PHP round() Function: -- PHP round() Function rounds a floating-point number to its nearest integer.
Example:
<?php
echo(round(0.60));
echo(round(0.49));
?>
Output:
1
0
PHP date() Function: converts timestamp to a more readable date and time format.
Example:
<?php
echo "Today's date is:";
$today= date("d/m/Y");
echo $today;
?>
Output:
Today's date is: 10/04/2022

Example:
<?php
echo date("h:i:s") . "\n";
echo date("M,d,Y h:i:s A") . "\n";
echo date("h:I a");
?>
Output:
09:33:07
Apr,10,2022 09:33:07 AM
09:33 am

PHP time() Function: used to get the current as a Unix timestamp.


Example:
<?php
$timestamp=time ();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
Output:
1649556391
April 10, 2022 07:53:47 AM

PHP echo and print statements


The PHP echo and print statement is often used to output data to the screen, echo and print
are more or less the same. They both are used to output the data to the screen.

By: Mukesh Kumar Sah 15


Registration No.: 782170170401

The difference is small: echo has no return value while print has a return value of 1 so it can be used
in expressions, echo can take multiple parameters (although such usage is rare) while print can take 1
argument, echo is marginally faster than print.
Example:
<html>
<head>
</head>
<body>
<?php
$str="Mukesh";
$x=5;
$y=4;
echo $x+$y;
print $str;
print "<br> what anice day!";
print "My teacher's name is $str";
?>

Operator
Operators are used to perform operations on variable and values. The operators used in PHP
and other programming language including JavaScript are similar. PHP divides the operators in the
following groups:
• Arithmetic operators (+, -, *, /, %, **)
• assignment operators (=, +=, -=, *=, /=, %=)
• comparison operators (==, ===, !=, <>, !==, >, <, >=, <=, <=>)
• increment decrement operators (++$x, $x++, --$x, $x--)
• logical operators (and, or, Xor, And, Or, ||, !)
• string operators (.=)
• conditional assignment operators (?:, ??)
PHP conditional statements
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different conditions. You
can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
1. PHP - the if statement
The if statement executes some code if one condition is true.
Syntax:
if (condition) {
code to be executed if condition is true;
}
Example:
<?php
$t=date("H");
if ($t<"20") {
echo "Have a good day!";
}
?>
Output:
18
Have a good day!

By: Mukesh Kumar Sah 16


Registration No.: 782170170401

2. PHP - The if …. else statement


The if …. else statement executes some code if a condition is true and another code if that
condition is false.
Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example:
<?php
$t=date("H");
if ($t<20) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output:
21
Have a good night!

3. PHP - The if … elseif …. else statement


The if … elseif …. else statement executes different codes for more than two conditions.
Syntax
if(condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if the all conditions are false;
}
Example:
<?php
$t=date("H");
if ($t<"10") {
echo "Have a good morning!";
} elseif ($t<"20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output:
9
Have a good morning

4. The PHP switch statement


The switch statement is used to perform different actions based on different conditions. The
switch statement to select one of many blocks of code to be executed.
Syntax:

By: Mukesh Kumar Sah 17


Registration No.: 782170170401

switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
…..
default:
code to be executed if n id different from all labels;
}
Example:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red";
echo "Your favorite color is red!";
break;
case "blue";
echo "Your favorite color is blue!";
break;
case "green";
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue nor green!";
}
?>
Output:
Your favorite color is red!

PHP Loops
Often when you write code, you want to the same block of code to run over and over again a
certain number of times. So, instead of adding several almost equal code-lines in a script, we can use
loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is
true.
In PHP, we have the following loop types:
1. The PHP while loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition is true) {
code to be executed;
}
Example:
<?php
$x=1;
while($x<=5) {

By: Mukesh Kumar Sah 18


Registration No.: 782170170401

echo "The number is: $x <br>";


$x++;
}
?>
Output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
2. The PHP do … while loop
The do … while loop will always execute the block of code once, it will then check the condition, and
repeat the loop while the specific condition is true.
Syntax:
do {
code to be executed;
} while (condition is true);
Example
<?php
$x=6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
Output:
The number is: 6
3. The PHP for loop
The for loop is used when you know in advance how many times the script should run.
Syntax:
for (initial counter; test counter; increment counter) {
code to be executed for each iteration;
}
Example
<?php
for ($x=0; $x<=50; $x+=10) {
echo "The number is: $x <br>";
}
?>
Output:
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
Nesting Loops
Nested loop is a loop within a loop, an inner loop within the body of an outer one.
Syntax:
for (expr.1; expr.2; expr.3) {
for (expr.1; expr.2; expr.3) {
}

By: Mukesh Kumar Sah 19


Registration No.: 782170170401

}
Example:
<?php
for ($i=1; $i<5; $i++) {
for ($j=1; $j<=$i; $j++) {
echo " * ";
}
echo "<br/>";
}
?>
Output
*
**
***
****
*****
PHP Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
Example:
<?php
for ($x=0; $x<10; $x++) {
if ($x==4) {
break;
}
Echo "The number is: $x <br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
PHP Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example:
<?php
for ($x=0; $x<5; $x++) {
if ($x==2) {
continue;
}
echo "The number is: $x<br>";
}
?>
Output:
The number is: 0
The number is: 1
The number is: 3
The number is: 4
PHP goto statement

By: Mukesh Kumar Sah 20


Registration No.: 782170170401

The go to statement is used to send flow program to a certain location in the code. The
location is specified by a user defined label. Generally, goto statement comes in the script as a part
of conditional expression such as if, else or case ( in switch construct).
Syntax:
statement1;
statement2;
if (expression)
goto label1;
statement3;
label1: statement4;
Example:
<?php
$x=0;
start:
$x++;
echo "x=$x\n";
if ($x<5)
goto start;
?>
Output:
x=1
x=2
x=3
x=4
x=5
PHP- A Simple HTML Form

PHP POST Method


This is the built in PHP super global array variable that is used to get values submitted via
DHTTP POST method. The array variable can be accessed from any script in the program; it has a global
scope. This method is ideal when you do not want to display the form post values in the URL. A good
example of using post method is when submitting login details to the server.
It has following syntax.
<?php
$_POST ['variable_name'];
?>
Example to illustrate the concept of POST method
File: Home.php
<html>
<head>
<title>Post Method </title>
</head>
<body>
<b> Post Method to Get value </b><br>
[POST method does not display the value send the URL]
<form action= "welcome.php" method= "post"><br>
Name: &nbsp; <input type= "text" name="name"><br><br>
E-mail: <input type="text" name="email"><br>
<input type= "submit" value="submit">
</form>
</body>

By: Mukesh Kumar Sah 21


Registration No.: 782170170401

</html>
File: welcome.php
<html>
<body>
Welcome <?php echo $POST ["name"]; ?><br>
Your email <?php echo $_POST ["email"]; ?>
</body>
</html>

PHP GET METHOD


This is the built in PHP super global array variable that is used to get values submitted via HTTP GET
method.
The array variable can be accessed from any script in the program; it has a global scope. This method
displays the form values in the URL. It's ideal for search engines from as it allows the users to
bookmark the results.
It has the following syntax.
<?php
$_ GET [ 'variable_name'];
?>
HERE,
"$_GET [….]" is the PHP array
"'variable_name"' is the URL variable name.
Example to illustrate the concept of GET method
File: Home.php
<html>
<head>
<title> Get Method </title>
</head>
<body>
<b> Get Method to Get Values</b><br>
[GET method displays the values send in the URL]
<form action="welcome.php" method="GET"><br>
Name: &nbsp; <input type="text" name="name"><br> <br>
E-mail: <input type="text" name="email"><br>
</form>
</body>
</html>
File: welcome.php
<html>
<body>
Welcome <?php echo $GET ["name"]; ?><br>
Your email <?php echo $_GET ["email"]; ?>
</body>
</html>

By: Mukesh Kumar Sah 22


Registration No.: 782170170401

C Programming Language - II
Function in C
Function
A function is a self-contained program segment or the block of statement that perform some
specific, well-defined task every C program comprises of one or more functions. The execution of any
program always begins by the executing the instructions in the main() functions.

Types of functions: Functions are of 2 types they are:


i. Library function
Library functions is pre-fined functions in a header file or pre-processor directive. Program can
use this function by simple adding header file in our program. They do not have to declare and defined
this function. For example, printf(), scanf(), getch(), strlen(), strupr(), pow(), sqrt() etc..
ii. User-defined function
A user defined function is declared, defined and used by the programmer according to their
need. The function contains following component:
i. Function declaration (prototype)
ii. Function call
iii. Function definition
iv. Return and void statement of the function.

i. Function declaration (prototype):


Function declaration or prototype is model or blue print of the function, which provides the
basic information about a function which tell the compiler then the function is used correctly or not.
If the function is used before, they are defined, then function declaration or prototype is necessary
for providing following information to the compiler.
Syntax: return_value function_name(parameter list);
e.g. int sum(int);
ii. Function call:
A function call is a statement that activates at the execution of the function when a function
call is encountered in the program, the control of the program jumped to the called function and
execution of the function starts.
Syntax:
i. Variable =function_name(argument_list);
ii. Function_name(argument_list);
e.g.
i. C = sum(a, b);
ii. area(r);
Example: To print square of a number using function.
# include<stdio.h>
int value(int); //function prototype
void main() //called function
{
int a, b;
printf(“ \n enter a number”);

By: Mukesh Kumar Sah 23


Registration No.: 782170170401

scanf(“%d”, &a);
b= value(a); //call function
}
int value (int a) //function declarator
{
int p; function body (called function)
P =a^ a
return (p);
}
iii. Function definition:
A function definition provides the actual body of the function. It contains the statements that
will be executed when the function is called. It contains function name, list of parameters, return type
of function and statement of the function.
Syntax:
data_type function_name(data_type arg1,data_type arg2......data typeargn)
{
declaration and statements
}
e.g.
int sum(int a, int b) //function declarator
{
int c;
c=a+ b; body of the function
return(c)
}
iv. Return and void statements of the function
Return statement: One of the main features of the function is that it can return the value to the calling
function. For this, a return keyword is used. So, return keyword return the program control from a
function to the calling function.
Syntax:
return expression:
Example:
int great (int a, int b)
{
if(a> b)
return a;
else
return b;
}
Void statement: If a function does not return a value, then we say that the function return type is
void. So, no expression is present if a return keyboard is used, then it is used to transfer the control at
the end of the function.
Syntax:
void function_name(data_type var)
Example:
void evenodd(int n)
{
if (n%2==0)
printf(“%d is even number”, n);
else
printf(“%d is odd number”, n);

By: Mukesh Kumar Sah 24


Registration No.: 782170170401

}
Example: WAP in c to find sum of two number using function.
Solution:
#include<stdio.h>
#include<conio.h>
int sum(int, int); //function declaration
void main()
{
int a, b, s;
printf(“enter two number:”);
scanf(“%d%d”, &a, &b);
s=sum(a, b); //function call
printf(“the sum is %d”, S);
getch();
}
int sum(int a, int b) //function definition
{
int add;
add =a+ b;
return add;
}
Output:
enter two number:
3
4
The sum is 7
Recursion:
The concept of using recursive function to repeat the execution of statements many times is
known as recursion.
Example: WAP in c to calculate factorial of user input number by using recursion.
Solution:
#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
int n, ans =0;
printf(“\n enter any number:”);
scanf(“%d”, &n);
ans = factorial(n);
printf(“ the factorial of %d is %d”, n ans);
getch();
factorial(int p)
{
if(p==1)
return(1);
else
return(p* factorial(p-1));
}
Output:
enter any number: 3

By: Mukesh Kumar Sah 25


Registration No.: 782170170401

the factorial of 3 is 6
STRUCTURE AND UNION
Introduction to structure
A structure is a collection of one or more variables, possible of different data types, grouped
together under a single name for convenient handling. Each data item is called member (elements,
field) of structure. The keyboard struct is used to declare structure.
Declaration of structure
Syntax:
Keyword structure name or tag

Struct user_defined_name
{
data-type member1;
data-type member2;
data-type member3;
-------------------------; Structure members
-------------------------;
-------------------------;
data-type-member n;
} structure variables;
Optional
Example of structure declaration:
A structure declaration to present information about a student’s name and other details.

struct student Or struct employee


{ {
int id; char name [35];
char name[30]; unsigned int age;
char gender; char address [50];
float marks[7]; float salary;
float total; } emp1, emp2;
float per;
int result;
};

Structure variable
A structure variable is a variable of a structure type. To declare a variable of type students,
defined earlier, write:
struct student st;
Initialization of structure
Like other variable and arrays, structure variable can be initialized where they are declared.
The format is quite similar to that used to initialized arrays. The initial values must appear in the order
in which they will be assigned to their corresponding structure members. Let us initialized structure
variable emp1, emp2 and emp3 as well in the above-mentioned example,
struct employee

By: Mukesh Kumar Sah 26


Registration No.: 782170170401

{
char name[35];
unsigned int age;
char address[50];
float salary;
} emp1= {“alpha”,20, “ktm”,15000.00};
emp2= {“beta”, 25,”jnp”, 20000.00};
struct employee emp3 ={“gamma”,25,”prk”,25000.00};

Size of structure
The elements of structure are always stored in contiguous memory location.
struct employee
char name[35];
unsigned int age;
char address[50];
float salary;
As we know every structure member takes its own memory. In the above example, name
takes 35 bytes. As we know that char takes 1 byte i.e., 35 char takes 35 bytes.

Example: A program to illustrate size of structure


#include<stdio.h>
#include<conio.h>
struct employee
{
char name[35];;
unsigned int age;
char address[50];
float salary;
};
void main()
{
unsigned int s;
clrscr();
s= size of (employee);
printf(“\n the size of structure is %u bytes”, s);
getch();
}
Output: The size of structure is 91 bytes.
Accessing structure elements
After the declaration of structure name and structure variable, let us see how the elements
can be accessed. The structure member of the structure is always referred to and accessed using the
structure variable.
Structure_variable.structure_member.
This structure member access pointer “.”, connects the structure name. for example, to print the
employee's name,
printf(“the employee’s name is %s”, empt.name);

By: Mukesh Kumar Sah 27


Registration No.: 782170170401

Note: we can access an individual member of a structure variable by using a dot (.) operator.

Example: WAP in c to read different structure variable and display them.


#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int roll;
char name[30];
char section;
float height;
} s1;
printf(“\n enter roll number:”);
scanf(“%d”, &s1.roll);
printf(“\n enter name:”);
gets(s1.name);
printf(“\n enter section:”);
scanf(“%c”,s1.section);
printf(“\n enter height:”);
scanf(“%f”,&s1.height);
printf(“\n you have entered: \n”);
printf(“Roll number %d name %s section \’%c’ and height is %f”, s1.roll, s1.name, s1.section, s1.height);
getch();
}
Output:
Enter roll number: 231
Enter name: Mukesh Kumar Sah
Enter section: E
Enter height: 5.02
You have entered:
Roll number 231 Name Mukesh Kumar Sah Section ‘E’ and Height is 5.0200000

UNION
Introduction to Union
Union is similar to structure but it is differing only its storage location. The ‘union’ keyword is used to
define union. In structure, each member has its own memory block whereas all member of union can
share same memory location. Union can take less amount of memory than structure and it can access only
one member at a time.
Declaration of union: OR:-
Union union_name union user defined as name
{ {
data type member variable1; data type member1;
data type member variable2; data type member2;
------------------------------------- ---------------------------

By: Mukesh Kumar Sah 28


Registration No.: 782170170401

------------------------------------- ---------------------------
------------------------------------ }
data type member variable n; union user_defined name var1,
}; var2; …………… var n;
Once union name is declared as new data type, then variables of that
type can be declared as
union union_name union_variable;
Example: Create a union named structure that has name, roll-no, marks, gender and phone-no as
members.
#include<stdio.h>
#include<conio.h>
union student
{
char name[20];
int roll_no;
float marks;
};
void main()
{
union student s;
clrscr();
printf(“enter the name:”);
gets(s.name);
printf(“name=%s \t”, s.name);
printf(“\n enter roll no:”);
scanf(“%d”, &s.roll);
printf(“\n Roll= %d”, s.roll);
s.marks =91.5;
printf(“\n marks= %2f”, s.marks);
getch();
}

POINTER
Pointer
A pointer is a variable which stores the address of another variable i.e., direct address of memory
location. The pointer variable might be any of the data type such as int, float, char, double etc.
Pointer Declaration:
Pointer variables like all other variables must be declared before they may be used in the c program.
We can use asterisk(*)to do so. Its general form is:
data type *pointer variable:
For example:
int *ptr;
This statement declares the variable ptr as a pointer to int, that is ptr can hold address of an integer
variable. Some examples of pointer declaration is as follows:
int*ip; //Pointer to as integer
double*dp; //Pointer to as double
float*fp; //Pointer to as float

By: Mukesh Kumar Sah 29


Registration No.: 782170170401

char*ch; //Pointer to as character

The Address (&) and indirection (*) operator:


The ‘&’ is the address operator and it represents the address of the variable and’*’ operator is the
value at the operator. It represents the value at the specified address.
Example,
int*p=&q;
In the above example, p returns the address of q to the variable p or we can simply say that p is a
variable which contains the address of an integer variable q. We can also declare as,
int*p;
In the above example, p is a pointer variable. We can use * for pointer variable.
Example: WAP in c to display the address and value of a variable using pointer.
Solution:-
#include<stdio.h>
#include<conio.h>
void main()
{
inti=3,*j;
j=&i;
clrscr();
printf("\n address of i=%u",j);
printf("\n value of i=%d",*j);
getch();
}
Output:
address of i=654978
value of i=3

Pointer Arithmetic
Pointer can be manipulated by arithmetic operators with integer values. These arithmetic operators
are only + and - and increment and decrement operator. The increment and decrement of pointer variable
depend on its data types.
Example: An example to illustrate pointer arithmetic.
#include<stdio.h>
#include<conio.h>
main()
{
int *p;
int age =17
p = &age;
printf("\n Value of age is %d", age);
printf("\n Increment of an age is%d", ++age);
printf("\n Address of age is%u", p);
printf("\n Increment in pointer is %u", ++p);
getch();
}
Output:
Value of age is 17

By: Mukesh Kumar Sah 30


Registration No.: 782170170401

Increment of an age is 18
Address of age is 284989
Increment of pointer is 284993

File Handling
File
A file is a collection of bytes stored on a secondary storage media, (i.e., hard disk, floppy disk, etc).
Files are used to store information permanently and to access and change that information whenever
necessary. C Programming has different types of library function for creating and managing data files.

Operating modes of files:


1. r: Opens files for reading or display/
2. w: open file for writing
3. a: opening file for appending.
4. rt: open an existing file for both reading and writing
5. wt: open new file for both reading and writing
6. at: open an existing file for both reading and appending.

Note:
Compiler automatically origins special character at the end of the file called EOF(end of file)

Defining and opening data file


The following syntax is used to define data file
FILE*fp;
fp = fopen(“file name”, “mode”);

The keyword FILE is used to declare filer data type. The first statement defines a file pointer variable
with a data type file. The second statement creates a file with name file name and returns memory
location(address) that is arrogated to the file pointer fp. The mode defines the purpose of the file
which can be read, written or append.

Closing data file


A data file must be closed after doing various operations such as reading, writing etc. it
ensures that all the information associated with the file is flushed out from the memory and all the
links to the file are broken. It also helps us to protect from accidental loss of data from the file. The
following syntax is used to close the file.
fclose(file pointer);
Opening, Reading, Writing and Appending on / from data file
1. Character input/output
I. fgetc()
It is used to read a single character from a data file [and returns the value of EOF]
Syntax: variable =getc(file pointer);
e.g., ch=fgetc(fp);
ii. fputc()
It is used to write a single character into a data file. [This function normally returns the
character written but will return value of EOF if error is encountered].
Syntax: put (character, file pointer);
fputc(ch,fp);

By: Mukesh Kumar Sah 31


Registration No.: 782170170401

2. String input/output
i. fgets()
It is used to read a set of character as a string from a given file and copies the string to a given
memory location normally in array.
Syntax
fgets(sptr,n,ptr);

When sptr =pointer to the location to receive string.


n = count maximum number of characters to be in the string.
ptr = pointer to the file to be read
ii. fputs()
It is used to write a string to a given file.
Syntax
fputs(sptr,ptr);

where, sptr = pointer to the string to be written.


Ptr = pointer to file.
3. Word input/output
i. getw()
It is used to read an integer value from a given file.
Syntax
getw(fp);
variable= getw(file pointer);
ii. putw()
It is used to write an integer quality on the specified file;
Syntax
putw(w,fp)

where w is an integer value and fp is file pointer.


4. Formatted input/output
i. fscan
It is used to read a formatted data from a specified file.
Syntax
fscanf:-(ptr, “control string”, list);

where ptr is file pointer, control is different format like %d%f etc and list is variable parasfeter list to
be read from specified file.
ii. fprintf():- It is used to write a formatted data into a given file.
Syntax
fprintf(ptr, control spring”, list);
when ptr is the file pointer, control spring is a formatted command and list is a variable parameter list
record.
5. Block input/output
i. fwrite()
It is used to write a binary data to a given file.
Syntax
fwrite(ptr, size, n items, fptr);

where, ptr = pointer that is first structure to be written.


size = size in bytes of each structure.
nitems = number of structures to be written.

By: Mukesh Kumar Sah 32


Registration No.: 782170170401

fptr = file pointer to the file.


ii. fread()
It is used to read a block of binary data from a given file.
Syntax
fread(ptr,size,n items,fptr);

Step for writing a file


1. Create a file pointer.
2. Open file in write (w or a) made.
3. Perform general I/O operation.
4. Same I/O results using following syntax.
fprintf (file-pointer, “format specifier lists”, variable list);
5.Close the file using fclose(file-pointer)

Example: To store data in a file


#include<stdio.h>
#include<conio.h>
void main()
{
int age;
char name[20];
file *fp;
printf(”enter age:”);
scanf(“%d”,&age);
fprintf(fp,”%s %d “, name, age);
fclose(fp);
// returno;
getch();
}

Step for reading a file


1. Create a file pointer.
2. Open file in read mode (r mode).
3. Read the data from the file using following syntax:
fscanf (file-pointer, “format specifier list”, variable list);
4.Display data as required.
5. Close the file using fclose(file-pointer)

Example: To display the contact of a file


#include<stdio.h>
#include<conio.h>
void main()
{
int age;
char name[20];
file *fp;
fp= fopen(“in & o.dat”,”r”);
fscanf(fp, “%s %d”, name,&age);
printf(“your name is %s”, name);
printf(your age is %d”, age);
fclose(fp);

By: Mukesh Kumar Sah 33


Registration No.: 782170170401

//returno;
getch();
}

Example
1. WAP in c which writes “welcome to Nepal” in a file.
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
file*fp;
fp= fopen(“NEPAL.DAT”,”w”);
fprintf(fp,”%s” “welcome to Nepal”);
fclose(fp);
getch();
}

2. WAP in c which needs name, roll number and age from a file named “student.dat” and display
them
Solution:
#include<stdio.h>
#include<conio.h>
void main()
{
int rn,age;
char name[25];
file*fp
fp= fopen(“student.dat”, “r”);
printf(“\n name \t Roll number \t age \n”);
printf(“\n……………………….\n”);
fscanf(fp, “%s %d %d “, name, &rn, &age);
/*reads first record*/ while(!feof (fp))
{
printf(“\n %s \t %d \t %d”,name, rn, age);
fscan(fp, %s %d %d”,name,&rn,&age);
/*reads remaining records*/
}
fclose(fp);
getch();
}

By: Mukesh Kumar Sah 34

You might also like