Month: September 2014

Basic HTML document

Posted on

1

<!DOCTYPEhtml>

<html>

<body>

<h1>MyFirstHeading</h1>

<p>Myfirstparagraph.</p>

</body>

</html>

ThebasicstructureofanHTMLdocument

HTMLdocumentsaremadeupofelementscalledtags,whichdefinethepresentationofthewebpage.MosttagsinanHTMLdocumentmustbefollowedsomewhereinthefilewithaclosingtag.

Forexample:

Thisisanopeningtag:<blockquote>Thisisaclosingtag:</blockquote>

Notethatthedifferencebetweenthesetwotagsisonlythepresenceofaforwardslashaftertheopeningbracketofthetag.Theforwardslashiswhatmakesthisaclosingtag.

NearlyeveryHTMLpageiswritteninthisbasicformat:

<html>

<head>

<title>PageTitle</title>

</head>

<body>

Themainpartofthedocumentgoeshere.

</body>

</html>

EveryHTMLdocumentmustincludetheopening<html>tagatthetopofthefile,andtheclosing</html>tagattheveryendofthefile.

Beneaththeopeninghtmltagyou’llfindthe<head>section.Hereyouwillplaceyourwebpagekeywords,description,andpagetitle.

The<head>elementisacontainerforalltheheadelements.Elementsinside<head>canincludescripts,instructthebrowserwheretofindstylesheets,providemetainformation,andmore.

Thefollowingtagscanbeaddedtotheheadsection:<title>,<style>,

<meta>,<link>,<script>,<noscript>,and<base>.

The<title>Element

The<title>tagdefinesthetitleofthedocument.

The<title>elementisrequiredinallHTML/XHTML documents.The<title>element:

  • definesatitleinthebrowsertoolbar
  • providesatitleforthepagewhenitisaddedtofavorites

displaysatitleforthepageinsearch-engineresults

2

HTMLheadingsaredefinedwiththe<h1>to<h6>tags:<h1>definesthemostimportantheading.<h6>definestheleastimportantheading.

Note:Browsersautomaticallyaddsomeemptyspace(amargin)beforeandaftereachheading.

HeadingsAreImportant

  • UseHTMLheadingsforheadingsonly.Don’tuseheadingstomake

text BIGorbold.

  • Searchenginesuseyourheadingstoindexthestructureandcontent

ofyourwebpages.

  • Sinceusersmayskimyourpagesbyitsheadings,itisimportantto

useheadingstoshowthedocumentstructure.

  • H1headingsshouldbeusedasmainheadings,followedbyH2head-

ings, then the lessimportant H3 headings, andso on.

Example

<h1>Thisisaheading</h1>

<h2>Thisisaheading</h2>

<h3>Thisisaheading</h3>

Paragraphs

HTMLparagraphsaredefinedwiththe<p>tag:Example

<p>Thisisaparagraph.</p>

<p>Thisisanotherparagraph.</p>

TheHTML<a>tagdefinesahyperlink.

Ahyperlink(orlink)isaword,groupofwords,orimagethatyoucanclickontojumptoanotherdocument.

WhenyoumovethecursoroveralinkinaWebpage,thearrow willturn into alittlehand.

Themostimportantattributeofthe<a>elementisthehrefattribute,whichindicatesthelink’sdestination.

Bydefault,linkswillappearasfollowsinallbrowsers:

  • Anunvisitedlinkisunderlinedandblue
  • Avisitedlinkisunderlinedandpurple
  • Anactivelinkisunderlinedandred

Example

<ahref=”http://www.w3schools.com“>Thisis alink</a>Thelinkaddressisspecifiedinthehrefattribute

Images

3

HTMLImages

HTMLimagesaredefinedwiththe<img>tag.

Thesourcefile(src),alternativetext(alt),andsize(widthandheight)areallprovidedasattributes:Example

<html>

<imgsrc=”sunset.jpg”width=”500″height=”250″>

</html>

4

HTMLHorizontalLines

The<hr>tagcreatesahorizontallineinanHTMLpage.Thehrelementcanbeusedtoseparatecontent:Example

<!DOCTYPEhtml>

<html>

<body>

<p>Thisisaparagraph.</p>

<hr>

<p>Thisisaparagraph.</p>

<hr>

<p>Thisisaparagraph.</p>

</body>

</html>

5

  • Usethe<br>tagifyouwantalinebreak(anewline)withoutstartinganew

paragraph:Example

<!DOCTYPEhtml>

<html>

<body>

<h1><p>Thisis<br>apara<br>graphwithlinebreaks</p></h1>

</body>

</html>

6

<!DOCTYPEhtml>

<html><body>

<p><b>Thistextisbold</b></p>

<p><strong>Thistextisstrong</strong></p>

<p><i>Thistextisitalic</i></p>

<p><em>Thistextisemphasized</em></p>

<p><code>Thisiscomputeroutput</code></p>

<p>Thisis<sub>subscript</sub>and<sup>superscript</sup></p>

</body>

</html>

Commenttags<!–and–>areusedtoinsertcommentsinHTML.

HTMLCommentTags

YoucanaddcommentstoyourHTMLsourcebyusingthefollowingsyntax:

<!–Writeyourcommentshere–>

Commentsarenotdisplayedbythebrowser,buttheycanhelpdocumentyourHTML.

WithcommentsyoucanplacenotificationsandremindersinyourHTML:Example

<!–Thisisacomment–>

<p>Thisisaparagraph.</p>

<!–Remembertoaddmoreinformationhere–>

7

HTMLTablewithoutborderexample

  • Tablesare definedwiththe<table>t
  • Tablesaredividedintotablerowswiththe<tr>t
  • Tablerowsaredividedintotabledatawiththe<td>t
  • A tablerowcanalso be dividedintotableheadings with the <th>t

Tabledata<td>arethedatacontainersofthetable.

TheycancontainallsortsofHTMLelementsliketext,images,lists,othertables,etc

Example

<html><body>

<tablestyle=”width:100%”>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

</table>

</body>

</html>

Ifyoudonotspecifyaborderforthetable,itwillbedisplayedwithoutborders.

Abordercanbeaddedusingtheborderattribute:Example

<html><body>

<tableborder=”1″style=”width:20%”>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

</table>

</body></html>

8

Ifyouwanttheborderstocollapseintooneborder,addCSSborder-collapse:

<!DOCTYPEhtml>

<html><head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

</style>

</head>

<body>

<tablestyle=”width:20%”>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

<tr>

<td>John</td>

<td>Doe</td>

<td>80</td>

</tr>

</table></body>

</html>

Teble With Cell Padding :

9

Cellpaddingspecifiesthespacebetweenthecellcontentanditsborders.Ifyoudonotspecifyapadding,thetablecellswillbedisplayedwithoutpadding.

Tosetthe padding, usethe CSS padding property:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

th,td{padding:15px;}

</style>

</head>

<body>

<tablestyle=”width:100%”>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

<tr>

<td>John</td>

<td>Doe</td>

<td>80</td>

</tr>

</table>

<p>Trytochangethepaddingto5px.</p>

</body>

</html>

Table Headings :

10

Tableheadingsaredefinedwiththe<th>tag.

Bydefault,allmajorbrowsersdisplaytableheadingsasboldandcentered:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

th,td{padding:5px;}

</style>

</head>

<body>

<tablestyle=”width:100%”>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>Points</th>

</tr>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

<tr>

<td>John</td>

<td>Doe</td>

<td>80</td>

</tr>

</table>

</body>

</html>

Table with Border spacing :

11

Borderspacingspecifiesthespacebetweenthecells.

Tosettheborderspacingforatable,usetheCSSborder-spacingproperty:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;padding:5px;

}

table{border-spacing:15px;}

</style>

</head>

<body>

<tablestyle=”width:20%”>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

<tr>

<td>John</td>

<td>Doe</td>

<td>80</td>

</tr>

</table>

<p>Trytochangetheborder-spacingto5px.</p>

</body>

</html>

TableCellsthatSpanmanyColumns:

13

Tomakeacellspanmorethanonecolumn,usethecolspanattribute:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

th,td{

padding:5px;

text-align:left;

}

</style>

</head>

<body>

<h2>Cellthatspanstwocolumns:</h2>

<tablestyle=”width:20%”>

<tr>

<th>Name</th>

<thcolspan=”2″>Telephone</th>

</tr>

<tr>

<td>BillGates</td>

<td>55577854</td>

<td>55577855</td>

</tr>

</table>

</body>

</html>

TableCellsthatSpanmanyRows:

14

Tomakeacellspanmorethanonerow,usetherowspanattribute:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

th,td{

padding:5px;

text-align:left;

}

</style>

</head>

<body>

<h2>Cellthatspanstworows:</h2>

<tablestyle=”width:20%”>

<tr>

<th>FirstName:</th>

<td>BillGates</td>

</tr>

<tr>

<throwspan=”2″>Telephone:</th>

<td>55577854</td>

</tr>

<tr>

<td>55577855</td>

</tr>

</table>

</body>

</html>

TableWithaCaption:

15

AnHTMLTableWithaCaption

Toaddacaptiontoatable,usethe<caption>tag:

<!DOCTYPEhtml>

<html>

<head>

<style>

table,th,td{

border:1pxsolidblack;

border-collapse:collapse;

}

th,td{

padding:5px;

text-align:left;

}

</style>

</head>

<body>

<tablestyle=”width:20%”>

<caption>Monthlysavings</caption>

<tr>

<th>Month</th>

<th>Savings</th>

</tr>

<tr>

<td>January</td>

<td>$100</td>

</tr>

<tr>

<td>February</td>

<td>$50</td>

</tr>

</table>

</body>

</html>

DescriptionList:

1

Adescriptionlist,isalistofterms,withadescriptionofeachterm.

The<dl>tagdefinesadescriptionlist.

The<dt>tagdefinestheterm(name),andthe<dd>tagdefinesthedata(description).

DescriptionList:

<!DOCTYPEhtml>

<html>

<body>

<h2>ADescriptionList:</h2>

<dl>

<dt>Coffee</dt>

<dd>-blackhotdrink</dd>

<dt>Milk</dt>

<dd>-whitecolddrink</dd>

</dl>

</body>

</html>

2

Astyleattributecanbeaddedtoanunorderedlist,todefinethestyleofthemarker:

<!DOCTYPEhtml>

<html>

<body>

<h2>Discbullets</h2>

<ulstyle=”list-style-type:disc”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>

<h2>Circlebullets</h2>

<ulstyle=”list-style-type:circle”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>

<h2>Squarebullets</h2>

<ulstyle=”list-style-type:square”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>

</body>

</html>

Style Description
list-style-type:disc Thelistitemswillbemarkedwithbullets(default)
list-style-type:circle Thelistitemswillbemarkedwithcircles
list-style-type:square Thelistitemswillbemarkedwithsquares

OrderedList-StyleAttribute :

3

Atypeattributecanbeaddedtoanorderedlist,todefinethetypeofthemarker:

<!DOCTYPEhtml>

<html>

<body>

<h4>Numberedlist:</h4>

<ol>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Letterslist:</h4>

<oltype=”A”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Lowercaseletterslist:</h4>

<oltype=”a”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Romannumberslist:</h4>

<oltype=”I”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>LowercaseRomannumberslist:</h4>

<oltype=”i”>

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

</body>

</html>

Type Description
type=”1″ Thelistitemswillbenumberedwith numbers (default)
type=”A” Thelistitemswill benumberedwith uppercaseletters
type=”a” Thelistitemswill benumberedwith lowercaseletters
type=”I” Thelistitemswill benumberedwith uppercaseromannumbers
type=”i” Thelistitemswill benumberedwith lowercaseromannumbers

NestedList:

1

Listcanbenested(listsinsidelists).

<!DOCTYPEhtml>

<html>

<body>

<h2>A nestedList:</h2>

<ul>

<li>Coffee</li>

<li>Tea

<ul>

<li>Blacktea</li>

<li>Greentea</li>

</ul>

</li>

<li>Milk</li>

</ul>

</body>

</html>

NOTE:Listitems can containnew list, and otherHTMLelements, like images and links, etc.

HTML formsareusedtopassdatato aserver.

AnHTMLformcancontaininputelementsliketextfields,checkboxes,radio-buttons,submitbuttonsandmore.Aformcanalsocontainselectlists,textarea,fieldset,legend,andlabelelements.

The<form>tagisusedtocreateanHTMLform:

<form>

inputelements

</form>

Forms – TheInput Element

Themostimportantformelementisthe<input>element.The<input>elementisusedtoselectuserinformation.

An<input> element canvary inmany ways,dependingonthetypeattribute.An<input>elementcanbeoftypetextfield,checkbox,password,radiobutton,submitbutton,andmore.

Themostcommoninputtypesaredescribedbelow.

Forms-TextFields

2

<inputtype=”text”>definesaone-lineinputfieldthatausercan

entertextinto:

<form>

Firstname:<inputtype=”text”name=”firstname”><br>Lastname:<inputtype=”text”name=”lastname”>

</form>

Note:Theformitselfisnotvisible.Alsonotethatthedefault

widthofatextfieldis20characters.

1

<inputtype=”password”>definesapasswordfield:

<form>

Password:<inputtype=”password”name=”pwd”>

</form>

Note:Thecharactersinapasswordfieldaremasked(shownasasterisksorcircles).

Forms-RadioButton

2

<inputtype=”radio”>definesaradiobutton.Radiobuttonsletauser

selectONLYONE of alimitednumber of choices:

<form>

<inputtype=”radio”name=”sex”value=”male”>Male<br>

<inputtype=”radio”name=”sex”value=”female”>Female

</form>

Forms-Checkboxes

3

<inputtype=”checkbox”>definesacheckbox. Checkboxesletauser select

ZEROorMOREoptions ofalimitednumberofchoices.

<form>

<input type=”checkbox”name=”vehicle” value=”Bike”>Ihavea bike<br>

<inputtype=”checkbox”name=”vehicle”value=”Car”>Ihaveacar

</form>

Forms-SubmitButton :

4

<inputtype=”submit”>definesasubmitbutton.

Asubmitbuttonisusedtosendformdatatoaserver.Thedataissenttothepagespecifiedintheform’sactionattribute.Thefiledefinedintheactionattributeusuallydoessomethingwiththereceivedinput:

<formname=”input”action=”demo_form_action.asp”method=”get”>

Username:<inputtype=”text”name=”user”>

<inputtype=”submit”value=”Submit”>

</form>

Ifyoutypesomecharactersinthetextfieldabove,andclickthe”Submit”button,thebrowserwillsendyourinputtoapagecalled”demo_form_action.asp”.Thepagewillshowyouthereceivedinput.

WorkingwithForms

<html>

<head>

<title>WORKINGWITHFORMS</title>

<body>

<formname=”input”action=”Nested.html”method=”get”>

<b>FirstName:</b><inputtype=”text”name=”firstname”><br>

<b>LastName:</b><inputtype=”text”name=”lastname”><br>

<b>Password:</b><inputtype=”password”name=”pwd”><br>

<b>Address:&nbsp&nbsp</b><inputtype=”textarea”name=”add”><br>

<inputtype=”radio”name=”sex”value=”male”>Male<br>

<inputtype=”radio”name=”sex”value=”female”>Female<br>

<input type=”checkbox”name=”vehicle” value=”Bike”>Ihavea bike<br>

<inputtype=”checkbox”name=”vehicle”value=”Car”>Ihaveacar

<inputtype=”submit”value=”Submit”>

</form>

</body>

</head>

</html>

HTMLframesareusedtodivideyourbrowserwindowintomultiplesectionswhereeach section can load aseparateHTML document. Acollectionofframesinthebrowserwindowisknownasaframeset.Thewindowisdividedintoframesinasimilarwaythetablesareorganized:intorowsandcolumns.

<!DOCTYPEhtml>

<html>

<head>

<title>HTMLFrames</title>

</head>

<framesetrows=”10%,10%,10%”>

<framename=”top”src=”t1.html”/>

<framename=”main”src=”t2.html”/>

<framename=”bottom”src=”t3.html”/>

<noframes>

</frameset>

</html>

Frames-Columns

<!DOCTYPEhtml>

<html>

<framesetcols=”25%,50%,25%”>

<framesrc=”t1.html”>

<framesrc=”t2.html”>

<framesrc=”t3.html”>

</frameset>

</html>

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Advertisements

Array, String, Date &Time function

Posted on Updated on

Arrays

An array stores multiple values in one single variable:

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

Example

<?php
$cars=array(“Volvo”,”BMW”,”Toyota”);
echo “I like ” . $cars[0] . “, ” . $cars[1] . ” and ” . $cars[2] . “.”;
?>

O/P: I like Volvo, BMW and Toyota.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

  • Numeric array – An array with a numeric index. Values are stored and accessed in linear fashion
  • Associative array – An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  • Multidimensional array – An array containing one or more arrays and values are accessed using multiple indices

Numeric Array

These arrays can store numbers, strings and any object but their index will be prepresented by numbers. By default array index starts from zero.

Example

Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>

<body>

<?php

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )

{

echo “Value is $value <br />”;

}

/* Second method to create array. */

$numbers[0] = “one”;

$numbers[1] = “two”;

$numbers[2] = “three”;

$numbers[3] = “four”;

$numbers[4] = “five”;

foreach( $numbers as $value )

{

echo “Value is $value <br />”;

}

?>

</body>

</html>

This will produce following result:

Value is 1Value is 2Value is 3Value is 4Value is 5Value is oneValue is twoValue is threeValue is fourValue is five

Associative Arrays

The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.

To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.

NOTE: Don’t keep associative array inside double quote while printing otheriwse it would not return any value.

Example

1

This will produce following result:

2

Multidimensional Arrays

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects:

This example is an associative array, you can create numeric array in the same fashion.

3

This will produce following result:

4

String Concatenation Operator

To concatenate two string variables together, use the dot (.) operator:

5

If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.

Between the two string variables we added a string with a single character, an empty space, to separate the two variables.

Using the strlen() function

The strlen() function is used to find the length of a string.

Let’s find the length of our string “Hello world!”:

<?php

echo strlen(“Hello world!”);

?>

This will produce following result:

12

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)

Using the strpos() function

The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

Let’s see if we can find the string “world” in our string:

<?php

echo strpos(“Hello world!”,”world”);

?>

This will produce following result:

6

As you see the position of the string “world” in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.

Date and Time

The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

Syntax

date(format,timestamp)

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Get a Simple Date

The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)
  • l (lowercase ‘L’) – Represents the day of the week

Other characters, like”/”, “.”, or “-” can also be inserted between the characters to add additional formatting.

The example below formats today’s date in three different ways:

Example

<?php
echo “Today is ” . date(“Y/m/d”) . “<br>”;
echo “Today is ” . date(“Y.m.d”) . “<br>”;
echo “Today is ” . date(“Y-m-d”) . “<br>”;
echo “Today is ” . date(“l”);
?>

O/P:

Today is 2014/08/23
Today is 2014.08.23
Today is 2014-08-23
Today is Saturday

Get a Simple Time

Here are some characters that is commonly used for times:

  • h – 12-hour format of an hour with leading zeros (01 to 12)
  • i – Minutes with leading zeros (00 to 59)
  • s – Seconds with leading zeros (00 to 59)
  • a – Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:

Example

<?php
echo “The time is ” . date(“h:i:sa”);
?>

O/P: The time is 05:42:07am

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Operator, Control Structure

Posted on

PHP Operators

This chapter shows the different operators that can be used in PHP scripts.

PHP Arithmetic Operators

Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
Subtraction $x – $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y

The example below shows the different results of using the different arithmetic operators:

Example

<?php
$x=10;
$y=6;
echo ($x + $y); // outputs 16
echo ($x – $y); // outputs 4
echo ($x * $y); // outputs 60
echo ($x / $y); // outputs 1.6666666666667
echo ($x % $y); // outputs 4
?>

1

PHP Assignment Operators

The PHP assignment operators is used to write a value to a variable.

The basic assignment operator in PHP is “=”. It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Same as… Description
x = y x = y The left operand gets set to the value of the expression on the right
x += y x = x + y Addition
x -= y x = x – y Subtraction
x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus

The example below shows the different results of using the different assignment operators:

Example

<?php
$x=10;
echo $x; // outputs 10
$y=20;
$y += 100;
echo $y; // outputs 120
$z=50;
$z -= 25;
echo $z; // outputs 25
$i=5;
$i *= 6;
echo $i; // outputs 30
$j=10;
$j /= 5;
echo $j; // outputs 2
$k=15;
$k %= 4;
echo $k; // outputs 3
?>

PHP String Operators

Operator Name Example Result
. Concatenation $txt1 = “Hello”
$txt2 = $txt1 . ” world!”
Now $txt2 contains “Hello world!”
.= Concatenation assignment $txt1 = “Hello”
$txt1 .= ” world!”
Now $txt1 contains “Hello world!”

The example below shows the results of using the string operators:

Example

<?php
$a = “Hello”;
$b = $a . ” world!”;
echo $b; // outputs Hello world!
$x=”Hello”;
$x .= ” world!”;
echo $x; // outputs Hello world!
?>

PHP Increment / Decrement Operators

Operator Name      Description
++$x Pre-increment      Increments $x by one, then returns $x
$x++ Post-increment     Returns $x, then increments $x by one
–$x Pre-decrement     Decrements $x by one, then returns $x
$x– Post-decrement     Returns $x, then decrements $x by one

The example below shows the different results of using the different increment/decrement operators:

Example

<?php
$x=10;
echo ++$x; // outputs 11
$y=10;
echo $y++; // outputs 10
$z=5;
echo –$z; // outputs 4
$i=5;
echo $i–; // outputs 5
?>

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or string):

Operator Name Example Result
== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y True if $x is greater than $y
< Less than $x < $y True if $x is less than $y
>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y
<= Less than or equal to $x <= $y True if $x is less than or equal to $y

The example below shows the different results of using some of the comparison operators:

Example

<?php
$x=100;
$y=”100″;
var_dump($x == $y); // returns true because values are equal
echo “<br>”;
var_dump($x === $y); // returns false because types are not equal
echo “<br>”;
var_dump($x != $y); // returns false because values are equal
echo “<br>”;
var_dump($x !== $y); // returns true because types are not equal
echo “<br>”;
$a=50;
$b=90;
var_dump($a > $b);
echo “<br>”;
var_dump($a <  $b);
?>

PHP Logical Operators

Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP Array Operators

The PHP array operators are used to compare arrays:

Operator Name Example Result
+ Union $x + $y Union of $x and $y (but duplicate keys are not overwritten)
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non-identity $x !== $y True if $x is not identical to $y

The example below shows the different results of using the different array operators:

<?php
$x = array(“a” => “red”, “b” => “green”);
$y = array(“c” => “blue”, “d” => “yellow”);
$z = $x + $y; // union of $x and $y
var_dump($z);
echo “<br>”;
var_dump($x == $y);
echo “<br>”;
var_dump($x === $y);
echo “<br>”;
var_dump($x != $y);
echo “<br>”;
var_dump($x <> $y);
echo “<br>”;
var_dump($x !== $y);
?>

O/P: array(4) { [“a”]=> string(3) “red” [“b”]=> string(5) “green” [“c”]=> string(4) “blue” [“d”]=> string(6) “yellow” }
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)

Control StructureConditional statements are used to perform different actions based on different conditions.

PHP Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

In PHP we have the following conditional statements:

  • if statement – executes some code only if a specified condition is true
  • if…else statement – executes some code if a condition is true and another code if the condition is false
  • if…elseif….else statement – selects one of several blocks of code to be executed
  • switch statement – selects one of many blocks of code to be executed

PHP – The if Statement

The if statement is used to execute some code only if a specified condition is true.

Syntax

if (condition) {
code to be executed if condition is true
;
}

The example below will output “Have a good day!” if the current time (HOUR) is less than 20:

Example

<?php
$t=date(“H”);

if ($t<“20”) {
echo “Have a good day!”;
}
?>

PHP – The if…else Statement

Use the if….else statement to execute some code if a condition is true and another code if the condition is false.

Syntax

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output “Have a good day!” if the current time is less than 20, and “Have a good night!” otherwise:

Example

<?php
$t=date(“H”);

if ($t<“20”) {
echo “Have a good day!”;
} else {
echo “Have a good night!”;
}
?>

PHP – The if…elseif….else Statement

Use the if….elseif…else statement to select one of several blocks of code to be executed.

Syntax

if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

The example below will output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the current time is less than 20. Otherwise it will output “Have a good night!”:

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!”;
}
?>

 Switch Statement

The switch statement is used to perform different actions based on different conditions.

The PHP switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

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 is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.

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, or green!”;
}
?>

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;
}

The example below first sets a variable $x to 1 ($x=1;). Then, the while loop will continue to run as long as $x is less than, or equal to 5. $x will increase by 1 each time the loop runs ($x++;):

Example

<?php
$x=1;
while($x<=5) {
echo “The number is: $x <br>”;
$x++;
}
?>

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 specified condition is true.

Syntax

do {
  code to be executed;
} while (condition is true);

The example below first sets a variable $x to 1 ($x=1;). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

Example

<?php
$x=1;
do {
echo “The number is: $x <br>”;
$x++;
} while ($x<=5);
?>

Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition fails the first time.

The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:

Example

<?php
$x=6;
do {
echo “The number is: $x <br>”;
$x++;
} while ($x<=5);
?>

The PHP for Loop

PHP for loops execute a block of code a specified number of times.

The for loop is used when you know in advance how many times the script should run.

Syntax

for (init counter; test counter; increment counter) {
code to be executed;
}

Parameters:

  • init counter: Initialize the loop counter value
  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example

<?php
for ($x=0; $x<=10; $x++) {
echo “The number is: $x <br>”;
}
?>

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value) {
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

The following example demonstrates a loop that will output the values of the given array ($colors):

Example

<?php
$colors = array(“red”,”green”,”blue”,”yellow”);
foreach ($colors as $value) {
echo “$value <br>”;
}
?>

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Php, Php Variable, Php Constant

Posted on

What is PHP?

  • 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 costs nothing, it is free to download and use.

What is a PHP File?

  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension “.php”

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data

Why PHP?

  • PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP supports a wide range of databases
  • PHP is free. Download it from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

What Do I Need?

To start using PHP, you can:

  • Find a web host with PHP and MySQL support
  • Install a web server on your own PC, and then install PHP and MySQL

Basic PHP Syntax

  • A PHP script can be placed anywhere in the document.
  • A PHP script starts with <?php and ends with ?>:
  • <?php
    // PHP code goes here
    ?>

PHP Variables

As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case sensitive ($y and $Y are two different variables)

NOTE:  Remember that PHP variable names are case-sensitive!

Creating (Declaring) PHP Variables

PHP has no command for declaring a variable.

A variable is created the moment you first assign a value to it:

Example

<?php
$txt=”Hello world!”;
$x=5;
$y=10.5;
?>

5

After the execution of the statements above, the variable txt will hold the value Hello world!, the variable x will hold the value 5, and the variable y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the value.

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically converts the variable to the correct data type, depending on its value.

In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

  • local
  • global
  • static

Example

<?php
$x=5; // global scope

function myTest() {
$y=10; // local scope
echo “<p>Test variables inside the function:</p>”;
echo “Variable x is: $x”;
echo “<br>”;
echo “Variable y is: $y”;
}
myTest();
echo “<p>Test variables outside the function:</p>”;
echo “Variable x is: $x”;
echo “<br>”;
echo “Variable y is: $y”;
?>

In the example above there are two variables $x and $y and a function myTest(). $x is a global variable since it is declared outside the function and $y is a local variable since it is created inside the function.

When we output the values of the two variables inside the myTest() function, it prints the value of $y as it is the locally declared, but cannot print the value of $x since it is created outside the function.

Then, when we output the values of the two variables outside the myTest() function, it prints the value of $x, but cannot print the value of $y since it is a local variable and it is created inside the myTest() function.

NOTE: You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

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.

To do this, use the static keyword when you first declare the variable:

Example

<?php
function myTest() {
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

1

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.

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).

Note: Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant

To set a constant, use the define() function – it takes three parameters: The first parameter defines the name of the constant, the second parameter defines the value of the constant, and the optional third parameter specifies whether the constant name should be case-insensitive. Default is false.

Example

<?php
define(“GREETING”, “Welcome to W3Schools.com!”, true);
echo greeting;
?>

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Php Fuction,Regular Expression

Posted on

PHP Functions:

The real power of PHP comes from its functions; it has more than 1000 built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, we can create our own functions.

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.

Create a User Defined Function in PHP

A user defined function declaration starts with the word “function”:

Syntax

function functionName() {
  code to be executed;
}

Note: A function name can start with a letter or underscore (not a number).

In the example below, we create a function named “writeMsg()”. The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The function outputs “Hello world!”. To call the function, just write its name:

Example

<?php
function writeMsg() {
echo “Hello world!”;
}
writeMsg(); // call the function
?>

1

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just seperate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

<?php
function familyName($fname) {
echo “$fname Refsnes.<br>”;
}
familyName(“Jani”);
familyName(“Hege”);
familyName(“Stale”);
familyName(“Kai Jim”);
familyName(“Borge”);
?>

2

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

<?php
function setHeight($minheight=50) {
echo “The height is : $minheight <br>”;
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

3

PHP -Regular Expressions

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality.

Using regular expression you can search a particular string inside a another string, you can replace one string by another string and you can split a string into many chunks.

PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.

  • POSIX Regular Expressions
  • PERL Style Regular Expressions

POSIX Regular Expressions:

The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions.

The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag.

PHP’s Regexp POSIX Functions

PHP currently offers seven functions for searching strings using POSIX-style regular expressions:

Function Description
ereg() The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
eregi() The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive.
eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
split() The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string.
spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters.

PERL Style Regular Expressions:

Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section.

PHP’s Regexp PERL Compatible Functions

PHP offers following functions for searching strings using Perl-compatible regular expressions:

Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

Data Type in C, C Operators

Posted on

In the C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted

The types in C can be classified as follows:

S.N. Types and Description
1 Basic Types:
They are arithmetic types and consists of the two types: (a) integer types and (b) floating-point types.
2 Enumerated types:
They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program.
3 The type void:
The type specifier void indicates that no value is available.
4 Derived types:
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function’s return value. We will see basic types in the following section, whereas, other types will be covered in the upcoming chapters.

Integer Types

Following table gives you details about standard integer types with its storage sizes and value ranges:

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

#include<stdio.h>

#include<limits.h>

int main()

{

printf(“Storage size for int : %d \n”,sizeof(int));

return0;

}

When you compile and execute the above program it produces the following result on Linux:

Storage size for int : 4

Floating-Point Types

Following table gives you details about standard floating-point types with storage sizes and value ranges and their precision:

Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values:

#include<stdio.h>

#include<float.h>

int main()

{

printf(“Storage size for float : %d \n”,sizeof(float));

printf(“Minimum float positive value: %E\n”, FLT_MIN );

printf(“Maximum float positive value: %E\n”, FLT_MAX );

printf(“Precision value: %d\n”, FLT_DIG );

return0;

}

When you compile and execute the above program, it produces the following result on Linux:

Storage size for float : 4

Minimum float positive value: 1.175494E-38

Maximum float positive value: 3.402823E+38

Precision value: 6

The void Type

The void type specifies that no value is available. It is used in three kinds of situations:

S.N. Types and Description
1 Function returns as void
There are various functions in C which do not return value or you can say they return void. A function with no return value has the return type as void. For example void exit (int status);
2 Function arguments as void
There are various functions in C which do not accept any parameter. A function with no parameter can accept as a void. For example, int rand(void);
3 Pointers to void 
A pointer of type void * represents the address of an object, but not its type. For example a memory allocation function void *malloc(size_t size ); returns a pointer to void which can be casted to any data type.

The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in the upcoming chapters.

C – Operators and Expressions

  • The symbols which are used to perform logical and mathematical operations in a C program are called C operators.1
  • These C operators join individual constants and variables to form expressions.
  • Operators, functions, constants and variables are combined together to form expressions.
  • Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant and A + B * 5 is an expression.

Types of C operators:

C language offers many types of operators. They are,

    1. Arithmetic operators
    2. Assignment operators
    3. Relational operators
    4. Logical operators
    5. Bit wise operators
    6. Conditional operators (ternary operators)
    7. Increment/decrement operators
    8. Special operators

Arithmetic Operators in C:

    • C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus in C programs.
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B

Assignment operators in C:

    • In C programs, values for the variables are assigned using assignment operators.
    • For example, if the value “10″ is to be assigned for the variable “sum”, it can be assigned as “sum = 10;”
    • Other assignment operators in C language are given below.
Operators Example  Explanation 
Simple assignment operator = sum=10 10 is assigned to variable sum
Compound assignment operators += sum+=10 This_is_same_as_sum=sum+10…………
-= sum-=10 This is same as sum = sum-10
*= sum*=10 This is same as sum = sum*10
/+ sum/=10 This is same as sum = sum/10
%= sum%=10 This is same as sum = sum%10
&= sum&=10 This is same as sum = sum&10
^= sum^=10 This is same as sum = sum^10

Relational operators in C:

    • Relational operators are used to find the relation between two variables. i.e. to compare the values of two variables in a C program.
S.no Operators Example  Description
1 > x > y x is greater than y
2 < x < y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y

Logical operators in C:

    • These operators are used to perform logical operations on the given expressions.
    • There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no Operators Name Example Description
1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
3 ! logical NOT !((x>5)&&(y<5)) It reverses the state of the operand “((x>5) && (y<5))”

If “((x>5) && (y<5))” is true, logical NOT operator makes it false

Bit wise operators in C:

    • These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.
    • Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).
 x y  x|y x & y x ^ y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift

Conditional or ternary operators in C:

    • Conditional operators return one value if condition is true and returns another value is condition is false.
    • This operator is also called as ternary operator.

Syntax     :        (Condition? true_value: false_value);

Example :        (A > 100  ?  0  :  1);

    • In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements.

C – Increment/decrement Operators

  • Increment operators are used to increase the value of the variable by one and decrement operators are used to decrease the value of the variable by one in C programs.
  • Example:

Increment operator :     ++ i ;    i ++ ;

Decrement operator:     – – i ;    i – – ;

Difference between pre/post increment & decrement operators in C:

    • Below table will explain the difference between pre/post increment and decrement operators in C.
 S.no Operator type Operator Description
1 Pre increment ++i Value of i is incremented before assigning it to variable i.
2 Post-increment i++ Value of i is incremented after assigning it to variable i.
3 Pre decrement – –i Value of i is decremented before assigning it to variable i.
4 Post_decrement i– – Value of i is decremented after assigning it to variable i.

Special Operators in C:

    • Below are some of special operators that C language offers.
 S.no Operators Description
1 & This is used to get the address of the variable.

Example : &a will give address of a.

2 * This is used as pointer to a variable.

Example : * a  where, * is pointer to the variable a.

3 Sizeof () This gives the size of the variable.

Example : size of (char) will give us 18u.

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com

HISTORY OF C, VARIABLES

Posted on

HISTORY OF C

C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972.

In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard.

The UNIX operating system, the C compiler, and essentially all UNIX applications programs have been written in C. The C has now become a widely used professional language for various reasons.

  • Easy to learn
  • Structured language
  • It produces efficient programs.
  • It can handle low-level activities.
  • It can be compiled on a variety of computer platforms.

Facts about C

  • C was invented to write an operating system called UNIX.
  • C is a successor of B language which was introduced around 1970
  • The language was formalized in 1988 by the American National Standard Institute (ANSI).
  • The UNIX OS was totally written in C by 1973.
  • Today C is the most widely used and popular System Programming Language.
  • Most of the state-of-the-art softwares have been implemented using C.
  • Today’s most popular Linux OS and RBDMS MySQL have been written in C.

Why to use C?

C was initially used for system development work, in particular the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:

  • Operating Systems
  • Language Compilers
  • Assemblers
  • Text Editors
  • Print Spoolers
  • Network Drivers
  • Modern Programs
  • Databases
  • Language Interpreters
  • Utilities

C Programs

A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with extension “.c”; for example, hello.c. You can use “vi”“vim” or any other text editor to write your C program into a file.

This tutorial assumes that you know how to edit a text file and how to write source code inside a program file.

What is Variable in C Programming

Variable in C Programming is also called as container to store the data. Variable name may have different data types to identify the type of value stored. Suppose we declare variable of type integer then it can store only integer values.Variable is considered as one of the building block of C Programming which is also called as identifier.

A Variable is a name given to the memory location where the actual data is stored.

Consider real time example , suppose we need to store water then we can store water in glass if quantity of water is small and Bucket is the quantity of water is large. And big can to store water having quantity larger than bucket similarly Variable (i.e Value container) may have different size for storing different verities of values.

What is Variable in C Programming?

  1. Initially 5 is Stored in memory location and name x is given to it
  2. After We are assigning the new value (3) to the same memory location
  3. This would Overwrite the earlier value 5 since memory location can hold only one value at a time
  4. Since the location ‘x’can hold Different values at different time so it is refered as ‘Variable
  5. In short Variable is name given to Specific memory location or Group.

1

What is Local Variable ?

  1. Local Variable is Variable having Local Scope.
  2. Local Variable is accessible only from function or block in which it is declared .
  3. Local variable is given Higher Priority than the Global Variable.

Above Fig.  Tells us that – Above Program has 2 blocks i.e Inner Block and Outer Block

Facts about Local Variable :

  1. Variables declared inside outer block are visible or meaningful only inside outer block.
    • Example : var1 is Local to Outer Block.
    • var1 cannot be accessed from its outer block.
    • var1 cannot be accessed from Other Function or other block
    • var1 can be accessed from inner block
  2. Similarly Variables declared inside inner block are visible or meaningful only inside Inner block.
  3. Variables declared inside inner block are not accessed by outer block .i.e

2

#include<stdio.h>

voidmain()

{

int var1=10;

{

int var2 =20;

printf(“%d%d”,var1,var2);// Legal : var1 can be accessed

}

printf(“%d%d”,var1,var2);// Error : var2 is not declared

}

Short Summary :

Inner Block can access variables declared inside Outer Block

Outer block can’t access variables declared inside

Posted By-: Vissicomp Technology Pvt. Ltd.

Website -: http://www.vissicomp.com