-->

Thursday, February 19, 2015

Primitive data types in C language

Introduction

Definition : “Basic data types are those that are not composed of other data types.

Primitive Data types are:

  • int
  • char
  • float
  • double
  • void
Note: The primitive data types are also called basic data types or simple data types or
fundamental data types.

int

It is a keyword which is used to define integer numbers. Normally they are associated with the
Variables to store singed integer values in memory  locations. That is, using this data type both
Positive and negative numbers can be stored in the memory . To represent only unsigned numbers
it is normally associated with a qualifier unsigned.
For example, unsigned int is used to define only positive numbers. Negative numbers cannot be
Stored if a variable is associated with unsigned int. the size and the range of integer vary from
Machine to machine as shown below:


n- bit machine
Size of int
Range of unsigned int
0 to 2n -1
Range of signed int
-2n-1 to 2n-1 -1
16-bit machine
2 bytes
0 to 216-1
Or
0 to 65532
-215 to 215-1
Or
-32768 to 32767
32-bit machine
4 bytes
0 to 232-1
Or
0 to 4294967295
-231 to 231 -1
Or
-2147483648 to 2147483647


Float

 It is a keyword which is used to define floating point numbers. The floating point numbers are Also called real numbers. Normally they are associated with the variables (also called identifiers) To store floating point numbers in memory locations. That is , using this data type both positive And  negative floating point numbers can be stored in the memory.

 Double

It is a keyword which is used to define  high precision floating point numbers Normally they are       Associated with the variables to store large floating point numbers in memory locations. That is, Using this data type both positive and negative large floating point numbers can be stored in the Memory.

Char

 It is a keyword which is used to define single character or a sequence of character called string.
Normally , They are associated with the variables to store a character or a string  in  memory
Locations. Each character stored in the memory is associated with a unique value called an ASCII
(American standard Code For Information Interchange) value.

Void

It is an empty data type. It is normally used in functions to indicate that the function does not
Return any value. Since no value is associated with this data type, it does not occupy any space
in the memory. Normally, it is not associated any variable (except pointers).

Table- Size and Range of Data types on a 10-bit machine.

Type
Size (bits)
Range
Format
Char of signed char
Unsigned char
Short signed int
Shot unsigned int
Signed int
unsigned int
long signed int or long int
long unsigned int
Float
double
long double
8
8
16
16
16
16
32
32
32
64
80
-128 to 127
0 to 255
-32768 to +32767
0 to65535
-32768 to +32767
0 to 65535
-2147483648 to +2147483647
   0 to 429467295
-3.4e38 to +3.4e38
-1.7e308 to +1.7e308
-1.7e4932 to +1.7e4932
%c
%c
%d
%u
%d
%u
%ld
%lu
%f
%lf
% lf

Tuesday, February 17, 2015

Structure in C language

Introduction to structures


We know that an array is a collection of similar data items such as int, float, char etc. If more number of Data items of same data type are grouped, we normally use arrays. For example, the marks of 6 students can be stored using array as shown below:

Int marks[6]={86,99,95,93,87,91};

The ordinary variables and arrays can handle variety of situations. But, in real world, we often deal with entities that are collection of dissimilar data types. For example, suppose we want to have the data related to a student. We may be interested in:
  • Name of the student            (char array, string type)
  • Roll number                        (int type)
  • Average marks                    (float type)
Note that the above data is a collection of various items of dissimilar data types(heterogeneous). So, arrays cannot be used (because, array is a collection of similar data types, homogeneous in nature). This is where, the structure are used.

Structure and its definition


Now, we shall see “ what is a structure? What is the syntax of a structure?”
Definition : A structure is defined as a collection of logically related (generally heterogenous) Variables under a single name. All these variables may contain data items of similar or dissimilar
Data types. Using these variables each item of a structure can be selected. Each variable in the
Structure represents an item and is called member or field or element of the structure. Each field
Has a type.


The general format or syntax of a structure is shown below:

Structure in C Programming


Where
  • Struct is keyword which tells the compiler that a structure is being defined.
  • Member1, member2,… are called members of the structure. They are also called fields or Elements of the structure.
  • The members are declared within curly braces. It is called body of the structure. The Members can be any of data types such as int, char, float etc.
  • There should be semicolon at the end of closing brace.
Example: Structure definition for storing student data.
Assume the student data consists of the following:
  •    Name of the student: Name is made up of sequence of characters. Ex: “Jecob Lefore”
  •    Roll number: It is of type integer Ex:1101
  •    Average marks: It is of type float Ex: 93.45
Since the above information is related to student and all the above information is logically related to
A student, we can use the structure. The structure definition to hold the information of student is
Shown below:
                               Struct student
                               {
                                          Char name [10];
                                          Int    rollno;
                                          Float   avg;
                             };
In the above example, observe the following points:

  • Struct is the keyword.
  • Student is called the name of the structure. The name of the structure is also called structure tag.
  • Name, rollno and avg are called fields of the structure. They are also called members of Structure and are associated with data types char, int and float.

The structure definition does not reserve any space  in memory for the members. So, it is called a  structure template and memory will  not be allocated for the template. This is pictorially represented as shown below:

structure template and memory will  not be allocated for the template

                                                          
Note : the various items in a structure can be same or different data types. But, all the items should be logically related. Do not combine un-related data.

For example, for the above structure definition, let us have filed number_of_wheels. The field number_of_wheels is in no way related to student data and hence has to  be avoided.

Data Types in C language

Definition : "Data types are means to identify the type of data and associated operations for handling it." In other words, " The type of the value that a variable can store in the memory is called the data type."

There are three types of Data types in C :

  • Basic or simple or Primitive data types
  • User-defined data type
  • Derived-type
Basic or Simple or Primitive data types
Definition : "Basic data types are those that are not composed of other data types."
The various primitive data types of C Language are classified as:
  • int
  • char
  • float
  • double
  • void
Note: The primitive data types are also called basic data types or simple data types or fundamental data types.
int 
It is a keyword which is used to define integer numbers. Normally they are associated with the variables to store signed integer values in memory locations. That is, using this data type both positive and negative numbers can be stored in the memory. To represent only unsigned numbers it is normally associated with a qualifier unsigned.

For example, unsigned int is used to define only positive numbers. Negative numbers cannot be stored if a variable is associated with unassigned int. The size and the range of integer vary from machine to machine as shown below:

float
It is a keyword which is used to define floating point numbers. The floating point numbers are also called real numbers. Normally they are associated with the variables (also called identifiers) to store floating point numbers in memory locations. That is, using this data type both positive and negative floating point numbers can be stored in the memory.

double
It is a keyword which is used to define high precision floating point numbers. Normally they are associated with the variables to store large floating point numbers in memory locations. That is, using this data type both positive and negative large floating point numbers can be stored in the memory.

char 
It is a keyword which is used to define single character or a sequence of character called string. Normally , they are associated with the variables to store a character or a string in memory locations. Each character stored in the memory is associated with a unique value called an ASCII (American Standard Code For Information Interchange) value.

void
It is an empty data type. It is normally used in functions to indicate that the function does not return any value. Since no value is associated with this data type, it does not occupy any space in the memory . Normally, It is not associated with any variable (except pointers).


Type
Size (bits)
Range
Format
char or signed char
8
-128 to 127
%c
unsigned char
8
0 to 255
%c
short signed int
16
-32768 to + 32767
%d
short unsigned int
16
0 to 65535
%u
signed int
16
-32768 to + 32767
%d
unsigned int
16
0 to 65535
%u
long signed int or long int
32
-2147483648 to +2147483647
%ld
long unsigned int
32
0 to 4294967295
%lu
float
32
-3.4e38 to +3.4e38
%f
double
64
-1.7e308 to +1.7e308
%lf
long double
80
-1.7e4932 to +1.7e4932
%Lf

User-defined data type 

 "what are user defined data types?"
User defined data type enables a programmer to invent his/her own data types and define what values it can take on. This can help programmer listing more readable, in the case of a complicated program or when more than one programmer works on it. Therefore this data type would help a programmer to reduce programming errors.

Definition : " A special data type that is defined by user from the derived data type is called user-defined data type or user-defined derived data types."

typedef, structure, union and enumeration are user-defined Data Types. Now let discuss these data types in detail.

(1) Structure: It is defined as collection of logically related variables under a single name. All these, variables may contain data items of similar or dissimilar data types. Using these variables each item of a structure can be selected. Each variable in the structure represents an item & is called member or field or element of the structure. Each field has a type. You can also use a user- defined Data type called structure using struct keyword.

struct (keyword): This keyword groups variables (same type or different type) into a single record and is used to create user-defined data type called structure.
Syntax:
struct [<struct_type_Name>] {
[<type> <variable_name [, variable_name, ]>];
[<type> <variable_name> [,variable_name, ]>];
[<structure_variables>];

A struct, like a union, groups variables into a single record.
 Where,
(1) <struct_type-Name> is an optional tag name that refers to the structure type. 
(2) <structure_variables> are the data definitions, also optional.

Though both <struct_type_name> and <structure_variables> are optional, one of the two must appear.
Elements in the record are defined by naming a <type>, followed by one or more <variable_name> that are separated by commas (,). Different variable type can be separated by a semicolon(;).

Let us see
struct my_struct {
char name [80], 
phone_number[80];
 int age, height; 
} my_friend;

This struct declares an array of records containing two strings (name and phone_number) and two integers (age and height).
To access elements in a structure, we use a record selector (.). For example,

 strcpy (my_friend.name, "Mr. jacob");

When a variable is associated with a structure, the compiler allocates the memory for each member. 
(2) Union (Keyword): A union is similar to a struct, except it allows you to define the variables that share storage space and are created using union keyword.

Syntax :
Union [<uniontype_name>] {
 <type> <variable_names>;
) [<union variables>];

Let us see an example :
union int_or_long {
int i;
long l;
} a_number;
Turbo C will allocate enough storage in a_number to accommodate the largest element in the union Unlike a structure(struct), the variable a_number.i and a_number.l occupy the same location in memory. Thus, writing into one will overwrite the other. Elements of a union are accessed in the same manner as a struct.

(3) Enumeration : A enumerated data type is another user-defined type which provides a way for attaching names to numbers. The enum keyword gives you an opportunity to define your own data type and also define what values the variable of this data type can take. This can help in making the program listing more readable, which can be an advantage when a program gets complicated or when more than one programmer would be working on it. Using enumerated data type can also help you reduce programming errors. The enum keyword (from C language) automatically enumerates a list of words by passing them values 0,1,2 and so on. This facility provides an alternative method for creating symbolic constants. The syntax of an enum statement is similar to that of the struct or union statement.

enumerator data type in c programming


Now let us see an example to understand enumeration data type.

enum shape {rectangle, square, triangle, circle}; Enum  position {off, on};
enum  color {black, white, red, blue, green, yellow};
enum  months {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec.}; 
enum emp_dept {Assembly, manufacturing, accounts, stores};

In C, the tag names shape, position, color, months and emp_dpt becomes new type names, using these tag names, we can declare new variables. For examples:

shape ellips; //ellips is of type shape
color background; // background is of type color
emp_dept IT; // IT is of type emp_dpt

ANSI C defines the types of enums to be int. Let us see some examples:
In C, By default, the enumerators are assigned integer values starting with 0 for the first enumerator, 1 for the second, 2 for the third and so on. However, you can over-ride the default explicitly assigning integer values to the enumerators. Let us see the examples:

enum months {Jan, Feb, Mar, Apr = 10, May, Jun, Jul}; 
enum monts {Jan = 2, Feb, Mar, Apr, May, Jun = 20, Jul};

are valid definitions. In the first case, Jan is 0 by default. In the second case, Jan is 2, Feb is 3. Mar is 4, Apr is 5, May is 6 and Jun is 20, Jul is 21.

(4) typedef: C supports a feature known as "type definition" that allows users to define an identifier that would represent an existing data type. Consider the syntax, typedef data_type identifier;
Where
typedef is the keyword.
datatype can be basic or derived or any other user defined data type.
identifier is the new name given to the datatype. Consider the type definition statement shown below:

 typedef  float AMOUNT;

Here, the identifier AMOUNT can be considered as a new data type, derived from the basic data type float. For example, in the declaration :
AMOUNT a;
a is variable of type AMOUNT i.e., of type float. Some of the points to be remembered at this point are:

(1) Using typedef, more meaningful data type names with short names can be created and used for declaring the variables. Thus, the readability of the program increases.
(2) The rules used for defining the identifier can be used to obtain a new data type such as AMOUNT.
(3) If the typedef statement is situated within a function, the scope of this typedef is limited only to that function and the new data type thus obtained, cannot be used outside this function. If the typedef is in the beginning of all the functions, then it will be global and can be used by any function.

Monday, February 16, 2015

Conditional If-Else Statement with Example in c language

To overcome the disadvantage of if statement, in computer programming the if-else statement is introduced. It is a two way decision statement which executes either first statement (or block of statements) or second statement (or block of statements) based on the condition.

For the true part if takes care and for the false part else takes care. The syntax of if-else statement along with equivalent flow chart is shown below:

if (condition)
 statement 1 or (block of statement 1)
else
 statement 2 or (block of statement 2)
Conditional If-Else Statement with Example: Turbo C

According to Flowchart, compiler will first check the condition. If the condition is true, the right side of statement(s) will execute otherwise left side of statement(s) will execute. For example 

Program to check whether the number is even or odd: Let num is the given number. After dividing num by 2, if the remainder is zero, then the given number num is even otherwise, given number num is odd. The equivalent statement can be written as:

if (num%2==0)
    Write: “Number is Even”
else
    Write: “Number is odd”
[End of if]

Algorithm:

Step 1: [Read the number to check]
              Read: NUM
Step 2: [Check the number]
              if(NUM%2==0)
                    Write: ‘Number is Even’
              else
           Write: ‘Number is Odd;
    End of if
Step 3:  Exit

The C program to perform the algorithm:

main()
{
   int num;
   printf(“Enter an integer number here:”);
   scanf(“%d”,&num);
   if(num%2==0)
      printf(“The number num %d is EVEN”,num);
   else
      printf(“The number num %d is ODD”,num);
   getch();
}

Nested-If statement

Branching Statements in Turbo C Language

In sequential statements, we know that all the statements are executed in the order specified in the program one after one. However, computer can skip execution of some statements those statements will not be execute by the compiler. This skipping feature is provided by the a set of instructions called skip instructions. These skip instructions are further called Branching Statements in technical words.

In other words the statements that alter/change the sequence of execution of the instructions, written in a program, are called branching statements. These statements or skip instructions have its own types. I will describe types of branching statement in brief:

Conditional Statements

The written instructions can be skipped based on a condition specified by the programmer. The branching statements that alter the sequence of execution of the program based on some condition are called conditional branching statements. They can also be called Selection Statements or Decision Statements.
For example, if, if-else, else-if ladder and switch statement.

Non Conditional Statements

Sometimes, user wants to transfer the control from one point to another point during execution without any condition. These type of branching statements that transfer the control from one point to another point in a program without any condition are called unconditional branching statement or unconditional control statements.
For example, goto, break, return and continue. We will understand all these statements with example.

If Condition

If or If statement is a simple selection or decision statement. When a set of statements have to be executed or skipped according to the given condition, this statement is used. Here's the syntax and flowchart of this statement:

If (Condition)
statement;
rest of code;
If flowchart in Branching Statements: Turbo C Language

According to Flowchart, compiler will first check the condition. If the condition is true, the block of statements will execute otherwise rest of code will execute. For example
if(num%2==0)
Write: ‘Even Number’
End if

Here, "Even Number" is displayed only if the condition is true. Now, let us write some simple programs that shows the application where if-statement can be used.

Program to check whether the given number is even or not.
Process: Let num is the given number. After dividing num by 2, if the remainder is equals to zero, then num will be even number. So, the equivalent algorithm and C language code is written here.

Algorithm:
Step 1: [Read the number to check]
              Read: NUM
Step 2: [Check the number]
            if(NUM%2==0)
                    Write: ‘Number is Even’
            End of if
Step 3: Exit

The C program to perform the algorithm
main()
{
   int num;
   printf(“Enter an integer number here:”);
   scanf(“%d”,&num);
   if(num%2==0)
   printf(“The number num %d is EVEN”,num);
   getch();
}

Advantage

If statement is one way decision statement. The if statement is used when a set of statements have to be executed or skipped based on one condition. That is only when the condition is true or false.

Disadvantage

If we have two statements to be executed, one on true and another on false, then if statement is not recommended. This disadvantage can be overcome using two way decision statement i.e. if-else statement.

Features of Bottom-up technique in C language


  • Program preparation starts from designing the sub-problems.
  • The solutions are clubbed in the main coordinating module.
  • The composition of solutions is generalized for main solution.
  • Program is structured as hierarchy of various tasks but viewed from bottom to upper level.
  • As the technique moves from bottom to top it is a type of generalization.
  • Main module can only be designed after the detailed design of sub-problems.
  • The tested sub-programs are used to frame the main solution.
  • Integration test is performed at the final stage of programming.
  • The code of the sub-problems are reusable.
  • The modules linking details is not available at the lower stage of programming.
  • This type of programming technique is most popular in Object Oriented Programming using C++ and Java.

If-Else-If Ladder Statement in Computer Programming: C Language

When series of actions have to be performed based on decisions one–by-one, then the statement used is called if-else-if ladder. In computer programming it is called multi-way decision statement. The if-else-if ladder is a form of nested if-statement. Here, nesting is allowed only in the else part. The orderly nesting of if statement only in the else part is called if-else-if ladder. The syntax of if-else-if ladder is shown below:

SQL Video Channel : Download all SQL Video

Syntax:

if(condition1)
    statement(s);
      else if(condition2)
    statement(s);
else if(condition3)
    statement(s);
-
-
-
    else if(conditionn)
    statement(s);
                               else
                                  statement(S);

In this statement the conditions condition1, condition2 etc. of if-else-if ladder are evaluated to true, the corresponding statement is executed and control comes out of the entire if-else-if ladder executing the rest statements that come after the if-else-if ladder.

If all the conditions are evaluated to false, then the last statement is executed, and the control comes out of if-else-if ladder and the rest statements that come after the if-else-if ladder are executed.

Problem:

Let consider a problem to display the grade obtained by a student based on the marks. The criteria to find the grade based on marks as follows:
    Marks        Grade
    0 to 34        F
    35 to 44      E
    45 to 59      D
    60 to 69      C
    70 to 79      B
    80 to 89      A
    90 to 100    A+

Algorithm:
Step1:    Read: Marks
Step2:    if(Marks<=34)
        Write: ‘Grade F’
    else if(Marks<=45)
        Write: ‘Grade E’
    else if(Marks<=59)
        Write: ‘Grade D’
else if(Marks<=69)
        Write: ‘Grade C’
else if(Marks<=79)
        Write: ‘Grade B’
else if(Marks<=89)
        Write: ‘Grade A’
else
Write: ‘Grade A+’
[End of if-else-if]
Step3:    Exit

Here's the C program to solve the above problem.

main()
{
  int marks;
  clrscr();
  printf(“Enter the student’s obtained marks here:\n”);
  scanf(“%d”,&marks);
  if(marks<=34)
     printf(“Grade F”);
  else if(marks<=45)
     printf(“Grade E”);
else if(marks<=59)
     printf(“Grade D”);
else if(marks<=69)
     printf(“Grade C”);
else if(marks<=79)
     printf(“Grade B”);
else if(marks<=89)
     printf(“Grade A”);
else
     printf(“Grade A+”);
getch();
}

Output
If-Else-If Ladder Statement in Computer Programming: C Language

Advantages:

In computer programming, situations involving series of decisions one after the other, each decision or condition may involve expression of various data types such as float, integer, char and double. In these situations the if-else-if ladder is used.

Disadvantages:

  • The nested ifs are hard to understand and modify.
  • As the depth of nesting increases, the readability of the program decreases.
  • In situations involving series of decisions one after the other, each decision or condition may involve expressions which result in integer value. In these situations the usage of if-else-if ladder is not recommended. Instead of this statement, we go for switch statement.
© Copyright 2013 Computer Programming | All Right Reserved