Skip to main content

Data Types in C

Objectives:

Having read this section you should be able to:

1.declare (name) a local variable as being one of C's five data types
2.initialise local variables
3.perform simple arithemtic using local variables

Now we have to start looking into the details of the C language. How easy you find the rest of this section will depend on whether you have ever programmed before - no matter what the
language was. There are a great many ideas common to programming in any language and C is no exception to this rule.

So if you haven't programmed before, you need to take the rest of this section slowly and keep going over it until it makes sense. If, on the other hand, you have programmed before you'll be
wondering what all the fuss is about It's a lot like being able to ride a bike!

The first thing you need to know is that you can create variables to store values in. A variable is just a named area of storage that can hold a single value (numeric or character). C is very
fussy about how you create variables and what you store in them. It demands that you declare the name of each variable that you are going to use and its type, or class, before you actually

try to do anything with it.

In this section we are only going to be discussing local variables. These are variables that are used within the current program unit (or function) in a later section we will looking at global
variables - variables that are available to all the program's functions.


There are five basic data types associated with variables:

int - integer: a whole number.
float - floating point value: ie a number with a fractional part.

double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type which we will examine closely in later sections.

One of the confusing things about the C language is that the range of values and the amount of storage that each of these types takes is not defined. This is because in each case the 'natural'
choice is made for each type of machine.You can call variables what you like, although it helps if you give them sensible names that give you a hint of what they're being used for - names

like sum, total, average and so on. If you are translating a formular then use variable names that reflect the elements used in the formula. For example, 2&188;r (that should read as "2 pi
r" but that depends upon how your browser has been set-up) would give local variables names of pi and r. Remember, C programmers tend to prefer short names!

Note: all C's variables must begin with a letter or a "_" (underscore) character.


Integer Number Variables:

The first type of variable we need to know about is of class type int - short for integer. An int variable can store a value in the range -32768 to +32767. You can think of it as a largish

positive or negative whole number: no fractional part is allowed. To declare an int you use the instruction:

int variable name;

For example:

int a;

declares that you want to create an int variable called a.

To assign a value to our integer variable we would use the following C statement:

a=10;

The C programming language uses the "=" character for assignment. A statement of the form a=10; should be interpreted as take the numerical value 10 and store it in a memory

location associated with the integer variable a. The "=" character should not be seen as an equality otherwise writing statements of the form:

a=a+10;

will get mathematicians blowing fuses! This statement should be interpreted as take the current value stored in a memory location associated with the integer variable a; add the
numerical value 10 to it and then replace this value in the memory location associated with a.


Decimal Number Variables:

As described above, an integer variable has no fractional part. Integer variables tend to be used for counting, whereas real numbers are used in arithmetic. C uses one of two keywords to

declare a variable that is to be associated with a decimal number: float and double. They are each offer a different level of precision as outlined below.

float
A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to 1.E+36. A float takes four bytes to store.

double
A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to 1.E+303. A double takes eight bytes to store.

For example:

float total;

double sum;

To assign a numerical value to our floating point and double precision variables we would use the following C statement:

total=0.0;

sum=12.50;


Character Variables:

C only has a concept of numbers and characters. It very often comes as a surprise to some programmers who learnt a beginner's language such as BASIC that C has no understanding of
strings but a string is only an array of characters and C does have a concept of arrays which we shall be meeting later in this course.

To declare a variable of type character we use the keyword char. - A single character stored in one byte.

For example:

char c;

To assign, or store, a character value in a char data type is easy - a character variable is just a symbol enclosed by single quotes. For example, if c is a char variable you can store the letter
A in it using the following C statement:

c='A'

Notice that you can only store a single character in a char variable. Later we will be discussing using character strings, which has a very real potential for confusion because a string constant

is written between double quotes. But for the moment remember that a char variable is 'A' and not "A".


Assignment Statement:

Once you've declared a variable you can use it, but not until it has been declared - attempts to use a variable that has not been defined will cause a compiler error. Using a variable means
storing something in it. You can store a value in a variable using:

name = value;

For example:

a=10;

stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actually very useful! Who wants to store a known value like 10 in a variable so you can use it later? It

is 10, always was 10 and always will be 10. What makes variables useful is that you can use them to store the result of some arithmetic.

Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see how C would use these operations on two float variables a and b.

add
a+b
subtract
a-b
multiply
a*b
divide
a/b

Note that we have used the following characters from C's character set:


+ for add

- for subtract
* for multiply
/ for divide

BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?

a=10/3

The answer depends upon how a was declared. If it was declared as type int the answer will be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader
to find out the answer for a of type char.

Two points to note from the above calculation:

1.C ignores fractions when doing integer division!

2.when doing float calculations integers will be converted into float. We will see later how C handles type conversions.


Arithmetic Ordering:

Whilst we are dealing with arithmetic we want to remind you about something that everyone learns at junior school but then we forget it. Consider the following calculation:

a=10.0 + 2.0 * 5.0 - 6.0 / 2.0

What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that answer by following each instruction as if it was being typed into a calculator. A computer doesn't

work like that and it has its own set of rules when performing an arithmetic calculation. All mathematical operations form a hierachy which is shown here. In the above calculation the
multiplication and division parts will be evaluated first and then the addition and subtraction parts. This gives an answer of 17.

Note: To avoid confusion use brackets. The following are two different calculations:

a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

You can freely mix int, float and double variables in expressions. In nearly all cases the lower precision values are converted to the highest precision values used in the expression. For
example, the expression f*i, where f is a float and i is an int, is evaluated by converting the int to a float and then multiplying. The final result is, of course, a float but this may be
assigned to another data type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not rounded. In other words, in nearly all

cases you can ignore the problems of converting between types.

This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints, floats and doubles. This will shock any programmer who has used
another language, as it's another example of C getting us closer than is customary to the way the machine works. A character is represented as an ASCII or some other code in the range O
to 255, and if you want you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte integer variable that can hold a number

in the range O to 255, which can optionally be interpreted as a character. Notice, however, that C gives you access to memory in the smallest chunks your machine works with, i.e. one byte
at a time, with no overheads.


Something To Declare:

Before you can use a variable you have to declare it. As we have seen above, to do this you state its type and then give its name. For example, int i; declares an integer variable. You
can declare any number of variables of the same type with a single statement. For example:

int a, b, c;

declares three integers: a, b and c. You have to declare all the variables that you want to use at the start of the program. Later you will discover that exactly where you declare a variable
makes a difference, but for now you should put variable declarations after the opening curly bracket of the main program.

Here is an example program that includes some of the concepts outlined above. It includes a slightly more advanced use of the printf function which will covered in detail in the next part of

this course:

/*
/*
Program#int.c

Another simple program
using int and printf
*/

#include

main()
{
int a,b,average;
a=10;
b=6;
average = ( a+b ) / 2 ;
printf("Here ");
printf("is ");
printf("the ");
printf("answer... ");
printf("\n");
printf("%d.",average);
}


More On Initialising Variables:

You can assign an initial value to a variable when you declare it. For example:

int i=1;

sets the int variable to one as soon as it's created. This is just the same as:

int i;
i=l;


but the compiler may be able to speed up the operation if you initialise the variable as part of its declaration. Don't assume that an uninitialised variable has a sensible value stored in it. Some
C compilers store 0 in newly created numeric variables but nothing in the C language compels them to do so.


Summary:

Variable names:

-should be lowercase for local variables
-should be UPPERCASE for symbolic constants (to be dicsussed later)

-only the first 31 characters of a variables name are significant
-must begin with a letter or _ (under score) character

Comments

Popular posts from this blog

Random post with specific label - Blogger Widget

1. go to blogger dashboard, select template and edit html. 2. search for </head> to add script. - you may download and upload to your site, or just use this link (no download required) script <script src='http://docs.google.com/uc?id=0B7xJbTAja8i0a0ZJbXJ2TkkwSW8&amp;export=download' type='text/javascript'/> 2. search for ]]></b:skin> to add style/css. img.label_thumb{ float:left; padding:5px; border:1px solid #8f8f8f; background:#D2D0D0; margin-right:10px; height:55px; width:55px; } img.label_thumb:hover{ background:#f7f6f6; } .label_with_thumbs { float: left; width: 100%; min-height: 70px; margin: 0px 10px 2px 0px; adding: 0; } ul.label_with_thumbs li { padding:8px 0; min-height:65px; margin-bottom:10px; } .label_with_thumbs a {} .label_with_thumbs strong {} 2. save template. 3. add a widget. 3. edit widget. at this example i use random post with label "blogger", you must replace it with your label. <div s...

Submit your site for free to search engine~SEO TOOL SERACH ENGINE SUBMitt free

free Submit the main page of your site only. The rest of your site will be crawled by the search engines. Only 5 submissions in every 24 hours period are allowed. URL  * Email  * Name  * Business Phone  * Country  *   None Selected   United States   Afghanistan   Albania   Algeria   American Samoa   Andorra   Angola   Anguilla   Antigua and Barbuda   Argentina   Armenia   Aruba   Australia   Austria   Azerbaijan   Bahamas   Bahrain   Bangladesh   Barbados   Belarus   Belgium   Belize   Benin   Bermuda   Bhutan   Bolivia    Bosnia Hercegovina   Botswana   Bouvet Island   Brazil   Brunei Darussalam   Bulgaria   Burkina Faso   Burundi   Cambodia   Cameroon   Canada   Cape Verde   Cayman Islands   Central African Republic   Chad   Chi...

Tips to Enable or Disable Toast Notifications on Windows 8

Windows 8 is among the most incredible and interesting kind of Windows version from Microsoft. It has visually eye catching design, which is found in modern user interface that is meant for redesigning a number of operating systems, worked out for users. If you have used or seen someone using Windows 8 you could have noticed the toast notifications in this modern version of windows, which simply appears the moment you install or uninstall any application. There are many users who are well versed with the bubble notifications, which were found in the earlier versions of Windows seen via the taskbar. The new application platform in Windows 8 comes with an integrated notification system for installing or uninstalling a number of modern applications. The Windows 8 style application can employ a number of notifications types including the traditional toast notifications, live titles and lock screen. These can be managed by either disabling or enabling the notification of your applicatio...

List of all search engine by topics,genre and based on

Tweet General Baidu  (Chinese, Japanese) Bing Blekko Google Sogou  (Chinese) Soso.com  (Chinese) Volunia Yahoo! Yandex.com Yodao  (Chinese) P2P search engines FAROO Seeks  (Open Source) YaCy  (Free and fully decentralized) Metasearch engines See also:  Metasearch engine Blingo Yippy  (formerly Clusty) DeeperWeb Dogpile Excite Harvester42 HotBot Info.com Ixquick Kayak Mamma Metacrawler Mobissimo Otalo PCH Search and Win SideStep Thiv WebCrawler Geographically limited scope Accoona ,  China / United States Alleba , Philippines Ansearch ,  Australia / United States / United Kingdom / New Zealand Biglobe ,  Japan Daum ,  Korea Goo ,  Japan Guruji.com ,  India Leit.is ,  Iceland Maktoob ,  Arab World Miner.hu ,  Hungary Najdi.si ,  Slovenia Naver ,  Korea Onkosh ,  Arab World Rambler ,  Russia Rediff ,  India SAPO ,...

Downloading Windows 8 for Free [Full version]

Tweet Downloading Windows 8 for Free [Full version] Windows 8 is a new version of Windows that focuses on variety of hardware platform and form factors such as slim-type computers and new generation of touch devices. The new version free for download was made available for developers and testers of the new OS. Here’s the download links for the Enterprise version of Windows. How to get and download the latest operating system Thankfully, Microsoft released the new version free for download designed for technological professionals, engineers and IT personnel's for testing and debugging purposes. Download Links of the ISO file (x86 and x64) Windows 8 32-Bit version Windows 8 64-Bit version If you can’t download the file, make sure that you are login to your respected  Hotmail account .

Google Sheet/Google form Script to send automated Email to users

Well many of us want to send especially bloggers sometimes want to send automated replies to user 's ..but as usual, not everyone is a code geek or lovers ... so this is a small guide to How to use Google form with Google sheet to make an automated reply link....so follow the steps accordingly. STEP 1: GOTO google Forms ... and create a form ... in my case I just take users email id and how do they get to my site. 1. GOTO   https://docs.google.com/forms?usp=mkt_forms 2. login with your account. now choose blank form. 3. in Form title write your forms name, for example, let say my form. 4. in Form description write the description let say  A simple form ... 5. now go to setting and in general tab, check collect email address. and  click on save 6. (optional) you can also ask some basic question 7. now goto responses tab now click on create new spreadsheet button. (that green icon ..) in select response, destination cho...

Binary Search Tree in Java implementation (reference based, dynamic memory)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 import java.util.Scanner ; class BST { static BST . Node root = null ; public void insert ( int num ) { if ( root == null ) { root = new BST . Node ( num ); } else { // root node is not empty BST . Node temp = root ; while ( temp != null ) { if ( num <= temp . getVal ()) { if ( temp . getLeft () != null ) temp = temp . getLeft (); ...

just more way to disable autorun.inf

Auto run.Inf this is a instruction file associated with the Auto run function. It is a simple text configuration file that instructs the OS (operating system) which executable to start which icon to use which additional menu commands to make available etc Auto run.inf must be located in the root directory of a volume.That is CD,DVD,of Floppy Disk or Pen drive. It is mainly used by the manufacturer on what actions to taken when their CD-ROM when it is inserted. In OS, when autorun.inf is enabled (Normally by default it is enabled ) then by inserting the Cd or DVD the content of the medium is automatically executed. This is to avoid the user intervention and help the low level knowledge of computer literacy people. But Virus programmer taken this as advantage and make virus instruction in autorun.inf text file. TYPICAL AUTORUN.INF A typical autorun.inf file looks like below. [autorun] open=setup.exe icon=setup.exe,0 label=GameProgram SIMPLE METHOD NOT TO GET INFECTED BY AUTORUN.INF:...

python program get union of two list (program to get A union B ) list method .

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 16 17:08:52 2018 @author: beast """ def version1 (): a = [ 'a' , 'b' , 'c' , 'd' , 'e' ] # list 1 b = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ] # list 2 c = [k for k in (a) if (k in (a) and k not in (b))] # include unique item from list 1 : items are (list1-list2)(set thoery) d = [l for l in (b) if l in (a ) and l in (b) or (l not in (a) and l in (b))] #include all the comman from list 1 and unique from list 2 lst = c + d # append above two comprehensed list to get union of list1 U list2 lst . sort() # not neccessay but makes list easy to understand (sorting in ascending order ) ...

5 Quick Beginner-Friendly CSS Customizations That Make Your Blog Stand Out

Changing Background Color To change the background of your website, you first have to get familiar with the styling of the theme. Is the background color simply under body, or is it built into its own frame? Some themes are not as intuitive as others, so if the one you are currently using is intelligible, you might want to change to a different theme before you start editing. (The one I'm using in the example is the free  Catchbox Theme  and a very common starting theme is twentyeleven.) With most non full-width themes, the background color is simply under body. And overruling it is quite simple. 1 2 3 body {    background-color : #477C67 ; } You can use the  W3Schools HTML color picker  to get your colors, or install a Chrome extension, aFirefox plugin, or a WordPress plugin to speed things along when you're editing on the go. I chose a deep teal background color:  #477C67 : If this code snippet does not change the ba...