-->

Tuesday, February 17, 2015

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.

Get to Know about Decision Making and branching Statements in Detail: C Language

INTRODUCTION:

A statement (also known as instruction) is the smallest element of any programming language. A statement or instruction is used to inform the computer to perform an action, when a program is executed. A statement can be used to set values of variables, alter the values of a variables, accept the input, manipulate the data and display the data. Each statement in C language must be terminated by a semicolon “;”.

The expression such as “a + b”, “c = 20”, “printf()” may become statements when they are terminated by a semicolon as shown below:


a + b;                 /* statement 1 */
c = 20;                /* statement 2 */
printf();            /* statement 3 */
 

A statement can be simple statement (discussed above) or can be compound statement. The set of statements enclosed within a pair of curly braces such as “{“and “}” is considered as a compound statement. For example, the following compound statement computes and display the sum of two values.
{
  Num1 = 15;                                   
  Num2 = 35;                                   
  Sum = Num1 + Num2;                           
  printf(“The sum of Num1 %d and Num2 %d = %d”,Num1,Num2,Sum);   
}
This compound statement can be treated as a single statement. Note that in a compound statement ‘}’ must not end with semicolon. So, all the operations like arithmetic, assignment, control structures and input/output function calls are considered as statements. Now, let us see “What are control statements? What are the types of the control statements?”

Sequential Statements with FlowChart and Example

Saturday, February 14, 2015

Uses of Sequential and Compound Statements: C programming

INTRODUCTION

In our previous article, we have studied about the single statements. The order in which statements are executed known as control flow and the statements that are used to control the flow of execution of the program are called as control statements. Based on the order in which the statements are executed, the various control statements are classified as follows:
         
Uses of Sequential and Compound Statements: C Language

Now, let us consider each of the control statements one by one.

Sequential Statements

The programmer writes a sequence of statements to specify some activity in a program. All these statements in a program are executed in the order in which they appear in the program. These programming statements that are executed sequentially, i.e. one after one is known as the sequential statements. Here, no separate statements are required to make these statements executed in sequence. The flow chart and the equivalent programming statements are shown below:

Uses of Sequential and Compound Statements: C Language

Here, statement 1 is executed first followed by statement 2 followed by statement 3 and so on. In short, we can say that execution of program is normally sequential (one after one). For example, let us write a program to find the sum of two integer numbers, which is given by the following relation:

Sum = Num1 + Num2

The sequence of steps to be followed as:
•    Input two integer numbers
•    Compute the sum using Sum = Num1 + Num2
•    Display the result
•    Stop the execution

The equivalent algorithm and the flow chart for the same are shown below:

Example 1:    Algorithm and flow chart to compute the sum of two integer numbers.
Algorithms:    ADD
    [Compute the sum of two integer numbers.]
    Step 1: [Input any two integer numbers]
        Read: Num1, Num2
    Step2: [Compute the sum]
        Sum = Num1 + Num2
    Step3: [Display the result]
        Write: Sum
    Step4: [Stop]
        Exit
Uses of Sequential and Compound Statements: C Language

Example2:
main()
{
 int Num1, Num2, Sum;
 clrscr();
 printf(“Enter any two integer numbers\n”);
 scanf(“%d%d”,&Num1.&Num2);
 /* compute the sum*/
 Sum = Num1 + Num2;
 Printf(“Sum = %d”,Sum);
 getch();
}

Output:
Uses of Sequential and Compound Statements: C Language

Advantage

No other separate control statement is required to execute the sequential statements one after one.

Disadvantage:

The sequence in which statements are executed cannot be altered or changed.
© Copyright 2013 Computer Programming | All Right Reserved