Pages

Thursday, 30 December 2010

Ethernet Cable

  1. What are Ethernet Cables?
       Ethernet cables connect network devices such as modems, routers, and adapters. They transmit data using the Ethernet protocol. Ethernet cables have RJ-45 jacks on both ends, each with 8 pins. (They look similar to telephone jacks, which use 4 pins or 6 pins.)
    Note:
    • Equipment using an Ethernet cable is referred to as wired.
    • Wireless equipment uses radio waves in place of some (or all) Ethernet cables. A network device that uses both Ethernet and wireless connections is usually called just wireless.
  2. How to find the first pin position in RJ45 connector?
  3. Pin Position in RJ45 connector?
  4. RJ45 Pins:

  5. Straight-Through Ethernet Cable:
    1.A straight-thru cable has identical ends.
    2.A straight-thru is used as a patch cord in Ethernet connections.
    3.Both the T-568A and the T-568B standard Straight-Through cables are used most often as patch cords for your Ethernet connections. If you require a cable to connect two Ethernet devices directly together without a hub or when you connect two hubs together, you will need to use a Crossover cable instead
    1. T-568A:
    2. T-568B:
  6.  Crossover Ethernet Cable:
  7. Transmission in straight and cross over cable:
Points to Remember:
  1. A straight-thru cable has identical ends.
  2. A crossover cable has different ends.
  3. A straight-thru is used as a patch cord in Ethernet connections.
  4. A crossover is used to connect two Ethernet devices without a hub or for connecting two hubs.
  5. A crossover has one end with the Orange set of wires switched with the Green set.
  6. Odd numbered pins are always striped, even numbered pins are always solid colored.
  7. Looking at the RJ-45 with the clip facing away from you, Brown is always on the right, and pin 1 is on the left.
  8. No more than 1/2" of the Ethernet cable should be untwisted otherwise it will be susceptible to crosstalk.
  9. Do not deform, do not bend, do not stretch, do not staple, do not run parallel with power cables, and do not run Ethernet cables near noise inducing components.

Friday, 26 November 2010

how to add a column after a particular column in mysql table

  1. To add a new colmn to the existing table the ALTER command is used. Syntax:
                alter table < table name > add < column name > ;
     Example:
           To add a column called ldate to the main_tab table with a datatype of date, use the following SQL statement:
                mysql> alter table main_tab add ldate date;
             This statement will add the ldate  column to the end of the table.
  2. To insert the new column after a specific column, such as name, use this statement:
    ALTER TABLE contacts ADD email VARCHAR(60) AFTER name;

    mysql> alter table main_tab add ldate date after doj;
    Query OK, 11 rows affected (0.12 sec)
    Records: 11  Duplicates: 0  Warnings: 0

    mysql> desc main_tab;
    +----------+-------------+------+-----+---------+----------------+
    | Field    | Type        | Null | Key | Default | Extra          |
    +----------+-------------+------+-----+---------+----------------+
    | acc_no   | int(5)      | NO   | PRI | NULL    | auto_increment |
    | name     | varchar(20) | YES  |     | NULL    |                |
    | gender   | varchar(6)  | YES  |     | NULL    |                |
    | password | varchar(10) | YES  |     | NULL    |                |
    | doj      | date        | YES  |     | NULL    |                |
    | ldate    | date        | YES  |     | NULL    |                |
    | amount   | float(10,2) | YES  |     | NULL    |                |
    +----------+-------------+------+-----+---------+----------------+
    7 rows in set (0.00 sec)
     

  3. If you want the new column to be first, use this statement:
    ALTER TABLE contacts ADD email VARCHAR(60) FIRST;


  4. //To drop a particular column in mysql table

    mysql> desc main_tab;
    +----------+-------------+------+-----+---------+----------------+
    | Field    | Type        | Null | Key | Default | Extra          |
    +----------+-------------+------+-----+---------+----------------+
    | acc_no   | int(5)      | NO   | PRI | NULL    | auto_increment |
    | name     | varchar(20) | YES  |     | NULL    |                |
    | gender   | varchar(6)  | YES  |     | NULL    |                |
    | password | varchar(10) | YES  |     | NULL    |                |
    | doj      | date        | YES  |     | NULL    |                |
    | amount   | float(10,2) | YES  |     | NULL    |                |
    | ldate    | date        | YES  |     | NULL    |                |
    +----------+-------------+------+-----+---------+----------------+
    7 rows in set (0.00 sec)

    mysql> alter table main_tab drop ldate;
    Query OK, 11 rows affected (0.10 sec)
    Records: 11  Duplicates: 0  Warnings: 0

    mysql> desc main_tab;
    +----------+-------------+------+-----+---------+----------------+
    | Field    | Type        | Null | Key | Default | Extra          |
    +----------+-------------+------+-----+---------+----------------+
    | acc_no   | int(5)      | NO   | PRI | NULL    | auto_increment |
    | name     | varchar(20) | YES  |     | NULL    |                |
    | gender   | varchar(6)  | YES  |     | NULL    |                |
    | password | varchar(10) | YES  |     | NULL    |                |
    | doj      | date        | YES  |     | NULL    |                |
    | amount   | float(10,2) | YES  |     | NULL    |                |
    +----------+-------------+------+-----+---------+----------------+
    6 rows in set (0.00 sec)


    how to change a column without deleting the contents in mysql table
  1. starting with mysql
    mysql -u root -p
  2. starting with mysql
    mysql -u root -p

sudo synaptic
then search for mysql, make sure you have the server selected, click apply.

command for creating a database create database ;
Example: create database bank;
command for list all the available databases
show databases;

command for selecting particular database
use ;
ex:
use bank;

http://www.tech-recipes.com/category/database/mysql/

A primary key uniquely identify a row in a table. One or more columns may be identified as the primary key. The values in a single column used as the primary key must be unique (like a person’s social security number). When more than one column is used, the combination of column values must be unique.


When creating the contacts table described in Create a basic MySQL table, the column contact_id can be made a primary key using PRIMARY KEY(contact_id) as with the following SQL command:
CREATE TABLE `test1` (
contact_id INT(10),
name VARCHAR(40),
birthdate DATE,
PRIMARY KEY (contact_id)
);

Additional columns can be identified as part of the primary key with a comma separated list in the PRIMARY KEY command, like PRIMARY KEY (contact_id, name).
A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do with the actual record). A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key.
Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the existing table structure (using ALTER TABLE).
Below are examples for specifying a primary key when creating a table:
MySQL:
CREATE TABLE Customer
(SID integer,
Last_Name varchar(30),
First_Name varchar(30),
PRIMARY KEY (SID));

Oracle:
CREATE TABLE Customer
(SID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));

SQL Server:
CREATE TABLE Customer
(SID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));

Below are examples for specifying a primary key by altering a table:
MySQL:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
Oracle:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
SQL Server:
ALTER TABLE Customer ADD PRIMARY KEY (SID);
Note: Before using the ALTER TABLE command to add a primary key, you'll need to make sure that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.

This slick MySQL syntax allows you to increment or decrement an existing number in a table without first having to read the value. This is a nice way to increment an access counter.


To increment the value ‘counter’ by one for the row in table ‘images’ where ‘image_id’ is ‘15′, use:
UPDATE images SET counter=counter+1 WHERE image_id=15

how to get system time and date in c
http://www.intechgrity.com/automatically-insert-current-date-and/
mysql> insert into main_tab values(1,1,'suni','f','cpgm',CURDATE(),1000.00);
Query OK, 1 row affected (0.00 sec)

mysql> select * from main_tab;
+----+--------+------+--------+----------+------------+---------+
| id | acc_no | name | gender | password | doj        | amount  |
+----+--------+------+--------+----------+------------+---------+
|  1 |      1 | suni | f      | cpgm   | 2010-11-19 | 1000.00 |
+----+--------+------+--------+----------+------------+---------+
1 row in set (0.00 sec)

mysql> insert into main_tab values(2,2,'prem','m','welcome',now(),1000.00);Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> select * from main_tab;
+----+--------+------+--------+----------+------------+---------+
| id | acc_no | name | gender | password | doj        | amount  |
+----+--------+------+--------+----------+------------+---------+
|  1 |      1 | suni | f      | cpgm   | 2010-11-19 | 1000.00 |
|  2 |      2 | prem | m      | welcome   | 2010-11-19 | 1000.00 |
+----+--------+------+--------+----------+------------+---------+
2 rows in set (0.00 sec)

add new column in to an existing mysql table

Drop Column:
 alter table icecream drop column flavor ;
Drop Column is used to remove an entire column and all its data from a table.
Add Column:
alter table icecream add column flavor varchar (20) ; 
 mysql> desc deposit;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| acc_no | int(5)      | YES  |     | NULL    |       |
| amount | float(10,2) | YES  |     | NULL    |       |
| ddate  | date        | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table deposit add column flag char(1);
Query OK, 0 rows affected (0.10 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc deposit;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| acc_no | int(5)      | YES  |     | NULL    |       |
| amount | float(10,2) | YES  |     | NULL    |       |
| ddate  | date        | YES  |     | NULL    |       |
| flag   | char(1)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
 
mysql> desc main_tab;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| acc_no   | int(5)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(20) | YES  |     | NULL    |                |
| gender   | varchar(6)  | YES  |     | NULL    |                |
| password | varchar(10) | YES  |     | NULL    |                |
| doj      | date        | YES  |     | NULL    |                |
| amount   | float(10,2) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql> alter table main_tab add column ldate date;
Query OK, 30 rows affected (0.07 sec)
Records: 30  Duplicates: 0  Warnings: 0

mysql> desc main_tab;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| acc_no   | int(5)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(20) | YES  |     | NULL    |                |
| gender   | varchar(6)  | YES  |     | NULL    |                |
| password | varchar(10) | YES  |     | NULL    |                |
| doj      | date        | YES  |     | NULL    |                |
| amount   | float(10,2) | YES  |     | NULL    |                |
| ldate    | date        | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

how to change/modify particular column value in mysql table
mysql> select * from deposit;
+--------+---------+------------+------+
| acc_no | amount  | ddate      | flag |
+--------+---------+------------+------+
|      1 | 2000.00 | 2010-11-26 | d    |
|      1 | 2000.00 | 2010-11-26 | d    |
|      2 | 3000.00 | 2010-11-26 | d    |
|      3 | 2000.00 | 2010-11-26 | d    |
+--------+---------+------------+------+
4 rows in set (0.00 sec)

mysql> update deposit set amount=5000.00 where acc_no=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from deposit;
+--------+---------+------------+------+
| acc_no | amount  | ddate      | flag |
+--------+---------+------------+------+
|      1 | 2000.00 | 2010-11-26 | d    |
|      1 | 2000.00 | 2010-11-26 | d    |
|      2 | 5000.00 | 2010-11-26 | d    |
|      3 | 2000.00 | 2010-11-26 | d    |
+--------+---------+------------+------+
4 rows in set (0.00 sec)

Monday, 6 September 2010

Linux Command netcat(nc)

What is 'netcat' (nc) ?
         Netcat is a generic utility capable to doing anything involving TCP/UDP connections.  It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning.
 
Syntax:
       netcat [flags] [hostname] [port]
               or
       nc [flags] [hostname] [port]

       Flags:
               -v ----> Include a verbose o/p to understand what netcat is doing
               -z ----> Check if the specified port [port] is open on server [hostname]

What can 'netcat' do?
It can be used a tool for any of the following
  1. Port Scanning.
  2. File Transfer
  3. Chat
1) Port Scanning:
          When '-z' flag is specified, netcat reports whether the specified ports are open or not.
Example:
hprem@hprem-lnx:~$ netcat -v -z hprem-lds 20-30
netcat: connect to hprem-lds port 20 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 21 (tcp) failed: Connection refused
Connection to hprem-lds 22 port [tcp/ssh] succeeded!
netcat: connect to hprem-lds port 23 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 24 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 25 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 26 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 27 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 28 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 29 (tcp) failed: Connection refused
netcat: connect to hprem-lds port 30 (tcp) failed: Connection refused

2)Chat

         To start a chat session between two hosts. For that start netcat in listen mode on some random port On host1 .In the following examples it is assumed that the machine that creates the session(listening connection) has the IP address 192.168.1.4 . So, create the chat server on this machine and set it to listen to 9600  TCP port::
       netcat -l 9600

On the other host, start netcat On the same port:
       netcat 192.168.1.4 9600

Anything that is typed on host2 would get echoed on host1 and vice-versa


3)File Transfer
       To transfer file between two hosts, start netcat in listen mode on the host that should accept the file, on some random available port and redirect the o/p to a file
       On host1:
       netcat -l 9600 > filename

On the other server, start netcat and as it to read data from the file that has to be copied
       On host2:
       netcat 192.168.1.4 9600 < filename
   netcat does not show any info about the progress of the data transfer. This is inconvenient when dealing with large files. In such cases, a pipe-monitoring utility like pv can be used to show a progress indicator.

Linux Command BC(Basic Calculator)

BC(Basic Calculator)
What is 'bc'
  • 'bc' (basic calculator) is a command line calculator. It reads "expressions to be evaluated" from stdin and sends output to stdout. So you can pipe the output of any linux command to 'bc' for further calculations and you can pipe the output to any other linux command.
  • Since 'bc' reads input from stdin, the common usage is of the form
         echo "expr" | bc     (or)        bc <<< "expr"
Why 'bc':

  • You dont have to load a GUI calculator to do simple calculations.
  • Precision can be set to any value (most of the graphical calculators has a precision upto 10 digits). Precision is limitted only by the processing power of your computer. You can find the value of pi upto 1000 decimal places within 1.5 mins with a normal computer.
  • Available by default with all flavours of linux by default
1.Example for Addition, Subtraction, Multiplication, Division, Power, square root


sunitha@sunitha-lappy:~$ echo "10+2" | bc
12
sunitha@sunitha-lappy:~$ echo "10-2" | bc
8
sunitha@sunitha-lappy:~$ echo "10*2" | bc
20
sunitha@sunitha-lappy:~$ echo "10/2" | bc
5
This can be written simple as
sunitha@sunitha-lappy:~$ bc <<< "10+2"
12
sunitha@sunitha-lappy:~$ bc <<< "10-2"
8
sunitha@sunitha-lappy:~$ bc <<< "10*2"
20
sunitha@sunitha-lappy:~$ bc <<< "10/2"
5

The scale (number of digits after decimal point), by default is set to 2
sunitha@sunitha-lappy:~$ bc <<< "scale=2;10/2"
5.00
sunitha@sunitha-lappy:~$ bc <<< "2^3"
8
sunitha@sunitha-lappy:~$ bc <<< "scale=20;sqrt(10)"
3.16227766016837933199


2.Grouping - using parenthesis

sunitha@sunitha-lappy:~$ bc <<< "10+(2*3)"
16

3.Relational Expressions - <, >, >=, <=, ==, !=

sunitha@sunitha-lappy:~$ bc <<< "5<3"
0
sunitha@sunitha-lappy:~$ bc <<< "5>3"
1
sunitha@sunitha-lappy:~$ bc <<< "5>=3"
1
sunitha@sunitha-lappy:~$ bc <<< "5<=3"
0
sunitha@sunitha-lappy:~$ bc <<< "5==3"
0
sunitha@sunitha-lappy:~$ bc <<< "5!=3"
1

4.Bitwise Operations:
Base - obase, ibase
Base conversion -- Hexadecimal to Decimal
sunitha@sunitha-lappy:~$ bc <<< "obase=16;124"
7C
Base conversion -- Decimal to Hexadecimal
sunitha@sunitha-lappy:~$ bc <<< "ibase=16;7C"
124

Hexadecimal calculation
sunitha@sunitha-lappy:~$ bc <<< "obase=16;ibase=16;7C+F"
8B

sunitha@sunitha-lappy:~$ bc <<< "ibase=16;obase=10;7C+F"
8B

Binary calculation:
sunitha@sunitha-lappy:~$ bc <<< "obase=2;28"
11100
sunitha@sunitha-lappy:~$ bc <<< "obase=2;ibase=2;11100+10011"
101111

5.MATH LIBRARY
       If bc is invoked with the -l option, math library gets preloaded, making a lot more math functions available to us.
Note: Default scale is set to 20 when bc is started with -l option

(a) sine,cos,tan and arctangent
Note: pi can be calculated using the formula, pi=4*arctangent(1)
sunitha@sunitha-lappy:~$ bc -l <<< "pi=4*a(1);pi"
3.14159265358979323844
sunitha@sunitha-lappy:~$ bc -l <<< "pi=4*a(1);s(pi/2)"
1.00000000000000000000
sunitha@sunitha-lappy:~$ bc -l <<< "pi=4*a(1);c(pi/2)"
.00000000000000000001

(b)exponential and logarithmic functions
sunitha@sunitha-lappy:~$ bc -l <<< "l(e(10))"
9.99999999999999999999

Some Cool tips
* Arbitrary precision (scale)
bc has a default scale of 0, which is quite annoyoing as bc <<< 3/2 gives 1 instead of 1.5.  bc -l would solve this issue

sunitha@sunitha-laptop:~$ bc <<< 3/2 -l
1.50000000000000000000
 
  The default scale is 20. But if you need any arbitrary precision, say you want the default scale to be 5 whenever you invoke bc, follow this

In your .bashrc in your home directory add "export BC_ENV_ARGS=~/.bc"
Then create the file named ".bc" in your home directory, with the following one line
        scale=5
Now, bc <<< 5/3 gives 1.66666

* Alarm
To start audacious (the default music player that comes with ubuntu) after 8 hrs (to server as an alarm)
sleep `bc <<< 8*60*60`; audacious -p

Sunday, 5 September 2010

Data Input and Output-III



Little More about printf

Flags in printf function:
  • We can place flags in the printf statement with in the control string which will affect the appearance of the output.
  • The flag must be placed immediately after the percent sign(%).
  • Two or flags can be combined for a single output.
  • Table shows the commonly used flags


    FlagMeaning
    -Data item is left justified(ie)Blanks added after the data item
    +A sign(+(or)-) will precede with each signed numerical data item
    0Place leading zeros to appear instead of leading blanks
    #(with 0- & x- type conversion)Causes octal and hexadecimal data items to be processed by 0 and 0x respectively
    #(with e-,f- & g- type conversion)Causes a decimal point to be present in all floating point numbers even if the data item is a whole number.Also prevents the truncation of trailing zeros in g-type conversion
  • Example:



     
     
    #include<stdio.h>
    int main()
    {
        int x=1234;
        float y=15.5,z=-5.5;
        printf("%d %f %e\n",x,y,z);
        printf("%6d %7.0f %10.1e\n",x,y,z);
        printf("%-6d %-7.0f %-10.1e\n",x,y,z);
        printf("%+6d %+7.0f %+10.1e\n",x,y,z);
        printf("%-+6d %-+7.0f %-+10.1e\n",x,y,z);
        printf("%7.0f %#7.0f %7g %#7g\n",y,y,z,z);
        return 0;
    }

    OutPut:


    1234 15.500000 -5.500000e+00
      1234      16   -5.5e+00
    1234   16      -5.5e+00 
     +1234     +16   -5.5e+00
    +1234  +16     -5.5e+00 
         16     16.    -5.5 -5.50000
Prefixes in printf function: 
  • Prefixes within the control string to indicate the length of the corresponding argument.
  • Example: i indicates a signed or unsigned integer argument or a double precision argument. h indicates signed or unsigned short integer.

    #include<stdio.h>
    int main()
    {
        short x,y;
        long a,b;
        printf("%5hd %6hx %8lo %lu\n",x,y,a,b);
        return(0);
    }
    hd->short decimal integer
    hx->short hexadecimal integer
    lo->Long octal integer
    lu->Long unsigned integer
  • It is also possible to write the conversion characters x,e,g in uppercase as X,E,G. These uppercase conversion characters cause any letters with in the output data to be displayed in uppercase
    Example:

    #include<stdio.h>
    int main()
    {
        int x=0x10ab,y=0777;
        float z=0.3e-12;
        printf("|%8x %10.2e|\n",x,z);
        printf("|%8X %10.2E|\n",x,z);
        printf("|%8x %8o|\n",x,y);
        printf("|%#8x %#8o|\n",x,y);
        return(0);
    }
    Output:

    | 10ab 3.00e-13|
    | 10AB 3.00E-13|
    | 10ab 777|
    | 0x10ab 0777|
gets() and puts() Function:
  • gets and puts function used to read and write string(character array terminate with a newline character)
  • The string may include whitespace characters
  • Example:

    #include<stdio.h>
    int main()
    {
        char text[100];
        gets(text);
        puts(text);
        return(0);
    }

    Output:
    ./a.out
    helo welcome
    helo welcome

Saturday, 28 August 2010

Data Input and Output-II

4.Printf function

  • Printf function prints data from the computers memory to the standard output device.
  • Syntax:
    printf("%converion character",Argument list);

    Argument->It can be constants,single variable, array names (or) complex expressions
  • Example:

    #include<stdio.h>
    int main()
    {
        int i=10,j=20;
        char text[20];
        printf("%d %d %s\n",i,j,text);
        return 0;
    }
  • printf allow us to include labels and message with the output data. The extra labels in the double quotes in the printf will be displayed in the screen.
    Example:
    #include &lt; stdio.h&gt;
    int main()
    {
    int avg=80;
    printf("Average=%d%\n",avg);
    return 0;
    }

    Output
    Average=80%
  • The f-type conversion and the e-type conversions are both used to output floating point values.  In e-type conversion an exponent to be included in the output.
    Example


    #include&lt; stdio.h &gt;
    int main()
    {
        float x=100.0,y=25.25;
        printf("%f %f \n",x,y);
        printf("%e %e\n",x,y);
        return 0;
    }

    Output
    100.000000 25.250000
    1.000000e+02 2.525000e+01
  •  In the printf, s-type conversion is used to output a string that is terminatedd by the null character(\0). Whitespace characters may be included with in the string.
    Example: Reading and writing a line of text.
    #include&lt; stdio.h &gt;
    int main()
    {
        char text[100];
        scanf("%[^\n]",text);
        printf("%s",text);
        return 0;
    }
Minimum field width specification
  • We can restrict the number of characters or numbers displayed in the screen by specifying a fieldwidth. A minimum field width can be specified by preceding the conversion character by an unsigned integer.
  • Syntax:
    %fieldwidth conversioncharacter
  • If the number of characters in the corresponding data item is less than the specified field width then the data item will be preceded by enough leading blanks to fill the specified field.
  • If the number of characters in the data item exceeds the specified field width then additional space will be allocated to the data item so that the entire data item will be displayed.
    Rule1: Number of digits > field width=Add additional space
    Rule2: Number of digits < field width=Add leading blankspace
  • Example:

    #include<stdio.h>
    int main()
    {
        int x=12345;
        float y=123.456;
        printf("%3d %5d %7d\n",x,x,x);
        printf("%3f %10f %13f\n",y,y,y);
        printf("%3e %10e %13e\n",y,y,y);
        return 0;
    }
    Output
    12345 12345   12345
    123.456000 123.456000    123.456000
    1.234560e+02 1.234560e+02  1.234560e+02
    x has 5 digits
    %3d->no of digits(5) < fieldwidth(3) so additional space added and all  the digits are displayed.
    %7d-> no of digits(5) > fieldwidth(7)=>12345
     
  • g-type conversion:
       In g-type conversion no extra trailing zeros are added in the floating point number.
    Example:
    #include<stdio.h>
    int main()
    {
        float x=123.456;
        printf("%3g %10g %13g\n",x,x,x);
        printf("%3g %13g %16g\n",x,x,x);
        return 0;
    }

    Output
    123.456    123.456       123.456
    123.456       123.456          123.456
Floating point precision specification
  • It is also possible to specify the maximum number of decimal places for a floating point value or the maximum number of characters displayed for a string. This specification is known as precision.
  • The precision is an unsigned integer. Precision is always preceded by a decimal point.
  • A floating point number will be rounded if the number of digits exceeds the precision.
  • Example:
    #include<stdio.h>
    int main()
    {
        float x=123.456,y=1.5,z=4575.255;
        printf("%5f %7f %7.1f %7.2f %7.3f\n",x,x,x,x,x);
        printf("%5f %7f %7.1f %7.2f %7.3f\n",y,y,y,y,y);
        printf("%5f %7f %7.1f %7.2f %7.3f\n",z,z,z,z,z);
        printf("%5g %7g %7.1g %7.2g %7.3g\n",x,x,x,x,x);
        printf("12e %12.3e %12.5e\n",x,x,x);
        //only precision no field width
        printf("%f %0.1f %0.3f\n",x,x,x);
        printf("%e %0.3e %0.5e\n",x,x,x);
        return 0;
    }

    Output
    123.456000 123.456000   123.5  123.46 123.456
    1.500000 1.500000     1.5    1.50   1.500
    4575.254883 4575.254883  4575.3 4575.25 4575.255
    123.456 123.456   1e+02 1.2e+02     123
    12e    1.235e+02  1.23456e+02
    123.456000 123.5 123.456
    1.234560e+02 1.235e+02 1.23456e+02
Minimum field width and precision specification for character data
  • The specification for a string is same as numerical data. (ie) leading blanks will be added if the string is shorter than the specified field width and additional space will be allocatedd if the string is longer than the specified field width.
  1. string characters < field width=add leading blanks
  2. string characters > field width=add additional space
  • The precision specification will determine the maximum number of characters that can be displayed.

    Precision < string characters=excess right most characters will not be displayed
  • This rule is applied even if the minimum field width is larger than the entire string but additional blanks will be added to the truncated string.
  • Example:

    #include<stdio.h>
    int main()
    {
        char text[20]="Welcome";
        printf("%5s\n %7s\n %10s\n %15s\n %0.5s\n %15.5s\n",text,text,text,text,text,text);
        return 0;
    }

    Output:
    Welcome
     Welcome
        Welcome
             Welcome
     Welco
               Welcome
    %0.5s=Welco [no field width but the maximum precision is 5. so only 5 characters displayed.
    %15.5s= < 10 blankspace > Welco [maximum precision is 5 so the string trimmed to Welco but the field width is 15 so 10 leading blanks added.]