A A
facebookacebook twitterwitter rssRSS

Welcome! BUHTH is a Web Development Blog featuring news, tutorials and tips on web development, web programming, web design and much more. You may want to follow this blog via RSS, Facebook and Twitter (top buttons^) or subscribe to our free email newsletter (on right ->).

>> Thursday, February 7, 2013

Introduction to PHP


Static and Dynamic websites

We consider that there are 2 types of websites: static sites and dynamic sites.

Static sites are ites that are created with ​​HTML and CSS. They work very well but their contents can not be updated automatically, it is necessary that the owner of the site (the webmaster) modifies the source code to add new features. This is not very practical when you have to update a site several times in the same day! This type of site is increasingly rare today, because as soon as we add an element of interaction (such as a contact form), we no longer speak of a static site but dynamic site.

Dynamic websites are more complex, they use other languages ​​in addition to HTML and CSS, such as PHP and MySQL. The contents of these websites are called "dynamic" because it can change without the intervention of the webmaster! Most of the websites that you visit today are dynamic sites. The only prerequisite to learn how to create this type of site is to already know how to make static sites in HTML and CSS.

The objective of this course is to make you able to make dynamic websites completely by yourself, step by step. In fact, it can provide functionalities much more exciting than static sites. Here are some things you will be able to achieve:

Members area: Your visitors can subscribe to your site and have access to sections reserved for them.

Forum: It is common today to see websites which offer a forum for mutual support and discussions.

Visitor counter: You can easily count the number of visitors who have logged in
on your site, or even know the number of visitors in general!

News: You can automate the writing of news, giving your visitors the ability to compose,comment, etc..

Newsletter: You can send an e-mail to all your members regularly to present the new posts and thus encourage them to return to your site.

Of course, these are only some examples. It is possible to go even further, depending on your needs. know for instance that almost all social network sites are dynamic.

But ... Do not get carried away. Before we get there, you have to read and have a lot to learn!

Start with the basics: do you know what happens when you visit a web page?

How does a website function

When you want to visit a website, you type its address in your web browser, either Mozilla Firefox, Internet Explorer, Opera, Safari or other. But have you ever wondered how the web page get to you?

You should know that the Internet is a network of computers. These can be classified into two categories:

Clients: computers are Internet users like you. Your computer is therefore part of the category of clients. Each client is a visitor to a website.

Servers: are powerful computers that store and deliver web sites to users, that is to say the customers. Most Internet users have never seen a server in their livea. However, the servers are essential for the proper functioning of the web.

Most of the time, the server has no screen: it stays on and works alone without human intervention,24h/24, 7/7. A real slave labor.

We summarize: your computer is called the client, while the computer that holds the web site is called the server. how both communicate?

It is precisely here that there is a difference between a static website and a dynamic website. Let's see together what they are.\

A static website

When the site is static, the pattern is very simple. This happens in two stages:
1. The client asks the server to view a web page.
2. The server responds by sending the requested page.


Communication is basic:
"Hello, I am the client, I would like to see this web page."
"Look, here's the page you requested me."

On a static site, nothing happens. The server stores the web pages and sends them to clients who request them without change.

A dynamic website

When the site is dynamic, there is an intermediate step: the page is generated.
1. The client asks the server to view a web page.
2. The server prepares the page specifically for the client.
3. The server sends the page that is generated.


The web page is generated whenever a client requests it. This is precisely what makes dynamic websites alive: the content of a page may change from one moment to another.

This is how some sites are able to display, for example your nickname on all pages. given the server generates a page every time you ask him for one, he can customize to suit the tastes and visitor's preferences (and display his nickname among others).

Web languages

When creating a website, it is necessary to handle not one but several languages. As a webmaster, it is imperative to know.

Some programs, called WYSIWYG (What You See Is What You Get) allow novices to
create static websites without knowing any programming languages ​​behind ... But to achieve a dynamic site as we wish, we will definitely need to get involved in the programming sides.

For a static website

Many languages ​​have been created to produce websites. Two of them are an essential basis for All webmasters:
1. HTML is the basic language for websites.
<p>Hello. This is my new website!</p>

2. CSS is the language for formatting websites. While HTML allows you to write the content of your webpages and the structure, the CSS takes care of the formatting and layout. CSS is what we choose including color, size, menus and many other things. Here is an example of CSS code:
div.banner {
text-align: center;
font-weight: bold ;
font-size: 120%;
}

These languages ​​are the basis of all websites. When the server sends the web page to the client, it actually sends the code back in HTML and CSS.


The problem is that when we only know HTML and CSS, we can only produce static sites ... and not Dynamic sites! For the latter, it is necessary to handle other languages ​​in addition to HTML and CSS.

The question we must ask is: do i know HTML and CSS?
If so, this is perfect, you can continue because we will need it later. If the answer is no, do not panic. these languages ​​are not very difficult, they are within the reach of all. You can learn by reading our course on HTML and CSS.

Know that learning these languages ​​is a matter of a few weeks, or even less if you have enough free time.

For a dynamic website we add PHP and MySQL

Whatever the website that you want to create, HTML and CSS are essential. However, they are not sufficient to make dynamic websites. They ust be complemented with other languages. It is exactly the whole purpose of this course you will learn to handle PHP and MySQL to make a website dynamic.

PHP: is a language that only servers understand and can make your site dynamic. This is PHP "generates" the web page as seen on a previous schemes.

This will be the first language we'll discover in this course. It can work alone, but it is really interesting when combined with tool such as MySQL. Here is a PHP code:
<?php echo "You are visitor n°" . $num_visitors; ?>

MySQL: this is called a DBMS (Database Management System). Its role is
to store data in an organized manner to help you find them easily later. It is thanks to MySQL you can save the list of members of your site, posts on the forum, etc.. the
language to communicate with the database called SQL. Here is a code in SQL:
SELECT id , author, message, datemsg FROM list ORDER BY
datemsg DESC LIMIT 0, 10

PHP and MySQL are freewares. Among other things, it guarantees sustainability: everyone can contribute to its development, you may not see all webmasters ignore the PHP and MySQL overnight, and this is very important! On the other hand, PHP and MySQL are available. This means one essential thing: you do not have to pay a dime to build your website.

PHP can be used alone and is sufficient to create a dynamic site, but things get really interesting when it is combine with a DBMS such as MySQL. However, for simplicity, for the moment forget MySQL and lets focus on PHP.

The role of PHP is precisely to generate HTML (You can also generate the CSS, but it's rare), code is sent to the client in the same way of that of a static website:

PHP is a programming language used on many servers to make decisions. PHP is who decides the HTML code that will be generated and sent to the client each time.

To understand the value of this, consider an example. You can write in PHP: "If the visitor is a member of my site and his name is Jane, display 'Welcome Jane' to the web page. However, if it is not a member of my site show 'Welcome to the site' and offer the visitor to 'register'. This is a very basic example of dynamic site: whether you are a registered member or not, you will not see the same things and may not have access to all sections.

Rivals of PHP and MySQL

HTML and CSS are not rivals because they are standards. Everyone is supposed to know them and use them on all websites.

In contrast to what is dynamic websites, PHP and MySQL are far from being alone. We cannot make a complete list of their rivals, it would be too long (and boring!). However, for your general culture you should at least know a few other big names.

Firstly, if there is a tendency to combine PHP and MySQL to make powerful dynamic sites, we should not mix the two. PHP has different rivals compared to MySQL.

Rivals of PHP

Among the rivals of PHP, we get:
ASP.NET: designed by Microsoft, it uses the .NET framework familiar to C# developers (a framework is a set of libraries that provide services for developers). This language can be interesting if you have the habit of developing in C#. NET and you do not want not be disoriented.

Ruby on Rails: active, this framework can be used with the Ruby language and allows to create dynamic sites very fast by following certain conventions.

Django: it is similar to Ruby on Rails, but it uses the Python language.

Java and JSP (Java Server Pages) more commonly called "JEE". It is particularly used in the world of professionals. It requires a certain rigor. Implementation of a project JEE is traditionally a little more longer and heavier but the system is appreciated by professionals and institutions (this is what is used on the Site of taxes, for example).

We can not present all the rivals, but this should already give you a good notion. For information, it is also possible to use eg C or C++, although it is more complex and not necessarily always adapted (clear, We do not recommend it at all).

Which one is better?
Given the purpose of this course, you expect me to answer that "PHP" instantly . But no. In fact, all depends on your programming skills. If you already know Java , you'll soon feel comfortable with JSP. If you know Python, Django seems entirely appropriate.

As for PHP, it distinguishes itself from its competitors by a large community that can help you quickly on the internet if you have problems. This is an easy language to use, ideal for beginners and professionals alike:
Wikipedia and Facebook are examples of famous landmarks that work with PHP.

In short, there is no better choice. We recommend the language in which you are most certain to get helped with. PHP in this sense is often a very good choice.

Rivals of MySQL

Regarding databases, the choice is still very large.

However, while PHP and its competitors are mostly free and open source, this is not the case for most DBMS.

Among the competitors MySQL, I advise you to know (at least in name):
Oracle DBMS is the most famous, the most complete and the most powerful. Unfortunately it is not free (and expensive), It is used heavily by large companies. However, there are free versions of Oracle especially for those who want to learn how to use it.

Microsoft SQL Server: published by Microsoft, and is often used in
combination with ASP.NET, although it can be used with any other language. It is not free, but there are limited free versions.

PostgreSQL: it is free and a DBMS such as MySQL, which offers more advanced features. Sometimes compared to Oracle, it remains some way to go. It has a community a little less important as MySQL and Oracle.

SQLite: DBMS is the simplest and smallest. It is free and open source but has very little functionality. Its advantage is being lightweight.

Again, this list is far from complete but presents at least a few big names.

Ultimately, if your resources are limited, you do not have many choices for the DBMS. MySQL is the most appropriate because it is free, effective and used by many people who are likely to help you.

Combinations are possible

As you can see, you have the choice between many tools to achieve a dynamic site. Most
of them are free.

Note that you can combine these tools as you see fit. For example, one can easily use PHP with another database, such as Oracle or PostgreSQL. Similarly, MySQL can be used with any other language: Java, Python, Ruby, etc..

However, the combination "PHP + MySQL" is probably the most common. It is not by chance that this course addresses these two tools that have proven their worth.

You should now have a good idea of what PHP and MySQL allow us to do. If you can remember that PHP generates personalized HTML for each visitor and that MySQL store data, you already know the principal.

In the first part of this course we will discover PHP smoothly. We therefore put MySQL aside and will not be storing data in a first time. Once you have acquired a certain level in PHP, we will talk about MySQL and then we can start making very interesting features for your future site.

____________________
Read this tutorial in french

>> Friday, January 18, 2013

Simple Technology Blogger Template 2013

I had this template for quite a while and wanted to share it. So here I present to you a simple and yet strong and efficient technology blogger template.

See Demo | Download Template

Template Features:
Posts auto-collapsed and thumbnails are auto-create
Search bar
Next - Previous - Home buttons
Facebook - Twitter - RSS buttons
SEO compatible
Favicon
Subscibtion by Email
Popular post widget
Adddthis share buttons integrated inside posts
All images are hosted on blogger itself
Template can be edited in blogger template designer

All of these are customizable.

Edit header
If there isn't a HTML/JavaScript gadget on top in the edit layout section, you'll add one and insert the code below into. Then insert the code below into it (after you place your links) and save the gadget.

Logo is 300 x 100

<table border="0" width="100%"><tr>
<td align="left" width="50%"><a href="ABOUT-PAGE-LINK"/>About</a> | <a href="CONTACT-PAGE-LINK">Contact</a></td>
<td width="50%" align="right"><a href="YOUR-FEED-LINK"><img src="http://2.bp.blogspot.com/-zr76jtU6QKg/TWoxmSvoe_I/AAAAAAAAAU8/E6rN0wOfnf8/s320/rss24.png" /></a> <a href="YOUR-TWITTER-LINK"><img src="http://2.bp.blogspot.com/-D2UrENKXEoc/TWoxmsmPITI/AAAAAAAAAVE/E8qOy5jIA-s/s320/twitter24.png" /></a> <a href="YOUR-FACEBOOK-LINK" /></a></td>
</tr>
</table>

<table broder="0" width="100%" height="100"><tr>
<td align="left" width="50%"><a href="YOUR-BLOG-LINK"><img src="LOGO-LINK"/></a></td>
<td align="right" width="50%">
<form id="searchthis" action="YOUR-BLOG-LINK/search" style="display:inline;" method="get">
<input id="b-query" maxlength="255" name="q" size="30" type="text"/>
<input id="b-searchbtn" value="Search" type="submit"/>
</form>
</td>
</tr>
</table>

Sidebars
Any blogger gadget can be added

Footers
There are three columns and you can add what you want.


>> Wednesday, January 16, 2013

Remove the quickedit buttons from blogger

The blogger quickedit buttons are very useful when someone need to edit a gadget from his template. But for users like me who code directly from the template and edit the component from the back-end, after editing and because i am logged in to my blogger account i see a lot of these buttons while viewing my template. And to be frank i got irritated by them as i want to see the clean template i just edited. Of course the quickedit buttons are not visible to the visitors and when you're yourself logged out of your blogger account.

So how do we remove these quickedit buttons?


Step 1
Logged in to you blogger account and lick on the blog you want to edit if you have several blogs.

Step 2
Click on "Template" link as shown is the image below:


Then click on "Edit HTML" on its right, under "Live on Blog".

Step 3
Once the edit HTML window is popped up, check the "Expand Widget Templates" as show below:


Step 4
Hold CTRL+F together on your keyboard to open the find box on your browser. On firefox it should look like:


Step 5
Search for this code below in the find box of your browser

<b:include name='quickedit'/>

Step 6
When found!


Erase the code from the template!

Step 7
To remove all the quickedit buttons, search for all of the code similarly in the template (click "Next" on the find bar/box in your browser) and remove all the code when they show up.

Step 8
Save your template and you're done.

Now even when you're logged in your blogger account you won't encounter the quickedit buttons.

>> Friday, January 11, 2013

Blogger do delete blogs that violate their terms

I had a blog set up on blogger.com with a custom domain name whereby i was promoting some amazon products to generate affiliate revenues. The blog had run for about a year and now its gone. This morning i got this beautiful email from blogger informing me that my blog has been deleted for SPAM:

Hello, Your blog at http://www.blogurl.com/ has been reviewed and confirmed as in violation of our Terms of Service for: SPAM. In accordance to these terms, we've removed the blog and the URL is no longer accessible. For more information, please review the following resources: Blogger Terms of Service: http://blogger.com/terms.g Blogger Content Policy: http://blogger.com/go/contentpolicy -The Blogger Team

With some seo practice I've been able to sell like 1 or 2 products per month. I know it's not huge but I've been able to cover the domain cost and my effort to upload like hundreds of products with my affiliate links.

Resolution
Set up a wordpress and install a shopping cart on it. Shopperpress seems to be a great solution to sell amazon products via affilate. Hence, yes you'll need to pay for hosting but it will be yours and no one can remove the blog except you.

>> Monday, December 24, 2012

Will the touch screen overcome the mouse?


V/S

Nowadays most of us has a PC, tablet PC or other devices which uses touch screen. In this article we'll try to compare classic computers which uses a mouse and devices which uses touch screen.

Mouse

Advantages of using a mouse
- Precision in editing word documents and spreadsheets
- Ability to work faster
- Ease when using (we don't get tired easily)
- Easy copy and paste

And I can't think of any disadvantage.

Touch Screen

Advantages of a touch screen
- Innovative and awesome
- Do what one usually do with the mouse
- Easy to use

Disadvantages of a touch screen
- Hands get tired quickly after some minutes, how many would let hand up in front of him for more than 5 minutes without it start to loose strength?
- Make copy and paste a nightmare
- Lack of precision even with the pen

Future of Mouse devices
It seems that in the near future most screen will be touch screens. But I don't think we can replace the mouse with our fingers. The cursor works better just as we can't play some game without a game controller.

So do you agree with me that our finger touch is far away from replacing a mouse click? Discuss your views below : )

>> Wednesday, May 30, 2012

C programming: Introduction to Arrays

Arrays are very useful when you need to process multiple data which have the same characteristics. They can be numbers, integers etc but they must be of the same type and class of storage.

Arrays are defined similarly to normal variables but has a slight difference. Lets see an example:

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

int main()
{
int name[5];

name[0]=123;
name[1]=646;
name[2]=233;
name[3]=678;
name[4]=231;

printf("%d\n", name[1]);
return 0;
}

Explanation
Here the type of our array is int and the name of our array is name itself. Then we defined the number of elements into our array. Here it is 5 and it is enclosed with [square brackets].
The computer will count the 5 elements in the array as 0 to 4 and not 1 to 5.
Then we have defined each of the five elements by assigning value to it.
A printf statement is created and name[1] is the selected element.
Compiling this will display 646 on the screen.

Suppose you were to print name[5], you'll get a number not known to you as you haven't defined name[5]. Remember that variables dealt with your computer memory and whatever we write as variable is stored there temporarily.


A simpler way to write arrays


int main()
{
int name[5]={123, 646, 233, 678, 231};


printf("%d\n", name[0]);
return 0;
}


Explanation
Here we've put an = and we've put the values of each elements of the array into a { curly brackets } separated with commas. But remember the first element is not 1 but 0. So compile the above with name[0] in our printf and you should get 123.

Now suppose you're making a program but don't know how many elements the array would contain as the user would enter a the number of elements. You just have to leave the [square bracket] blank, like this:
int name[]={123, 646, 233, 678, 231};

Let's add some more elements to it:

int name[]={123, 646, 233, 678, 231, 56, 43, 12, 89, 234};

Again the element start with 0, so if we were to look for the 6th element which is 56, our printf should contain name[5], like this:

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

int main()
{
int name[]={123, 646, 233, 678, 231, 56, 43, 12, 89, 234};

printf("%d\n", name[5]);
return 0;
}

The result of this should be 56.

Example of an array program

Let's make a program which will add the elements in the array.


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

int main()
{
int name[10]={123, 646, 233, 678, 231, 56, 43, 12, 89, 234};
int i;
int sum=0;

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

sum += name[i];

}


printf("The sum is %d\n", sum);

return 0;

}

Explanation
There are 10 elements in our array.
We have created a variable i and another one sum initializing it with 0.
We have made a for loop which you already know about. The program will loop ten times the element 0 to 9 and will add them and will store them in our variable sum, and finally display it as ordered in the printf.


Tabular loop array program

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

int main()
{
int name[10]={123, 646, 233, 678, 231, 56, 43, 12, 89, 234};
int i;

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

name[i];

}


printf("%s%13s\n","Element", "Value");


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

printf("%7d%13d\n", i, name[i]);

}


return 0;

}

Result:

Explanation
In this program only the two printf lines are new to you, so let's explain this:
printf("%s%13s\n","Element", "Value");

%s%13s tells the program to leave 13 spaces for the characters: Element and Value. 7 for Element 1 for a space in between and 5 for Value = 13, then we've wrote Element and Value in double quote.

the other printf line:
printf("%7d%13d\n", i, name[i]);
%7d tell the program to display the looping of 0 to 9 the characters space away, that is, unders the letter "t" of the word "Element" and 13%d tell the program to display the looping of the elements in the array 13 characters away, that is under the letter "e" of the word "Value". Note that to get the above result you must put \n so that the looping is done on the next line each time it loops.

So that was a bit on array with some examples, practice it by changing the values, and keep in touch for more tutorials and samples on C. Go to All C tutorials.

>> Saturday, May 26, 2012

C programming: Random number function and how to seed them

Random numbers is very useful and wildly use in many programs. To get a random number we use rand(), see example:

int main()
{
printf("%d\n", rand());
return 0;
}

Your computer will display a random number.

Now let's display several random number using the while loop function:

int main()
{
int num;

while (num <=10) {

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

num++;

}

return 0;

}



Now suppose you want the remainder of these numbers, you have to change to printf line to this:
printf("%d\n", rand()%5);

However big the random number is, you'll get the remainder of the 10 numbers from 0 to 4. If you put %9, you'll get the remainders from 0 to 8 and so on.

Now what if you don't want 0? then you need to add 1+ before the rand() and you'll get remainder from 1 to 5, and not 0 to 4, we do it like this:
printf("%d\n", 1+rand()%5);

In short the +1 is what number you want to start with and, so if you want to start with 3, then you write 3+. Notice that when we had %5 and +1, the remainders was 1 to 5 instead of 1 to 4, because the it has added 1 to the 4 which is default for %5. Similarly if we write 3+rand()%10, then our remainders will be between 3 to 12.

Seeding Random Numbers


You should have notice that the numbers returned by the computer are them same each time starting with 41 and so on. This looks like random numbers but in fact follow an algorithm and calculate and display these numbers which is random for the computer each time but not for us as we see the same thing each time it is run. We can change this a bit by seeding random numbers instead. See example:

int main()
{
int num;
srand(11);

while (num <=10) {

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

num++;

}

return 0;

}



The srand function is used to seed random numbers and its value is not necessary 11, it can be any other number. But here again each time you run this program you'll get the same numbers starting with 74. So how can we get different random numbers each time the program is run? To do this we should set our srand function time to NULL as shown below:|
int main()
{
int num;
srand(time(NULL));

while (num <=10) {

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

num++;

}

return 0;

}



Now try to compile and run this again and again, and you'll see that you'll get different numbers each time.

So that was a bit on random numbers and how to seed them, you may not find this useful now but in the coming tutorials you'll see how we will apply this to get results. So in short you have to know it. Go to all C Tutorials.

>> Friday, May 25, 2012

C programming: Introduction to functions

A function is a self-contained program segment that carries out some specific, well-defined task. Every C program consists of one or more functions. One of these functions must be called main, which is executed first. This is a very important part of our series in C programming because most of what come next will be based on functions.

Till here, we have been writing our codes in the main function between its { curly brackets }. This is because the programs we've made are short but normally a program has many functions which used each other to work. Functions acts like modules and keep everything neat.

How to call a function in C


Let's see how to call a function. For example we write a function and how do we access it from our main function. See a simple example:

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

int main()
{
int num1;
int num2;
scanf("%d%d", &num1, &num2);
printf("%d", sum(num1, num2));

return 0;
}

int sum(int x, int y)
{
return x + y;
}


Explanation
In the above code, we have two functions: main and sum
What's in the main function is what you have already learn previously except what is in red in the printf (i.e sum ...)
Then in the function sum we have put int x and int y in ( bracket) which are parameters, and in the the { curly bracket } we have return x + y;
When the program is executed and when it arrives to the line printf and see "sum" which is not a variable, so how can it calculate num1 and num2? So here it sees another function called sum and call it.

Another example:
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num = 0, triplenum = 0;

printf("Enter a number: ");
scanf("%d", &num);

triplenum = triple(num);
printf("The triple of this number is %d\n", triplenum);

return 0;
}
int triple(int x)
{
return 3 * x;
}

Explanation
This program will calculate the triple of a number entered by a user.
In this example we have two functions namely, main and triple.
We have only one parameter in triple which is int x, the return is 3 multiply by x.
So when the program arrive at this line:
triplenum = triple(num);

and it dont see a variable called triple it look for a function when found the function, it look for what it returns. Here it return 3 time the value entered by the user from the variable num.

We can simplify the above code to this:

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

int main()
{
int num = 0;

printf("Enter a number: ");
scanf("%d", &num);
printf("The triple of this number is %d\n", triple(num));

return 0;
}

int triple(int x)
{
return 3 * x;
}

Explanation
In this one the triple(num) is in the printf directly. It is more simple and easier. So this line has been removed:
triplenum = triple(num);

The function triple and the rest is the same.


A converter using function

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

double convert(double USD)
{
double euros = 0;

euros = 0.798849656 * USD; // May 26 2012
return euros;
}

int main()
{
printf("1 USD = %f Euros\n", convert(1));
printf("10 USD = %f Euros\n", convert(10));
printf("50 USD = %f Euros\n", convert(50));
printf("100 USD = %f Euros\n", convert(100));
printf("200 USD = %f Euros\n", convert(200));

return 0;
}

Explanation
Here we have use double instead of int for decimal numbers.
The value in red multiply the conversion to that value.


Void function


This type of function is used whereby nothing is returned. For example just to display something on the screen:
void Hello()
{
printf("Hello World");
}

int main()
{
Hello (1);
return 0;
}

The void function doesn't have a return.

Void function with looping

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

void number(int times)
{
int lines;

for (lines = 0 ; lines < times ; lines++)

{

printf("This program has written this line you're reading 15 times\n");

}

}


int main()
{
number(15);
return 0;
}



The result will be:

So this was a bit on functions, its basics, now you may want to practice functions along with looping (while, do while and for), if else or switch conditions and you may want to use double instead of int to practice more. If you have any problems then drop a comment below, i'll get back to you asap. Stay Tuned I may come up with other samples in the coming days..All C tutorials.

>> Tuesday, May 22, 2012

C programming: Looping: while loop, do ... while loop and for loop

Looping in programming means that we make a set of instructions in a program to execute repeatedly until some conditions are met. There are three known loops in C and they are:
- while
- do .. while
- for

With loops, when we don't set a limit, the program will continue to be repeated infinitely.

The While Loop



The while loops is as follows
while (condition) { statement }

Suppose we want to make a program that will execute 0 to 10 consecutively

#include <stdio.h>

int main()

{

int counter= 0; // initial value = 0

while ( counter <= 10) {

printf ( "%d\n", counter) ; /* they will be displayed on separate line with \n */

counter++; /* counter++ is another way to write counter = counter + 1; */

}

}

Explanation
We have made a variable called counter and we have set it to 0.
Then we have the while function and we have set the condition to be less than or equal to 10.
In our statement we have made a printf function to display the value of our variable.
Then we have set counter++ to add 1 to the initial 0 of our variable counter.
At this stage the program will go back and read the instruction again and will increment the variable counter by 1 each time. However it will stop at 10 as we have set the condition to be less than or equal to 10.
And that's it !

The result will be:

Note:
It is not necessary that the variable name is counter.
You can change the initial value 0 of the variable to other numbers, for e.g if you want it to start by 1, then write int counter = 1;
The logical/relational operators can be changed, for e.g just >
Try another example in your compiler by replacing the printf by:
printf("Student\n", counter);

When compiled it will display 11 times "Student" on separate lines.

Now lets merge the text and the number in the while loop's printf by adding %d to it:
printf("Student %d\n", counter);

Do you still remember what are booleans? Ok let's try it in our while condition, and see that it :
#include <stdio.h>

int main()
{
int counter= 1;
while (1) { // the boolean is 1 i.e true
printf("Number %d\n", counter) ;

counter++;
}
return 0;
}

What this will do is run:

Number 1
Number 2
Number 3
.
.
.

to infinite

It will never stop unless you close it.

The do .. while Loop


The do .. while loop is almost similar to the while loop, but we write the condition in the end. This means that this loop will execute at least one time, then it will abide to the condition in the while loop.

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

int main()
{

int counter = 0;

do
{
printf("Number %d\n", counter);
counter++;


} while (counter < 10);

return 0;



}


The for Loop


The for loop is just a more rapid way to do a loop. In fact with just the while loop we can do all the loops but the other way are just alternatives which is easier for some situations. Let's convert the above above into a while loop.

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

int main()
{
int counter;

for (counter = 1 ; counter < 10 ; counter++) {


printf("Number %d\n", counter);


}


return 0;


}



Explanation
(counter = 1 ; counter < 10 ; counter++) The first counter = 1 is where we have initialized our counter, the second one, counter < 10 is the condition, and the third one, counter++ as you know already it is to increment the counter by 1.
The rest is the printf which is not new to you.

That's a bit on loop, practice by changing the values and try to add a scanf function by yourself to ask a user to enter a value each time in the loop and the calculate the total. And if you have any problem just drop a comment below and i'll get back to you asap.

>> Monday, May 21, 2012

C programming: switch conditions

Like if ... else, switch is used to set conditions to a program. But we used switch for more specific value that we want a user to enter. Suppose you want to the user to have only 5 choice to choose between 5 objects. For example our program will display a statement for each choice the user chose, and will return a default statement if ever he/she enter a wrong choice. Let's make a small program using switch and follow the explanation below:

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

int main()
{
int tshirt;

printf("Choose your T-Shirt size:\n\n 1. Extra small\n 2. Small\n 3. Medium\n 4. Large\n 5. Extra-Large\n\n Enter the number of your choice: ");
scanf("%d", &tshirt);

printf("\n");

switch (tshirt)
{
case 1:
printf("This T-shirt is $10");
break;
case 2:
printf("This T-shirt is $15");
break;
case 3:
printf("This T-shirt is $20");
break;
case 4:
printf("This T-shirt is $25");
break;
case 5:
printf("This T-shirt is $30");
break;
default:
printf("You have entered a wrong number or we don't have this T-shirt in our stock");
break;
}

printf("\n");

return 0;
}


Explanation
The lines before the switch function should now be familiar to you. So let's see the switch function.
In the () after the switch there is the name of our variable which is tshirt.
Then we have open a curly bracket
The case is a function that we used to formulate our choice. Note that it end with a column and not a semi-column, that is : instead of ;
The there is a normal printf function which will display a statement if the value after the case is chosen. Like in our program, if the user enter 1, then the program will display "This T-shirt is $10".
It is then followed by a break; which tell the program to pause here as it has already reach what to display for what the user has entered.
Similarly for the rest.
Notice at the end we have used default. This tells the program that if the user hasn't enterred any of what is attributed to any case, then display what default contained as printf.

Note: you can put two case for a choice like this:
case 5:
case 6:
printf("This T-shirt is $50");
break;

If the user enter either 5 or 6, then the program will display "This T-shirt is $50".

Also instead of numbers you can also put letters as choices but you need to add =getchar() to the variable of the switch, like this:
switch (tshirt = getchar())

And you should write the letter of the case in single quote like this:
case 'a':
printf("This T-shirt is $50");
break;

And if you know that any user can enter either a letter in small or capital letter then you have to make two case like this:
case 'a':
case 'A':
printf("This T-shirt is $50");
break;

That's a bit on switch. Practice by changing the values and if you have any problems, drop a comment below.




© BUHTH 2011 All rights reserved