Sunday, June 10, 2012

C Language








Welcome to the csamplecode.in . The main motive of this site is used to learn the C language easily in this site we discuss about the total c language concepts like variables, control structures, Arrays, Strings, Functions, Pointers, Structures and Files concepts in addition we our guiding with sample programs.


C Language was developed by Dennis Ritchie in 1972 at bell labs in U.S.A.and it is a Middle Level Language.

C History:Algol is the ancient and traditional language to all the languages it is in binary format. From this language BCPL was developed by Ken Thomson. BCPL was High level language and it is not solved some problems at that time. From BCPL another language was dervied and named it as B by Martin Richards in 1969 at cambridge university. From these two languages one more language was dervied and it is named as "C" by Dennis Ritchie.

C Features: Simple:  C is a simple language because it has 32 keywords. Keyword is a reserve word which is taken from english dictionary and given a syntax for that word.

Procedure Oriented Programming Language: C is a Procedure Oriented Programming Languages causes code re usability.

Modularity: Modularity means breaking the project into sub modules, After developing the sub modules and again it is rejoined. C supports Modularity.

Fast Complier: C complier complies the program every fast than the other compliers becuase it is a middle level language.

System Indepedent : C creates system independent language becuase it is a middle level language.

Pointers: Pointers are special variable used to store the other variable address. Pointers are used to allocate dynamic memory allocation in the program.

Functions: c is a Procedure oriented programming language and we can define our own user defined functions.

C Characteristics: 1. C is a Strictly case senstive language

2. Every Program should start with main function.

3. Every Statement should end with semi-colon(;) called as line terminator.

4. Every block open with a { and end with } called as Delimiters.

5. Every function end with () called as parenthesis

Identifiers

Identifiers are defined by the programmer to identify the user defined function, variables, structures names etc.
to specify the names for the identifiers we must follow some rules and regulations these rules are called as identifiers rules and regulations.
Rule1: Identifier name may any length of long but at least one minimum character should be mentioned.
Rule 2: Identifier name  may be alphanumeric means identifier name can have numbers and alphabets but identifiers should not start with numbers and it can end with numbers.
Rule 3: Identifier name should not match with keyword.
Rule 4: Identifier name should not contain spaces in between the words if the identifier is more than one token it can separated by underscore( _ ).
Rule 5: Identifier name should not contain special characters.
Rule 6: identifier name may be upper case/ lower case once we define the name with that name only we must access other wise it show the error.
Example for Valid Identifiers :
  • Student_Name
  • firstnumber
  • m1
Example for Invalid Identifiers:
  • S.No
  • student name
  • int
Variables: It is used to allocate a block memory for the programmer to store the data. To identify the block of memory we must specify name, and it should follow identifiers rules and regulations.

Data types: We Use data types for two reasons
1. what type of data variable is storing to perform the operations.
2. How much memory should allocate for the variable.

Data type are classified into these types
  • Predefined datatypes
    • Numeric Datatypes
      • int
      • float
      • double
    • Non Numeric datatypes
      • char
      • string
  • User Defined datatypes
    • Structures
    • Unions
    • Enums

Keywords

Keyword is a reserve word taken form English dictionary and given a syntax for us. These word should be in lower case. We have 32 keywords in C Language and it became simple for us.
Keyword list :
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile
while
first program in C Language

Saturday, June 9, 2012

Program in C Langauge




When we write a program we should follow some rules and regulations.
Rule 1: Every program should start with main().
Rule 2: Variables can't define the everywhere in the program, in the starting only we must define when the function is defined.
Rule 3: When we use the predefined functions/ library functions we must include the header file.
Rule 4: According to the Editors we must mention the header file.

First Program

#include<stdio.h>
main()
{
printf(" Welcome to the C Sample Code ");
getch();
}

Output:
Welcome to the C Sample Code

Explanation

stdio.h it is a header file used for input and output purpose
printf() it is a function used to display the statement in the output screen.
Syntax: printf("statement");
There is a rule for us every program is should start with main() and it is user defined function

Let us See the Next program accepting the integer value and display the value in the output screen


#include<stdio.h>
main()
{
int no;
printf("\n Enter a number: ");
scanf("%d",&no");
printf("\n You Entered Number is :  %d",no);
getch();
}

Output: 
Enter a Number: 34
You Entered Number is :  34

In the above program we used scanf(), %d" and \n.
scanf(): it is a function used to accept the values in the run time of the program.
Syntax: scanf("formatspecifier",&variable_name);

Format Specifier: it is used to accept the value or displaying the value in the program.
Format SpecifierDatatype
%cchar
%ffloat
%ddouble
%dint
%sstring
& is used to specify the address location for the variables (Future we discuss about the variables location in the pointer concept)

Escape Sequences: it is used to format the output screen in the c editor
\n  is used to specify for the new line.
\a  is used to specify for the beep sound.
\b  is used to specify for the backspace.
\t  is used to specify for the tab space.
\" is used to specify for the " in the output screen.
\r is used to specify for the home.
\* */comment lines

Let us see the next program accept two variables and find the sum of two numbers

#include<stdio.h>
main()
{
int a,b,c;
printf("\n Enter two numbers: ");
scanf("%d%d",&a,&b");/* accepting the values */

c =a+b ;/*adding the values of a and b and it is placed in the c variable */
printf("\n Sum of two values is  :  %d",c);
getch();
}

Output: 
Enter two numbers: 4
5
Sum of two values: 9

Wednesday, June 6, 2012

Operators in c



C Language have rich set of Operators.
Operator: it is a special symbol used to perform a task on the operand.
Operand: it is a variable or data item
Expression: it is a combination of Operands and operators.
Ex: c= a+b
where c,a,b are operands
+,= are operators.

Arithmetic Operators

: It is used to perform a general mathematical operations.
OperatorUsage
+ Addition
- Subtraction
* Mutliplication
/ Division
% Remainder

Assignment Operators

It is used to assign the values from right hand side to the left hand side. Right hand side may be a variable / Expression / Value constant, But Left hand side must be a variable. To assign the values we use "=" symbol.

tr> tr> tr> tr>
-=
OperatorUsage
= Assign the value from R.H.S to L.H.S
Eg: a=b means b variable value is assigned to a variable
Eg: a=5 means 5 integer constant is stored in a variable
Eg: c= a+b means a and b variable values are added and it is strored in c variable
+= eg: A +=5
means A= A+5

5 value constant is added to A variable the sum value is stored in A again
-= eg: A -=5
means A= A-5

5 value constant is subtracted from A variable the difference value is stored in A again
*= eg: A *=5
means A= A*5

5 value constant is multiply to A variable the product is stored in A again
*= eg: A /=5
means A= A/5

5 value constant is division with A variable and the quotient value is stored in A
/= eg: A /=5
means A= A/5
5 value constant is division with A variable and the quiotent value is stored in A
%=eg: A %=5
means A=A%5
5 value constant is division with A variable and the remainder value is stored in A

+=,-=,*=,/=,%= are called as shorthand notations.

Relational Operators

It is used to check the simple conditions in the clanguage

Operator

Usage

<

greater than

<=

greater than or equal to

>

less than 

>=

less than or equal to

= =

comparision (equal to)

!=

Not Equal to

Logical Operators

It is used to combine more than one conditions into a single conditions and all the conditions are treat as single condition.
We have two operators

Operator

Usage

&& (and)

it is used to combine more than one condition as a single condition. if all the conditions are true than total condition is true other wise if one condition is false than total condition is false.

|| (or) 

it is used to combine more than one condition as a single condition. if any one  condition is  true than total condition is true 

Terinary Operators

it is used to check the condition if the condition is true it executes true set of statements other wise it executes false set of statements.
Syntax: (cond)? true_statement:false_statement;
Example: Write a C Program accept a number and check whether it is even or odd
#include<stdio.h>
main()
{
 int a;
printf("\n Enter a Number: ");
scanf("%d",&a); /* accepting a number */
(a%2= =0)? /*  checking the condition */
    printf("\n %d is an even no",a): printf("\n %d is an odd no",a);
}
Explanation: In the above program i accepted a number in the runtime and checking whether it is even or odd for this program first of all i must accept a number from the run time(out put screen) and the value should not be floating value( decimal values) for this reason i declare a variable datatype should be int and it stores the value from  -32768 to 32767  and it occupies two bytes memory. By using the scanf i accepted and %d is format specifier for the integer datatype (click here to see the format specifiers). Main task of the program is to check whether it is even or odd means if any number is divisible by 2 and remainder is 0 we say as even number other wise it is odd number here i required two operators 1. %  and 2. = = ( it is used to check the output value is equal to zero or not).


OUTPUT:  Enter a number: 5
                      5 is an odd no

Tuesday, June 5, 2012

Decision Making Statements




 In C Language doesn't follow the sequence follow means top to bottom. C Program flow can be change by the programmer by using Control Structures. In C Language we have three types of Control Structures
  • Decision Making Statements
  • Looping Control Structures / Iterative Control Statements
  • Unconditional Control Structures / Jumping Statements
Decision Making Statements: it is used to check the condition if the condition is true it executes the true set of statements otherwise it executes the false set of statements.
Decision Making Statements 
  • If Statements
    1. simple if
    2. if else
    3. if else if (or) if ladder
    4. Nested if
  • Switch Statements
Simple if: it is used to check the conditions. if the condition is true it executes the true set of statements otherwise if the condition is failed and rest of the program will be continuous. 
Syntax: if (cond)
            {
                    statements;
            }

If Else: it is used to check the condition. if the condition is true it executes the true set of statements otherwise it executes the false set if statements and rest of the program will be continuous.
Syntax: if (cond)
            {
                    statements;
            }
           else
           {
                     statements;
           }

If Else if or If Ladder: it is used to check multiple conditions.
Syntax: if (cond)
            {
                    statements;
            }
           else if( cond )
           {
                     statements;
           }
          else if( cond )
           {
                     statements;
           }
           else if( cond )


           {
                     statements;
           }
          else if( cond )
           {
                     statements;
           }
           ||
           ||
           else
           {
                  statements;
            }
Note:  if any one condition is true that block will be executed and rest of the statements will not executed. If all conditions are false than else block will be executed.

Nested if: In one if we are writing another if is called as Nested if.

Switch : It is a multiway decision statements used to perform = =( equal to operator) operations where as in if ladder we can perform all operators.
Syntax: switch(variablename/exression)
             {
                       case val1: statements; break;
                       case val2: statements; break;
                       case val3: statements; break;
                       case val4: statements; break;
                       case val5: statements; break;
                         ||
                         ||
                        default: statement; 
             }
Note: if we forget to write the break keyword for the case, next case statement will be executed if the condition is false. 



Friday, June 1, 2012

Looping Control Structures




In C Language We have three types of loops
  1. while loop: it is a precondition loop, first of all it checks the condition if the condition is true it executes the looping statements and incrementation / decrementation will done and again it check the condition.
    Syntax: intilization;
    while (cond)
    {
    statements;
    inc/dec;
    };
  2. do while loop: it is a post condition loop, First of all looping statements will be executed than it checks the condition if the true it enters into the loop other wise it come outside from the loop.
    Syntax: intilization;
    do
    {
    statements;
    inc/dec;
    }
    while(cond);
  3. for loop: it is same as while loop and it is a precondition loop. In for loop all the 3 statements are written in a single line. i.e. intilization, condition, incrementation/decrementation.
    Syntax: for(inti;cond;inc/dec)
    {
    statements;
    }

Thursday, May 31, 2012

Jumping Statments / UnConditional Control Structures



In C Language we have Unconditional Control Structures:
  • break
  • continue
  • goto
  • exit()
break: it is used to break the flow of the program at a particular condition.
Example for break keyword:
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for Break: ");
   for(i=1;i<=10;i++)
   {
              if(i==5)
                    break;
              printf("\t%d",i);
   }
}
Output: A Good Example for Break:           1            2              3              4               5
continue: it used to skip the iteration in the loops for a particular condition.

Example for continue keyword:
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for Break: ");
   for(i=1;i<=10;i++)
   {
             printf("\t%d",i);
              if(i==5)
              {
              printf("\n Loop is continued ");
              continue;
              }
              
   }
}
Output: A Good Example for Continue:           1            2              3              4            Loop is continued              6                7            8               9                   10
exit(): it is used to terminate the program and it is a function.

Example for exit():
#include<stdio.h>
main()
{
    int i;
   printf("\n A Good Example for exit(): ");
   for(i=1;i<=10;i++)
   {
              if(i==5)
             {  
                    printf("\n Program is terminated");
                    getch(); 
                    exit();
              } 
              printf("\t%d",i);
   }
}
Output: A Good Example for exit() :           1            2              3              4  
                                                                        Program is terminated
goto: it is used to execute the particular statement continuously when condition is given.
Write a program accept a number and display the numbers from 1 to n with out using loops

#include<stdio.h>
main()
{
    int i,n;
    printf("Enter a Number: \n");
    scanf("%d",&n);
     i=1;
     hai:
         printf("\t %d",i++);
     if(i<=n)
          goto hai;            
   }
}
Output: Enter a Number: 5
             1             2               3             4                  5

Wednesday, May 30, 2012

Examples On Control Structures




In this page you can see some examples on Control Structures
write a c Program accept three numbers and check which one of them is greatest by using if else
Solution: 
         #include<stdio.h>
         main()
         {
              int a,b,c;
              clrscr(); /* to clear the screen */
              printf("\n Enter three numbers: ");
              scanf("%d%d%d",&a,&b,&c);
              if(a>b&&a>c)
                   printf("\n %d is greatest",a);
              else
              {
                    if(b>c)
                         printf("\n %d is greatest",b);
                    else
                         printf("\n %d is greatest",c);
               } 
           getch(); 
         }
      output: Enter Three Numbers: 5 7 0
                  7 is greatest