Tuesday, 26 November 2013

String In C

The string in C programming language is a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
 C Programming
C Programming


The declaration and initialization for creating a a word "World".To determine the end of the string ,there is a symbol ('\0') at the end of the array which means null character.

char greeting[6] = {'W', 'o', 'r', 'l', 'd', '\0'};
The declaration of a string in C Programming language is:
 char a[] = "Hello";
 The memory presentation of above defined string in C Programming language is:

String Presentation in C:

 You not need to  place the null character at the end of a string by yourself. The C compiler automatically places the '\0' at the end of the string when it initializes the array.

#include <stdio.h>

int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   printf("Greeting message: %s\n", greeting );

   return 0;
}
Output:
Greeting message: Hello
C Provide a wide range of functions that manipulate null-terminated strings:

S.N.   Function & Purpose
1strcpy(s1, s2);      Copies string s2 into string s1.
2strcat(s1, s2);       Concatenates string s2 onto the end of string s1.
3strlen(s1);             Returns the length of string s1.
4strcmp(s1, s2);     Returns 0 if s1 and s2 are the same; less than 0 if                                                   s1<s2; greater than 0 if s1>s2.
5strchr(s1, ch);       Returns a pointer to the first occurrence of character                                             ch in string s1.
6 strstr(s1, s2);       Returns a pointer to the first occurrence of string s2                                               in string s1.

#include <stdio.h>
#include <string.h>

int main ()
{
   char str1[12] = "Hello";
   char str2[12] = "World";
   char str3[12];
   int  len ;

   /* copy str1 into str3 */
   strcpy(str3, str1);
   printf("strcpy( str3, str1) :  %s\n", str3 );

   /* concatenates str1 and str2 */
   strcat( str1, str2);
   printf("strcat( str1, str2):   %s\n", str1 );

   /* total lenghth of str1 after concatenation */
   len = strlen(str1);
   printf("strlen(str1) :  %d\n", len );

   return 0;
}
OutPut:

strcpy( str3, str1) :  Hello
strcat( str1, str2):   HelloWorld
strlen(str1) :  10

C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments


Monday, 25 November 2013

Scope Rules In C

A scope in any program is a that region of the program where a defined variable can have its existence and beyond that variable can't be accessed. The three places where variables can be declared in C programming language:
 
C Programming
C Programming

Local Variables:

Variables which  are declared within a function or block are called local variables. They can be used only by statements which are inside that function.Local Variables are not more alive outside the functions .Here is the example of local variables. All the variables a, b and c are local Variables  to main() function.

#include <stdio.h>

int main ()
{
  /* local variable declaration */
  int a, b;
  int c;

  /* actual initialization */
  a = 10;
  b = 20;
  c = a + b;

  printf ("value of a = %d, b = %d and c = %d\n",   a, b, c);

  return 0;
}

Global Variables:

Global variables are defined outside of all function, used in a program.Global Variables are usually on top of the program. The global variables  can be accessed inside any of the functions.You can access them form any where .

Example of global variable is:

#include <stdio.h>

/* global variable declaration */
int g;

int main ()
{
  /* local variable declaration */
  int a, b;

  /* actual initialization */
  a = 10;
  b = 20;
  g = a + b;

  printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

  return 0;
}
A same name will be assigned to a local and global variables in a same C program but value of local variable inside a function will take preference.

#include <stdio.h>

/* global variable declaration */
int g = 20;

int main ()
{
  /* local variable declaration */
  int g = 10;

  printf ("value of g = %d\n",  g);

  return 0;
}
Output:

value of g = 10

Formal Parameters:

Function parameters, formal parameters, are treated as local variables inside that function and they will take preference over the global variables.
example:

#include <stdio.h>

/* global variable declaration */
int a = 20;

int main ()
{
  /* local variables in main function */
  int x= 10;
  int y = 20;
  int z = 0;

  printf ("value of x in main = %d\n",  x);
  c = sum( x, y);
  printf ("value of z in main = %d\n",  z);

  return 0;
}

/* function to add two integers */
int sum(int x, int y)
{
    printf ("value of x in sum= %d\n",  x);
    printf ("value of y in sum= %d\n",  y);

    return x + y;
}
 result:

value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30

Initializing Local and Global Variables:

Local variable  is not initialized by the system, you must initialize it by yourself. Global variables are initialized the system.

Data Type            Initial Default Value
int                                 0
char                            '\0'
float                              0
double                          0
pointer                         NULL

It I good to habit of initialize the variables otherwise in some cases you will get the unexpected results.
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments 


Sunday, 24 November 2013

Decision Making Structure In C

Decision making structures allows the programmer to specify one or more conditions to be evaluated or tested by the compiler or , along with a statement or set of statements to be executed if the condition is  true, and  other statements to be executed if the condition is  false.
 C Programming
C Programming

 Most of the programming languages follows the same decision making structure:
Decision Making Structure
Decision Making Structure 

 In C programming language  any non-zero and non-null values is  true, and if it is either zero or null, then it is assumed as false value.

C programming language has  following types of decision making statements.

Statement                               Description
1.if statement                              It consists of a boolean condition followed by one or more                                                                 statements.
2.if...else statement                   It can be followed by an optional else statement, which                                                                       executes when the condition is false.
3.nested if statements              if or else if statement inside another if or else if statement(s).
4.switch statement                     It allows a variable to be tested for equality against a list of                                                                 values.
5.nested switch statements     You can use one switch statement inside another switch                                                                    statement(s).
6.The ? : Operator:

Example of conditional operator
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions.

The value of a ? expression is determined like this:first  Exp1 is evaluated. If Exp1 is true, then Exp2 is evaluated otherwise then Exp3 is evaluated and its value becomes the value of the expression.
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

Operators in C

An operator is a symbol that instruct  the compiler to perform specific mathematical or logical operation. C language  has following type of operators:
C Programming
C Programming
•  Arithmetic Operators
•  Relational Operators
•  Logical Operators
•  Bitwise Operators
•  Assignment Operators
•   Misc Operators
This post will explain the arithmetic, relational, logical, bitwise, assignment and other operators.

Arithmetic Operators:

The table  below shows all the arithmetic operators supported by C language. Let  suppose the value of A is  10 and variable B is 20 then:
Arithmetic Operators
Arithmetic Operators

Relational Operators:

The table shows all the relational operators supported by C language. Let  suppose the value of A is  10 and variable B is 20, then:
Relational Operators
Relational Operators


 Logical Operators:

Following table shows all the logical operators supported by C language.Let  suppose the value of A is  1 and variable B has value  0, then:
Logical Operators
Logical Operators


Bitwise Operators:

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
Assume if A = 60; and B = 13; now in binary format they will be as follows:
BitWise Operators
BitWise Operators

A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011

The Bitwise operators supported by C language are listed in the following table.Let  suppose the value of A is 60 and variable B is 13, then:
BitWise Operators
BitWise Operators

Assignment Operators:

 following are the assignment operators supported by C language:
assignment operators
assignment operators

Misc Operators ↦ sizeof & ternary

following are  few other important operators including sizeof and ? : supported by C Language.
Misc Operators
Misc Operators

Operators Precedence in C:

Operator precedence determines priority of operators in an expression . It also determines how  expression is evaluated. Some of the operators have higher precedence than others; for an instance , the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
The operators with the highest precedence is at the top of the table, those with the lowest are at the bottom. In  an expression, higher precedence operators will be evaluated first.
Operators Precedence in C:
Operators Precedence in C:

C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Argumen

Storage Classes in c

A storage class in C defines the scope (visibility) and life-time of a variables and/or a functions .These specifiers precede the type that they modify. There are some storage classes, which are  used in a C Program
 C Programming
C Programming


 1.auto
 2.register
 3.static
 4.extern

The auto Storage Class:

The auto storage class is the default class for local variables in a c program.

{
   int m;
   auto int mon;
}
The example defines two variables with the same storage class and auto can only be used within a functions, i.e., only for local variables.

The register Storage Class:

The register storage class is  used to define  variables(local) that supposed to be stored in a register instead of RAM. The variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it ( because  it does not have a memory location).

{
   register int  mile;
}
The register should only be used for those variables that require quick access such as counters. Defining 'register' does not mean that the variable will be stored in a register rather it  MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class:

The static storage class commands the compiler to keep a local variable alive during the life-time of the program instead of creating and destroying it each time when it comes into and goes out of scope.Static allows a variable to maintain their values between function calls.

The static modifier can also be applied to global variables. The variable's scope to be restricted to the file in which it is declared.

#include <stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

main()
{
   while(count--)
   {
      func();
   }
   return 0;
}
/* function definition */
void func( void )
{
   static int i = 5; /* local static variable */
   i++;

   printf("i is %d and count is %d\n", i, count);
}
Output Is:

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

The extern Storage Class:

The extern storage class is used to give a reference of a  variable(global) that is visible to all  program files. When you use 'extern' keyword, the variable can't be initialized and it point the variable name at a storage location that has been previously defined.

A extern storage class is more efficient  when you are using multiple files .You define a variable in one of the files which will be available at the time of linking of the program. You can use extern keyword to declare a variable at any place.

First File: mainfile.c

#include <stdio.h>

int count ;
extern void write_extern();

main()
{
   c = 5;
   write_extern();
}
Second File: supportfile.c

#include <stdio.h>

extern int count;

void write_extern(void)
{
   printf("count is %d\n", c)
}
The extern keyword is being used to declare c in the second file and its definition is  in the mainfile.c.
 compile these two files as shown below:

 $gcc main.c support.c

 following is the result:
 5
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operator
C - Decision Making
C - Loop
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

Constant and Literals in c

The constants refer to fixed values that the program may not change during its execution. These values are also called literals.
C Programming
C Programming


Constants can be of any of the  data types like an integer , a floating , a character , a string literal and an enumeration constants as well.

The constants are consider just like regular variables except that their values can't be modified after their definition.

Integer literals:

An integer literal can be of any number system 1.e a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix are :
1.0x or 0X for hexadecimal,
2.0 for octal.
3.and nothing for decimal.

An integer literal can also have a combination of  unsigned(U) and long(L), respectively. The suffix can be  in uppercase or  in lowercase and can be in any order.

 some examples of integer literals are:

2123         /* Legal */
2145u        /* Legal */
0xFeeL      /* Legal */
0718          /* Illegal: 8 is not an octal digit */
032UU      /* Illegal: cannot repeat a suffix */

 The various types of Integer literals are:
85             /* decimal */
0213         /* octal */
0x4b         /* hexadecimal */
30             /* int */
30u           /* unsigned int */
30l            /* long */
30ul          /* unsigned long */

Floating-point literal:

Floating-point literals must contain a decimal point,an integer part, a fractional part, and an exponent part.Floating point literals can be represent either in decimal form or exponential form.

When you  representing using decimal form, you must consider the decimal point, the exponent, or both and while using exponential form, the literal  must have  the integer part, the fractional part, or both. The signed exponent is introduced by e or E.
Example are:

3.14159           /* Legal */
314159E-5L    /* Legal */
510E                /* Illegal: incomplete exponent */
210f                 /* Illegal: no decimal or exponent */
.e55                 /* Illegal: missing integer or fraction */

Character constants:

Character literals are enclosed within single quotes, e.g., 'a' and can be stored in a variable of char type.

A character literal can be a plain character (e.g., 'a'), an escape sequence (e.g., '\n'), or a universal character (e.g., '\u02C0').

Some characters in C  are preceded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Following  are the some escape sequence codes:

Escape sequence             Meaning
\\                                   \ character
\'                                   ' character
\"                                   " character
\?                                  ? character
\a                                  Alert or bell
\b                                  Backspace
\f                                   Form feed
\n                                  Newline
\r                                   Carriage return
\t                                   Horizontal tab
\v                                  Vertical tab
\oo                                Octal number of one to two digits
\xhh . . .                         Hexadecimal number of one or more digits
Example using escape sequence:

#include <stdio.h>

int main()
{
   printf("Hey\tWorld\n\n");

   return 0;
}
Out put:

Hey  World

String literals:

String literals or constants are enclosed within a double quotes "".

You can also break a long line into multiple lines using string literals and separating them using whitespaces.

Some examples of string literals are:

"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

Defining Constants

The two simple ways to define a constant in are:

1.Using  preprocessor (#define):

2.Using const keyword.

The #define Preprocessor:
 the form to use #define preprocessor to define a constant is:

#define identifier value
example :

#include <stdio.h>

#define LENGTH 10  
#define WIDTH  5
#define NEWLINE '\n'

int main()
{

   int area; 
 
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}
Output of the above c program is:

value of area : 50

The const Keyword:
You can use const keyword prefix to declare constants with a specific type :

const type variable = value;
 example:

#include <stdio.h>

int main()
{
   const int  LENGTH = 10;
   const int  WIDTH  = 5;
   const char NEWLINE = '\n';
   int area; 
  
   area = LENGTH * WIDTH;
   printf("value of area : %d", area);
   printf("%c", NEWLINE);

   return 0;
}
Output:

value of area : 50
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments