SlideShare a Scribd company logo
1 of 79
=======0======================================
Year 1972 at Bell telephone laboratories (AT
&T) by DENNIS RITCHIE.


Features of ‘C’ language:
    1. it is a flexible high level structured program language
    2. it includes the features of low level language like assembly
       language.
    3. it is much faster and efficient.
    4. it has a number of built-in functions, which makes the
       programming task simple


The ‘C’ language is used for developing:
    1. database system.
    2. graphics packages.
    3. scientific and engineering applications.


Format of C program:


Headerfile include
Main()
{
variable declaration;
program statements;
}


Ex:


#include<stdio.h>
main()
{
printf(“god is great”);
}


Keywords:


Keywords are words belongs to C language. The users have no
right to change its meaning.


Ex:
auto, goto, if, int, while, do, switch, case, char, else…..
Datatype:


TYPE                SIZE(bits)   RANGE


char                8            -128 to 127


unsigned char       8            0 to 255


int                 16           -32,768 to 32,767


unsigned int        16           0 to 65,535


long int            32           -2,147,483,648 to
                                 2,147,483,647


unsigned long int   32           0 to 4,294,967,295


float               32           3,4E-38 to 3,4E+38


double              64           1.7E-308 to 1.7E+308


long double         80           3.4E-4932 to 1.1E+4932
Variables:
      C variable refers to the name given to the memory location to
store data. A particular memory location is given only one name.
Yet this name is called a variable because this memory location
can store sequence of different values during the execution of the
same program.


Rules:
   1. a variable name is formed with alphabets, digits and a special
      character underscore( _ )
   2. the first character must be an alphabet.
   3. no special characters are used other than underscore
   4. both upper case and lower case letters are used.


Declaration variables:
Syntax:
      Data-type list of variables;
Ex:
      int x,y,z;


initializing variables:
syntax:
      data-type variable=initial value;
Ex:
      int a=10;
      float b=43.3;


comment statement:
      comment statements are non-executable statements.
  1. single line statement //
  2. paragraph statement /*          */


OPERATORS:
  An operator is a symbol which represents some operation that
can be performed on data. There are eight operators available in C
to carry out the operations. They are
  1. arithmetic operators
  2. relational operators
  3. logical operators
  4. short hand assignment operators
  5. conditional operators


Arithmetic operators:
      Arithmetic operators are used to do arithmetic calculations.
There are 2 types
        (i)       binary operators
(ii)       unary operators


Binary operator:
     BO need two operands for operations.
Operator                operation           Ex
+                       addition            x=5+6
-                       subtraction         x=10-5
*                       multiplication      x=5*4
/                       division            x=5/3 =1
%                       modulo operator     x=5%3 =2


Unary operators:
UO need only one operands for operation.


Operator                operation           Ex
++                      increment           i++
--                      decrement           i—


Relational operators:
     RO are used to find out the relationship between two
operands. They are
Operator                operation           Ex
>                       greater than        a>b
<                     less than            a<b
>=                    greater than equal to a<=b
<=                    less than equal to   a>=b
==                    equal to             a= =b
!=                    not equal to         a!=b


Logical operators:
     LO are used to find out the relationship between two or more
relational expressions. They are


Operator              operation            Ex
&&                    AND                  (a>b)&&(a>c)
||                    OR                   (a>b)||(a>c)


Short-hand assignment operators:
     SHAO are operators which are used to simplify the coding
of certain type of assignment statement.


The general form is
     Variable operator = expression
Variable   =    user define name
Operator =      +,-,*,/,%
Ex:
Operator                operation              Ex
+=                 value of LHS variable
                   will be added to the        x = x +10can be
                   RHS value and is            written as x+=10
                   Assigned to LHS variable


Conditional Operators:
      The CO ? and : are used to build simple conditional
expression. It has three operands. So it is called ternary operator.


The general form is
Expression1 ? expression2: expression3;


Expression1 is evaluated first. If it is true expression2 is
evaluated.if expression1 if false expression3 is evaluated.


Ex:
Sum = a>b ? a: b;


Input statement:


Scanf () function:
Scanf () is used to give data to the variables using keyboard.


The general form is
Scanf (“control string”, &variable1, ….&variable n);


Ex:
Scanf(“%d”,&a);
This statement reads a integer data and assigns to variable a


Output statement:


Printf () function:
Printf () is used to output the results of the program to the user
through VDU.


The general form is
Printf(“control string”, list);


Conversion character table:


C           single character
D           decimal integer
F           floating point value
H             short-integer
S             string


CONTROL STATEMENTS:
    1. Unconditional statements
    2. Conditional (or) Decision making statements
    3. Looping Statement


Unconditional Statement:
    1. goto statement


goto statement is used to transfer the program control
unconditionally from one point to another.


The general form is:
      goto label;
The label is the name given to the point where the control has to be
transferred
The general form is
      Label:statement;


Conditional Statement:
CO are used to skip or to execute a group of statements based
on the result of some condition.
   1. if statement
   2. if….else statement
   3. else….if ladder
   4. nested if statement
   5. switch statement


(i) Simple if statement:


Simple if statement is used to execute or skip one statement or
group of statements for a particular condition.


The general form is


If(test condition)
      {
            statement block;
      }
next statement;


Ex:
#include<stdio.h>
void main()
{
int mark;
char grade;
scanf(“%d %c”, &mark, &grade);
if(grade = =’a’)
{
mark=mark+10;
}
printf(“%d”,mark);
}


(ii) if….else statement:


if…else statement is used to execute one group of statements if the
test condition is true or other group if the test condition is false.


The general form is


If(test condition)
      {
              statement block-1;
}
else
       {
            statement block-2;
       }
next statement;


Ex:


#include<stdio.h>
void main()
{
int mark;
scanf(“%d”, &mark);
if(mark=>35)
printf(“pass”);
else
printf(“fail”);
}


(iii) else…..if ladder:
else….if ladder statement is used to take multiway decision. This
statement is formed by joining if….else statement in which each
else conditions another if….else


The general form is


If(test condition-1)
       {
            statement block-1;
       }
else if(test condition-2)
       {
            statement block-2;
       }
…………………………
………………………
…………….
else if(test condition-n)
       {
            statement block-n;
       }
else
       default statement;
next statement;


Ex:
#include<stdio.h>
void main()
{
int day;
printf(“give a number between 1 to 7n”);
scanf(“%d”, &day);
if(day= =1)
printf(“sundayn”);
if(day= =2)
printf(“Mondayn”);
if(day= =3)
printf(“tuesdayn”);
if(day= =4)
printf(“wednesdayn”);
if(day= =5)
printf(“thursdayn”);
if(day= =6)
printf(“fridayn”);
if(day= =7)
printf(“saturdayn”);
else
printf(“enter the currect value”n);
}


Nested if….else statement:
       This statement is formed by joining if….else statements
either in the if block or in the else block or both


The general form is:


If(test condition-1)
       {
            if(test condition-2)
                   {
                        statement block-1;
                   }
            else
                   {
                        statement block-2;
                   }
else
       {
            statement block-3;
}
next statement;


when this statement is executed, the computer first evaluates the
value of test condition-1. if it is false control will be transferred to
statement block-3. if it is true test condition-2 is evaluated. If it is
true statement block-1 is executed and control is transferred to next
statement else statement block-2 is executed and control is
transferred to next statement.


Ex:
#include<stdio.h>
main()
{
int a,b,c;
printf(“enter 3 no”);
scanf(“%d %d%d”, &a,&b,&c);


if(a>b)
      {
             if(a>c)
             printf(“A is big=%d”,a);
      else
printf(“B is big=%d”,c);
       }
else
       {
              if(b>c)
              printf(“B is big=%d”,b);
       else
              printf(“C is big=%d”,c);
       }
}


Switch Statement:
       Switch statement is an extension of if…..else statement. This
permits any number of branches.


The general forms:


Switch (expression)
{
       case label-1:
              statement block-1;
              break;
       case label-2:
statement block-2;
           break;
…………………………..
…………………………..
      case label-n:
           statement block-n;
           break;
      default:
           default statement;
           break;
}
next statement


Ex:


#include<stdio.h>
main()
{
int day;
printf(“Enter the no 1 to 7n”);
scanf(“%d”, &day);
switch(day)
{
case 1:
printf(“Sunday n”);
break;


case 2:
printf(“Monday n”);
break;
case 3:
printf(“Tuesday n”);
break;
case 4:
printf(“Wednesday n”);
break;
case 5:
printf(“Thursday n”);
break;
case 6:
printf(“Friday n”);
break;
case 7:
printf(“Saturday n”);
break;
default:
printf(“Enter the currect no:n”);
break;
}
}


LOOPING STATEMENTS:
      Looping statements are used to execute a group of statements
repeatedly until some condition is satisfied. The looping
statements are
      1. while statement
      2. do…while statement
      3. for statement


While statement:
      First evaluates the test condition. If the value is false, the
control is transferred to next statement. If the value is true, then the
body of the loop is executed repetedly until the test condition
becomes false. When the test condition becomes false the control
is transferred to next statement.


The general form is:
While(test condition)
      {
body of the loop;
}


next statement;


Ex:
#include<stdio.h>
main()
{
int I;
I=1;
While(I<5)
{
printf(“god is love”);
I++;
}
}


Do…While statement
         When this statement is executed the body of the loop is
executed first. Then the test condition is evaluated. If the value is
false, the control is transferred to the next statement. If the value is
true the body of the loop is executed repeatedly until the test
condition becomes false. When the test condition becomes false
the control is transferred to the next statement.


The general form is:


Do
         {
             body of the loop;
         }
while(test condition);
next statement;


Ex:


#include<stdio.h>
main()
{
int I;
I=1;
Do
{
printf(“god is love”);
I++;
}
while(I<5)
}


For Statement:
      For statement is used to execute a statement or a group of
statements repeatedly for a known number of times.


The general form is:


For(initial condition; test condition; increment or decrement)
{
body of the loop;
}
next statement;


Ex:


#include<stdio.h>
main()
{
int I, sum;
sum=0;
for(I=1; I<=50; I++)
{
sum=sum+I;
}
printf(“sum=%d”,sum);
}


Arrays:
     An array is defined as a group of related data items that share
a common name. In computers we store information in the
memory by giving names to them. These names are called
variables.


Subscripted Variables:
     The variables which are used to represent the individual data
in the memory are called subscripted variables


The general form is:
     Array-name[subscript]


One dimensional arrays:
     An array name with only one subscript is known as one
dimensional array.
Ex:
      A [10], name [30], …


Declaration of one dimensional array:
      Arrays must be declared before it is used like other variables.


The general form is
      Data-type array-name [size];


Ex:
      Int mark[100]


Array initialization:
      We can assign initial values to the array just like we assign
values to variables when they are declared.


The general form is:
      Static data-type array-name [size] = { list of values};


Ex:
      1. Static int mark[3] ={65,87,78};
      2. static int mark[5] ={65,87,78};
3. static float mark[]={65,87,78, 65,87,78};


Ex: smallest no:


#include<stdio.h>
main()
{
int I,n,a[10],small;
printf(“Give the 10 value”);
scanf(“%d”, &n);
for(I=0; I<n; I++)
scanf(“%d”, &a[I]);
small=a[0];
for(I=1; I<n;I++)
{
if(a[I] < small)
small=a[I];
printf(“The small value is:%d”,small);
}
}


Table handling:
An one dimensional array may be horizontal or vertical. In
some applications it is necessary to represent data in horizontal
(rows) as well as in vertical (columns). This type of representation
is said to be in tabular form. A two dimensional array is needed to
represent a table in memory.


Two dimensional array
      An array with two subscripts is known as two dimensional
array.


The general form is
      Array-name[subscript1][subscript2]


Ex:
      A[2][2]


Declaration of 2-D array:
      Like one dimentional arrays two dimentional arrays must be
declared before it is used like other variables.


The general form is:
      Data-type array-name[row size][column size];
Ex:
       Int mark[5][2]


Array initialization:
       Like one dimensional arrays we can assign initial values to
2-D arrays when they are declared.


The genearal form is:
       Static data-type array-name [row size] [column size]={list of
values};


Ex:
       1. Static int mark[3][2]={1,2,3,4,5,6};
       2. Static int mark[3][2]={{1,2}, {3,4}, {5,6}};


Ex:
#include<stdio.h>
void main()
{
int i,j;
int a[2][2], b[2][2], c[2][2];
printf(“Enter the A matrix no:”);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
scanf(“%d”, &a[I][j]);
printf(“Enter the B matrix no:”);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
scanf(“%d”, &b[I][j]);
for(I=0;I<2;I++)
for(j=0;j<2;j++)
c[I][j]=a[I][j]-b[I][j];
printf(“n result of matrix isn”);
for(I=0;I<2;I++)
{
for(j=0;j<2;j++)
printf(“%d”,c[I][j]);
printf(“n”);
}
}




STRING:
Any group of characters enclosed in double quotes is a string
constant. A string is an array of characters terminated by a null
character.


Declaring String:
      The string that can hold an array of characters can be
declared as
      Char variable_name [size];


Ex:
      Char name [10], book [10];


Initializing String:
      A character array can be initialized by a string constant,
resulting in the first element of the array being set to first character
in the string, the second element to the second character and so on.
The array also receives the terminating ‘o’ in the string constant


Ex:
      Char name [9]=”computer”;
      Char name [9]={‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’o’}


Reading String:
1. By using scanf () function:
  2. By using getchar () function:
  3. By using gets () function:
  3. By using loops


By using scanf () function:
      The scanf () function with format string %s can be used to
read a string from the user.


Ex:
      Main()
      {
           char name[10];
           scanf(“%s”, name);
      }


      The disadvantage of scanf () function is that there is no way
to read a multi-word string into a single character array variable.
The scanf () function terminates its input when it encounters a
blank space


By using gets () function:
The gets () function with the array name can also be used to
read a string from the user. The gets () function overcomes the
disadvantage of the scanf () function, since it can read a string of
any length with any number of blank spaces and tabs.


Ex:
      Main()
      {
           char name [10];
           gets (name);
      }


By using loops:
      We know that a string is an array of characters, hence a string
can also be read, character by character from the user by using
loops.


STRING LIBRARY FUNCTION:
      1. strcpy() - copies a string into another string
      2. strcat() - appends one string at the end of another string
  4. strcmp()- compares two string
  5. strlen()     - finds length of a string
  6. strrev()     - reverse a string
The strlen () function:
      The strlen() function returns the count of number of
characters stored in a string.


Syntax: x=strlen(str);


#include<stdio.h>
#include<string.h>
void main()
{
char str[10];
printf(“Enter a string:”);
gets(str);
printf(“The length of the string is %d”, strlen(str));
}


The strcpy() function:
      The strcpy() function is used to copy the contents of one
string to another. The general form is
      Strcpy(string1,string2);


Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str[10],cpy[10];
printf(“Enter a string:”);
gets(str);
strcpy(cpy,str);
printf(“The source string is %s”,str);
printf(“The copied string is %s”,cpy);
}




The strcat() function:
      The strcat() function concatenates the source string at the end
of the target string. The strcat() function takes two arguments for
concatenating.


The general form is:
      Strcat(string1, string2);


Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str [10],cat [10];
printf(“Enter a string:”);
gets(str);
printf(“Enter another string:”);
gets(cat);
strcat(str,cat);
printf(“The concatenated string is :%s”,str);
}


The strrev() function:
      The strrev() function is used to reverse a string. This function
takes only one argument.


The general form is:
      X=strrev(string);


Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char x[10];
printf(“Enter the string:”);
gets(x);
printf(“The reversed string is :%s”,strrev(x));
}


The strcmp() function:
         The strcmp() function compares two strings to find whether
the strings are equal or not.


The general form is:
         Strcmp(string1,string2);


Ex:
#include<stdio.h>
#include<string.h>
void main()
{
char str[10],cmp[10];
int x;
printf(“Enter a string:”);
gets(str);
printf(“Enter another string:”);
gets(cmp);
x=strcmp(str,cmp);
if(x = = 0)
puts(“Strings are equal”);
else if (x>0)
printf(“String %s is greater than string %s”, str, cmp);
else
printf(“String %s is greater than string %s”, cmp, str);
}




FUNCTION:
       A function is a self-contained program segment that performs
some specific well-defined task when called. Function break large
computing tasks in to smaller ones. C programs generally consist
of many small functions rather than few big ones. Every c program
consists of one or more functions, but there should be at least one
function which must be main ().


       C functions may be classified into two categories namely
1. user-defined functions
2. library function


The main () function that we have seen so far in the programs is an
example of an user-defined function.


Printf (), scanf (), etc.. are the examples of library functions.


Ex:
#include<stdio.h>
void func();
void main()
{
printf(“n Inside main function”);
func();
printf(“n again inside main function”);
}
void func()
{
printf(“n inside func function”);
}


Defining a Function:
A function definition consists of two parts.
    1. argument declaration
    2. body of the function


Syntax:
Return-type function-name (argument list) ->argument decla
         {
              declarations;
              statements;                        ->body fun
              return(expression);
         }


Ex:
Int add (int x, int y)
{
Int z;
Z=x+y;
Return (z);
}


TYPE OF FUNCTION:
         A function depending upon the arguments present or not and
whether a value is returned or not. There are 4 types of classified
1. Function with no arguments and no return values.
      2. Function with no arguments and return values
      3. Function with arguments and no return values.
      4. Function with arguments and return values.


Function With No Arguments And No Return Values:
      In this type of function no value is passed from the caller
function to the called function and no value is returned to the
caller function from called function.


Ex:
#include<stdio.h>
void main()
{
void message ();
printf(“n I am in main function);
message();
printf(“n I am back in main function”);
getch();
}
void message()
{
printf(“nn I am in user defined function”);
return;
}


Function With No Arguments And Return Values:
      In this type of function no value is passed from the caller
function to the called function (user defined function) but some
value is returned to the caller function from the called function.
Ex:
#include<stdio.h>
main()
{
float f;
clrscr();
f=area();
printf(“n the area is %f”,f);
getch();
}
float area()
{
float a,b,area;
printf(“n enter the length and breadth of a rectangle:”);
scanf(“%f %f ”, &a, &b);
area = a*b;
return(area);
}


Function With Arguments And No Return Values:
      In this type of function, some values are passed from the
caller function and no values are returned to the caller function
from the called function.
Ex:
#include<stdio.h>
main()
{
float a,b;
void area_rectangle (float, float);
clrscr();
printf(“n enter the length & breadth:”);
scanf(“%f %f”, &a, &b);
area_rectangle (a,b);
getch();
}
void area_rectangle(x,y)
float x,y;
{
float area;
area=x*y;
printf(“n area of rectangle is %f”, area);
return;
}


Function With Arguments And Return Values:
      In this type of functions some values are passed to the called
function from the caller function and some values are passed back
to the caller function from the called function.
Ex:
#include <stdio.h>
main ()
{
float area(float, float), f,b,h;
clrscr();
printf(“n enter the breadth and height of a triangle:”);
scanf(“%f %f”, &b, &h);
f=area(b,h);
printf(“n the area is %f”,f);
getch();
}
float area(float b, float h)
{
float area;
area=b*h;
return(area);
}


Example for Type of Function’s:
/* FUNCTION WITH NO ARGUMENTS AND NO RETURN
VALUES
#include<stdio.h>
#include<conio.h>
void name();
void main()
{
clrscr();
name();
getch();
}
void name()
{
char empname[25];
printf("Enter the employee name:");
scanf("%s", empname);
printf("The employee name is %s", empname);
}


FUNCTION WITH RETURN VALUES AND NO ARGUMENTS
#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
clrscr();
printf("is %d", sum());
getch();
}
int sum()
{
int i,n,result=0;
printf("Enter the limit:");
scanf("%d", &n);
printf("Sum of even numbers within %d", n);
for(i=2;i<=n;i+=2)
{
result +=i;
}
return(result);
}


FUNCTION WITH ARGUMENTS AND NO RETURNVALUES
#include<stdio.h>
#include<conio.h>
void simple(float,float,int);
float principal,rate;
int year;
void main()
{
clrscr();
printf("Enter principal, rate of interest & no. of years n");
scanf("%f %f %d", &principal, &rate, &year);
simple(principal,rate,year);
getch();
}
void simple(float principal, float rate, int year)
{
float simple_interest=0.0;
simple_interest = (principal * rate * year)/100;
printf("The simple interest is %.2f", simple_interest);
}
FUNCTION WITH ARGUMENTS AND RETURN VALUES
#include<stdio.h>
#include<conio.h>
int sum(int x);
void main()
{
int n;
clrscr();
printf("Enter the limit:");
scanf("%d", &n);
printf("Sum of first %d natural numbers is %d", n, sum(n));
getch();
}
int sum(int x)
{
int i, result=0;
for(i=1; i<=x;i++)
result +=i;
return(result);
}
RECURSION:
         In c it is possible to call a function. Recursion is a process by
which a function calls itself repeatedly until some specified
condition has been satisfied. A function is called recursive if a
statement within the body of a function calls the same function.
Recursion is a process of defining something in terms of itself.


Ex:
#include<stdio.h>
Long fact (long);
void main()
{
long num, fac;
printf(“Enter a number:”);
scanf(“%ld”, &num);
fac=fact(num);
printf(“The factorial of %ld is %ld”, num, fac);
}
long fact (long x)
{
if(x<=1)
return (1);
else
return(x * fact(x-1));
}
NESTED OF FUNCTION:
      We have seen programs using functions called only from the
main() function. But there are situations, where functions other
than main() can call any other function(s) used in the program.
This process is referred as nested of functions.
Ex:
#include<stdio.h>
void func_1 ();
void func_2 ();
void main ()
{
printf(“n inside main function”);
func_1 ();
printf(“n again inside main function”);
}
void func_1 ()
{
printf(“n inside function 1”);
func_2 ();
printf(“n again inside function 1”);
}
void func_2 ()
{
printf(“n inside function 2”);
}
STORAGE CLASSES:
       The variables are associated with certain properties such as
scope and lifetime in a program. By scope of a variable means that
the portions of the program in which it can be used. The lifetime of
a variable is the period of time during which the value is available
in memory.
       The four different storage class
    1. automatic storage class
    2. external storage class
    3. static storage class
    4. register storage class


AUTOMATIC STORAGE CLASS
       Variables defined inside a block and are local to the block in
which they are declared, are refered as automatic variables as local
variables. Automatic variables can only be accessed by the block
in which they are declared. Any another block cannot access its
value.
Ex:
#include<stdio.h>
#include<conio.h>
/*void main()
{
auto int x=5;
{
auto int x=4;
{
auto int x=3;
clrscr();
printf("%d t",x);
}
printf("%d t",x);
}
printf("%d t",x);
getch();
}


EXTERNAL STORAGE CLASS:
      Variables that are both alive and active throughout the entire
program are called as external variables also refered as global
variables. Global variables can be accessed by any function in the
program. Global variables are also stored in the memory. When an
external variable is not initialized it takes a value of zero.
Ex:
int value;
void main()
{
value = 100;
clrscr();
test1();
test2();
test3();
printf("%dn", value);
getch();
}
test1()
{
value += 100;
printf("%dn", value);
}
test2()
{
value = 1000;
printf("%dn", value);
}
test3()
{
value += 100;
printf("%dn", value);
}


STATIC STORAGE CLASS:
      The world static in general refers to anything that is insert to
change. In a program if static variables are declared within
individual blocks they are local to the block in which they are
declared. The static variables retain their values throughout the life
of the program.
Ex:
void main()
{
clrscr();
sum();
sum();
sum();
sum();
getch();
}
sum()
{
static int x=1;
printf("%d", x);
x=x+1;
}*/


REGISTER STORAGE CLASS:
      The register storage class is similar to the auto storage class
since the variables defined inside a block are local to the block in
which it is specified. Register variable can only be accessed by the
block in which it is declared. Its value cannot be accessed by any
other function
Ex:
void main()
{
register int x;
clrscr();
for (x=1; x<=10; x++)
printf("%d",x);
getch();
}


STRUCTURES:
      A structure is a collection of one or more variables grouped
under a single name for easy manipulation. The variables in a
structure, unlike those in an array, can be of different variable
types. A structure can contain any of C’s data types, including
arrays and other structures. Each variable within a structure is
called a member of the structure.


Defining a structure:
      A structure definition contains keyword struct and a user
defined structure-name followed by the members of the structure
with in braces.


The general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
};


Ex:
Struct student
{
int no;
int age;
char sex;
};
Structure declaration:
       Structure declaration means defining variables to the already
defined structure. We can define variables in two ways.
     1. variable definition along with the structure definition
     2. variable definition using structure-name any where in the
       program
The first general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
} variable-1, variable-2,…….variable-n;


Ex:
Struct student
{
int no;
int age;
char sex;
}s1,s2,s3;


The second general form is:
Struct structure-name
{
data-type member-1;
data-type member-2;
……………..
…………….
data-type member-n;
};
structure-name variable-1, variable-2,…….variable-n;


Ex:
Struct student
{
int no;
int age;
char sex;
};
student s1, s2, s3;


Giving values to structure members:
       Dot operator or member operator ‘.’ Is used to give data to
the structure variables individual members.


The general form is;
Structure variable . member-name


       The variable name with a period and the member name is
used like any ordinary variable


Ex:
Struct student
{
int no;
int age;
char sex;
}s1;
       the above declaration has a variable s1 having three
members. The values or data to the members of the variable can
be given by any one of the following method.
(i) using keyword;
scanf(“%d”, &s1.no);
       scnaf(“%d”, &s1.age);
       scanf(“%c”,&s1.sex);
(ii) using assignment statement:
       s1.no = 100;
       s1.age = 18;
       s1.sex = ‘m’;


Example:
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
char sex;
int no;
float salary;
}d1;
clrscr();
printf("Give the values to the membersn");
printf("Give the sex.......");
scanf("%c", &d1.sex);
printf("Give the number....");
scanf("%d", &d1.no);
printf("Give the salary....");
scanf("%f", &d1.salary);
printf("n");
printf("Employee - details n");
printf("Sex: %cn", d1.sex);
printf("Number: %dn", d1.no);
printf("Salary: %fn", d1.salary);
getch();
}


Array of Structures:
      Array of structures are defined as a group of data of different
data types stored in a consecutive memory location with a common
variable name called an array of structures.


Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
struct student
{
int no;
int age;
char sex;
};
struct student s1[2];
int i;
clrscr();
for(i=0;i<2;i++)
{
printf("Enter number,age,sexn");
scanf("%d %d %c", &s1[i].no, &s1[i].age, &s1[i].sex);
}
for(i=0;i<2;i++)
printf("%d %d %cn", s1[i].no, s1[i].age, s1[i].sex);
getch();
}


Structures with structures [Nested Structure]:
         When a structure is declared as a member of another
structure then it is called structure within structure or nested
structure.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
struct hostel_detail
{
int hostel_room_no;
char food;
int deposit_amount;
};
struct student
{
char name[10];
int no;
char branch[5];
struct hostel_detail h1;
};
static struct student s1={"Raja", 100, "Ct", 10, 'v', 2000};
clrscr();
printf("%s %d %s %d %c %d", s1.name, s1.no, s1.branch,
s1.h1.hostel_room_no,
s1.h1.food, s1.h1.deposit_amount);
getch();
}


Passing Entire Structure To Function:
      In this method, the entire structure is passed as an argument
to the function. Note that when using a structure as a parameter,
remember that the type of the argument in the function call
statement must match the type of a parameter (list if any), in the
function prototype. Since the function is working on a copy of the
structure, any changes made to the structure members within the
function are not reflected in the orginal structure.


Ex:
#include<stdio.h>
#include<conio.h>
void employ(struct employee emp);
struct employee
{
int empno;
char empname[10];
}emp1;
void main()
{
printf("Enter employee no and name:");
scanf("%d %s", &emp1.empno, emp1.empname);
employ(emp1);
}
void employ(struct employee emp)
{
printf("n the employee no is :%d", emp.empno);
printf("n the employee name is:%s", emp.empname);
}


FILES
      Files are used for permanent storage of large amount of data.
A file can be used to write and/or read data from a disk. File
handling in C is very simple, since it essentially treats a file as just
a stream of characters and allows input and output in a file.
So far we used scanf and printf function to read and write data to
and from the computers through the console. If computers deal
with large amount of data as input and output (read, write) then
both methods are not efficient. The best way is to use files to give
data to the computers and get data from the computers.


Defining a File:
A file is defined as FILE in the header file stdio.h therefore
all files should be declared as type FILE before they are used.


The general form is:
      FILE *pointer variable;


Opening a File:
      Before we read from a file or write to a file, we must open
the file. Opening establishes a link between the program and the
operating system.


The general form is:
FILE *pointer variable;
Pointer variable = fopen (“file name”, “mode”);


Ex:
FILE *a;
a = fopen (“exam.txt”, “r”);


Closing the file:
      An opened file must be closed after all operations on it have
been completed.
The general form is:
fclose (pointer variable);


Ex:
……………….
……………….
FILE *a, *b;
a= fopen(“exam.txt”, “r”);
b= fopen(“exam.txt”,”w”);
…………………..
………………….
fclose(a);
fclose(b);


Reading a file:
      fscanf function is used to read data from a file.


The general form is:
fscanf(pointer variable, “control string”,list);


Ex:
fscanf(a, “%d%d”, &x,&y);
Writing to a file:
      fprintf function is used to write data into a file


The general form is:
fprintf (pointer variable, “control string”,list);


Ex:
fprintf(a,”%d%d”, x,y);


Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int empno;
char empname[20],deptname[20];
FILE *ptr;
clrscr();
ptr=fopen("exam.dat","w");
printf("Enter ename, eno and edept:");
scanf("%s %d %s", &empname, &empno, &deptname);
fprintf(ptr, "%s %d %s",empname, empno, deptname);
fclose(ptr);
ptr=fopen("exam.dat","r");
fscanf(ptr, "%s %d %s", &empname, &empno, &deptname);
printf("n Employee Name:%s", empname);
printf("n Employee Number:%d", empno);
printf("n Department Name:%s", deptname);
fclose(ptr);
getch();
}


Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int c;
FILE *fptr;
clrscr();
printf("Enter the text to store in the filen");
fptr=fopen("example.txt","w");
while((c=getc(stdin))!=EOF)
fputc(c,fptr);
fclose(fptr);
printf("n the contents of the file is n");
fptr=fopen("example.txt","r");
do
{
c=fgetc(fptr);
putchar(c);
}
while (c!= EOF);
fclose(fptr);
getch();
}


Random Access Function:
      Reading and writing operations on any file are normally
sequential. This is achieved by a system-controlled pointer, which
points the position immediately, after the last character is read or
written. Which points the position immediately, after the last
character is read or written. However, with the help of random
access functions a C programmer can move the file pointer to any
desired position in the file
      One advantage of a random access file over other files is that,
a character can be written or read from the file by specifying the
exact location where the operation is to take place.
The random access functions used in a file are
   1. the fseek() function
   2. the ftell() function
   3. the rewind() function


The fseek() Function:
      The fseek() function is used to move the file pointer to any
desired location within a file. It can be used to increment or
decrement the file pointer by any number of positions in the file.


The general form is:
fseek (fptr, long int offset, int position);


Ex:
fseek (fptr, 5L, 0);


The Position:
            Value            Meaning
                 0           Beginning of the file
                 1           Current position of the file
                 2           End of the file
The ftell() Function:
      The ftell() function returns the current position of the file
pointer in the file.


The general form is:
ftell(fptr);


The rewind () function:
      The rewind () function resets the file pointer to the beginning
of the file.


The general form is:
rewind (fptr);


Merging Two Files:
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
char *a;
FILE *f1, *f2, *f3;
clrscr();
f1=fopen("student.txt","w");
printf("Enter the content of file1n");
gets(a);
fputs(a,f1);
fclose(f1);
f2=fopen("student1.txt","w");
printf("Enter the content of file2n");
gets(a);
fputs(a,f2);
fclose(f2);
f1=fopen("student.txt","r");
f3=fopen("student2.txt","w");
printf("n the content of file1 is n");
while (fgets(a, strlen(a)+1,f1)!=NULL)
{
fputs(a,f3);
printf("%s",a);
}
fclose(f1);
fclose(f3);
f2=fopen("student1.txt","r");
f3=fopen("student2.txt","a");
printf("n The content of file2 is n");
while(fgets(a,strlen(a)+1,f2)!=NULL)
{
fputs(a,f3);
printf("%s",a);
}
fclose(f2);
fclose(f3);
f3=fopen("student2.txt","r");
printf("n the content of file3 is n");
while (fgets (a, strlen(a) + 1,f3)!=NULL)
printf("%s",a);
getch();
}


POINTERS:
      A pointer is a variable, which represents the location (not the
value) of a data item, such as a variable or an array element.
Advantages:
    1. pointers increase the execution speed of the program.
    2. pointers reduce the length and complexity of a program.
    3. pointers enable us to access a variable that is defined outside
      the pointers are used to pass information back and forth
      between a function and its reference point.
Pointer declaration:
         All pointer variables must be declared before it is used in the
program like other variable.


The general form is:
Data-type * variable;


Assigning the address of the variable to pointer variable:
         The address of the variables can be got with the help of the
address operator &. The operator & immediately preceding a
variable returns the address of the variable associated with it.


Ex:
int *a;
int x;
a = &x;


Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=10, *ptr;
clrscr();
ptr=&a;
printf("n initial values a=%d &b=%d",a,b);
b=*ptr;
printf("n changed values a=%d &b=%d",a,b);
printf("n value of ptr is %d", ptr);
getch();
}


Pointers and Array:
      An array is actually a pointer to its 0th element. Dereferencing
the array name will give the value stored in the 0th element of the
array.


Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,a[25],*ptr;
clrscr();
printf("Enter the number of elements:");
scanf("%d", &n);
printf("Enter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
*ptr=a[0];
for(i=0;i<n;i++)
if(a[i]>*ptr)
*ptr=a[i];
printf("The biggest element in the array is %d",*ptr);
getch();
}


Pointer to Function:
      A pointer to a function contains the address of the funcntion
in memory. A function, like a variable has an address location in
the memory, therefore it is possible to declare a pointer to a
function,


Ex:
#include<stdio.h>
#include<conio.h>
int sum(int (*) (int),int);
int square(int);
void main()
{
int num;
clrscr();
printf("Enter any integer:");
scanf("%d", &num);
printf("The sum of squares of first %d numbers is %d", num,
sum(square, num));
}
int sum(int (*fptr)(), int n)
{
int add, i;
for(i=1;i<=n;i++)
add += (*fptr) (i);
return 0;
}
int square (int i)
{
getch();
return(i*i);
}

More Related Content

What's hot

Branching statements
Branching statementsBranching statements
Branching statementsArunMK17
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programmingTejaswiB4
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and UnionsDhrumil Patel
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programmingKamal Acharya
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 

What's hot (20)

Branching statements
Branching statementsBranching statements
Branching statements
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
C basics
C   basicsC   basics
C basics
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
structure and union
structure and unionstructure and union
structure and union
 
Basic structure of c programming
Basic structure of c programmingBasic structure of c programming
Basic structure of c programming
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
C if else
C if elseC if else
C if else
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Function in C
Function in CFunction in C
Function in C
 
Structure in C
Structure in CStructure in C
Structure in C
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 

Similar to C fundamental

C operators
C operatorsC operators
C operatorsGPERI
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2yasir_cesc
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02CIMAP
 
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVINGGOWSIKRAJAP
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentalsumar78600
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYRajeshkumar Reddy
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptxrinkugupta37
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators pptViraj Shah
 
Microcontroller lec 3
Microcontroller  lec 3Microcontroller  lec 3
Microcontroller lec 3Ibrahim Reda
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariTHE NORTHCAP UNIVERSITY
 
Introduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoIntroduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoMark John Lado, MIT
 

Similar to C fundamental (20)

C operators
C operatorsC operators
C operators
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
What is c
What is cWhat is c
What is c
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Unit 1
Unit 1Unit 1
Unit 1
 
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING18CSS101J PROGRAMMING FOR PROBLEM SOLVING
18CSS101J PROGRAMMING FOR PROBLEM SOLVING
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
 
What is c
What is cWhat is c
What is c
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Class_IX_Operators.pptx
Class_IX_Operators.pptxClass_IX_Operators.pptx
Class_IX_Operators.pptx
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 
Microcontroller lec 3
Microcontroller  lec 3Microcontroller  lec 3
Microcontroller lec 3
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
Introduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John LadoIntroduction to C Language - Version 1.0 by Mark John Lado
Introduction to C Language - Version 1.0 by Mark John Lado
 
C programming session3
C programming  session3C programming  session3
C programming session3
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

C fundamental

  • 1.
  • 2. =======0====================================== Year 1972 at Bell telephone laboratories (AT &T) by DENNIS RITCHIE. Features of ‘C’ language: 1. it is a flexible high level structured program language 2. it includes the features of low level language like assembly language. 3. it is much faster and efficient. 4. it has a number of built-in functions, which makes the programming task simple The ‘C’ language is used for developing: 1. database system. 2. graphics packages. 3. scientific and engineering applications. Format of C program: Headerfile include Main() { variable declaration;
  • 3. program statements; } Ex: #include<stdio.h> main() { printf(“god is great”); } Keywords: Keywords are words belongs to C language. The users have no right to change its meaning. Ex: auto, goto, if, int, while, do, switch, case, char, else…..
  • 4. Datatype: TYPE SIZE(bits) RANGE char 8 -128 to 127 unsigned char 8 0 to 255 int 16 -32,768 to 32,767 unsigned int 16 0 to 65,535 long int 32 -2,147,483,648 to 2,147,483,647 unsigned long int 32 0 to 4,294,967,295 float 32 3,4E-38 to 3,4E+38 double 64 1.7E-308 to 1.7E+308 long double 80 3.4E-4932 to 1.1E+4932
  • 5. Variables: C variable refers to the name given to the memory location to store data. A particular memory location is given only one name. Yet this name is called a variable because this memory location can store sequence of different values during the execution of the same program. Rules: 1. a variable name is formed with alphabets, digits and a special character underscore( _ ) 2. the first character must be an alphabet. 3. no special characters are used other than underscore 4. both upper case and lower case letters are used. Declaration variables: Syntax: Data-type list of variables; Ex: int x,y,z; initializing variables: syntax: data-type variable=initial value;
  • 6. Ex: int a=10; float b=43.3; comment statement: comment statements are non-executable statements. 1. single line statement // 2. paragraph statement /* */ OPERATORS: An operator is a symbol which represents some operation that can be performed on data. There are eight operators available in C to carry out the operations. They are 1. arithmetic operators 2. relational operators 3. logical operators 4. short hand assignment operators 5. conditional operators Arithmetic operators: Arithmetic operators are used to do arithmetic calculations. There are 2 types (i) binary operators
  • 7. (ii) unary operators Binary operator: BO need two operands for operations. Operator operation Ex + addition x=5+6 - subtraction x=10-5 * multiplication x=5*4 / division x=5/3 =1 % modulo operator x=5%3 =2 Unary operators: UO need only one operands for operation. Operator operation Ex ++ increment i++ -- decrement i— Relational operators: RO are used to find out the relationship between two operands. They are Operator operation Ex > greater than a>b
  • 8. < less than a<b >= greater than equal to a<=b <= less than equal to a>=b == equal to a= =b != not equal to a!=b Logical operators: LO are used to find out the relationship between two or more relational expressions. They are Operator operation Ex && AND (a>b)&&(a>c) || OR (a>b)||(a>c) Short-hand assignment operators: SHAO are operators which are used to simplify the coding of certain type of assignment statement. The general form is Variable operator = expression Variable = user define name Operator = +,-,*,/,%
  • 9. Ex: Operator operation Ex += value of LHS variable will be added to the x = x +10can be RHS value and is written as x+=10 Assigned to LHS variable Conditional Operators: The CO ? and : are used to build simple conditional expression. It has three operands. So it is called ternary operator. The general form is Expression1 ? expression2: expression3; Expression1 is evaluated first. If it is true expression2 is evaluated.if expression1 if false expression3 is evaluated. Ex: Sum = a>b ? a: b; Input statement: Scanf () function:
  • 10. Scanf () is used to give data to the variables using keyboard. The general form is Scanf (“control string”, &variable1, ….&variable n); Ex: Scanf(“%d”,&a); This statement reads a integer data and assigns to variable a Output statement: Printf () function: Printf () is used to output the results of the program to the user through VDU. The general form is Printf(“control string”, list); Conversion character table: C single character D decimal integer F floating point value
  • 11. H short-integer S string CONTROL STATEMENTS: 1. Unconditional statements 2. Conditional (or) Decision making statements 3. Looping Statement Unconditional Statement: 1. goto statement goto statement is used to transfer the program control unconditionally from one point to another. The general form is: goto label; The label is the name given to the point where the control has to be transferred The general form is Label:statement; Conditional Statement:
  • 12. CO are used to skip or to execute a group of statements based on the result of some condition. 1. if statement 2. if….else statement 3. else….if ladder 4. nested if statement 5. switch statement (i) Simple if statement: Simple if statement is used to execute or skip one statement or group of statements for a particular condition. The general form is If(test condition) { statement block; } next statement; Ex:
  • 13. #include<stdio.h> void main() { int mark; char grade; scanf(“%d %c”, &mark, &grade); if(grade = =’a’) { mark=mark+10; } printf(“%d”,mark); } (ii) if….else statement: if…else statement is used to execute one group of statements if the test condition is true or other group if the test condition is false. The general form is If(test condition) { statement block-1;
  • 14. } else { statement block-2; } next statement; Ex: #include<stdio.h> void main() { int mark; scanf(“%d”, &mark); if(mark=>35) printf(“pass”); else printf(“fail”); } (iii) else…..if ladder:
  • 15. else….if ladder statement is used to take multiway decision. This statement is formed by joining if….else statement in which each else conditions another if….else The general form is If(test condition-1) { statement block-1; } else if(test condition-2) { statement block-2; } ………………………… ……………………… ……………. else if(test condition-n) { statement block-n; } else default statement;
  • 16. next statement; Ex: #include<stdio.h> void main() { int day; printf(“give a number between 1 to 7n”); scanf(“%d”, &day); if(day= =1) printf(“sundayn”); if(day= =2) printf(“Mondayn”); if(day= =3) printf(“tuesdayn”); if(day= =4) printf(“wednesdayn”); if(day= =5) printf(“thursdayn”); if(day= =6) printf(“fridayn”); if(day= =7) printf(“saturdayn”);
  • 17. else printf(“enter the currect value”n); } Nested if….else statement: This statement is formed by joining if….else statements either in the if block or in the else block or both The general form is: If(test condition-1) { if(test condition-2) { statement block-1; } else { statement block-2; } else { statement block-3;
  • 18. } next statement; when this statement is executed, the computer first evaluates the value of test condition-1. if it is false control will be transferred to statement block-3. if it is true test condition-2 is evaluated. If it is true statement block-1 is executed and control is transferred to next statement else statement block-2 is executed and control is transferred to next statement. Ex: #include<stdio.h> main() { int a,b,c; printf(“enter 3 no”); scanf(“%d %d%d”, &a,&b,&c); if(a>b) { if(a>c) printf(“A is big=%d”,a); else
  • 19. printf(“B is big=%d”,c); } else { if(b>c) printf(“B is big=%d”,b); else printf(“C is big=%d”,c); } } Switch Statement: Switch statement is an extension of if…..else statement. This permits any number of branches. The general forms: Switch (expression) { case label-1: statement block-1; break; case label-2:
  • 20. statement block-2; break; ………………………….. ………………………….. case label-n: statement block-n; break; default: default statement; break; } next statement Ex: #include<stdio.h> main() { int day; printf(“Enter the no 1 to 7n”); scanf(“%d”, &day); switch(day) {
  • 21. case 1: printf(“Sunday n”); break; case 2: printf(“Monday n”); break; case 3: printf(“Tuesday n”); break; case 4: printf(“Wednesday n”); break; case 5: printf(“Thursday n”); break; case 6: printf(“Friday n”); break; case 7: printf(“Saturday n”); break; default:
  • 22. printf(“Enter the currect no:n”); break; } } LOOPING STATEMENTS: Looping statements are used to execute a group of statements repeatedly until some condition is satisfied. The looping statements are 1. while statement 2. do…while statement 3. for statement While statement: First evaluates the test condition. If the value is false, the control is transferred to next statement. If the value is true, then the body of the loop is executed repetedly until the test condition becomes false. When the test condition becomes false the control is transferred to next statement. The general form is: While(test condition) {
  • 23. body of the loop; } next statement; Ex: #include<stdio.h> main() { int I; I=1; While(I<5) { printf(“god is love”); I++; } } Do…While statement When this statement is executed the body of the loop is executed first. Then the test condition is evaluated. If the value is false, the control is transferred to the next statement. If the value is true the body of the loop is executed repeatedly until the test
  • 24. condition becomes false. When the test condition becomes false the control is transferred to the next statement. The general form is: Do { body of the loop; } while(test condition); next statement; Ex: #include<stdio.h> main() { int I; I=1; Do { printf(“god is love”); I++;
  • 25. } while(I<5) } For Statement: For statement is used to execute a statement or a group of statements repeatedly for a known number of times. The general form is: For(initial condition; test condition; increment or decrement) { body of the loop; } next statement; Ex: #include<stdio.h> main() { int I, sum; sum=0;
  • 26. for(I=1; I<=50; I++) { sum=sum+I; } printf(“sum=%d”,sum); } Arrays: An array is defined as a group of related data items that share a common name. In computers we store information in the memory by giving names to them. These names are called variables. Subscripted Variables: The variables which are used to represent the individual data in the memory are called subscripted variables The general form is: Array-name[subscript] One dimensional arrays: An array name with only one subscript is known as one dimensional array.
  • 27. Ex: A [10], name [30], … Declaration of one dimensional array: Arrays must be declared before it is used like other variables. The general form is Data-type array-name [size]; Ex: Int mark[100] Array initialization: We can assign initial values to the array just like we assign values to variables when they are declared. The general form is: Static data-type array-name [size] = { list of values}; Ex: 1. Static int mark[3] ={65,87,78}; 2. static int mark[5] ={65,87,78};
  • 28. 3. static float mark[]={65,87,78, 65,87,78}; Ex: smallest no: #include<stdio.h> main() { int I,n,a[10],small; printf(“Give the 10 value”); scanf(“%d”, &n); for(I=0; I<n; I++) scanf(“%d”, &a[I]); small=a[0]; for(I=1; I<n;I++) { if(a[I] < small) small=a[I]; printf(“The small value is:%d”,small); } } Table handling:
  • 29. An one dimensional array may be horizontal or vertical. In some applications it is necessary to represent data in horizontal (rows) as well as in vertical (columns). This type of representation is said to be in tabular form. A two dimensional array is needed to represent a table in memory. Two dimensional array An array with two subscripts is known as two dimensional array. The general form is Array-name[subscript1][subscript2] Ex: A[2][2] Declaration of 2-D array: Like one dimentional arrays two dimentional arrays must be declared before it is used like other variables. The general form is: Data-type array-name[row size][column size];
  • 30. Ex: Int mark[5][2] Array initialization: Like one dimensional arrays we can assign initial values to 2-D arrays when they are declared. The genearal form is: Static data-type array-name [row size] [column size]={list of values}; Ex: 1. Static int mark[3][2]={1,2,3,4,5,6}; 2. Static int mark[3][2]={{1,2}, {3,4}, {5,6}}; Ex: #include<stdio.h> void main() { int i,j; int a[2][2], b[2][2], c[2][2]; printf(“Enter the A matrix no:”); for(I=0;I<2;I++)
  • 31. for(j=0;j<2;j++) scanf(“%d”, &a[I][j]); printf(“Enter the B matrix no:”); for(I=0;I<2;I++) for(j=0;j<2;j++) scanf(“%d”, &b[I][j]); for(I=0;I<2;I++) for(j=0;j<2;j++) c[I][j]=a[I][j]-b[I][j]; printf(“n result of matrix isn”); for(I=0;I<2;I++) { for(j=0;j<2;j++) printf(“%d”,c[I][j]); printf(“n”); } } STRING:
  • 32. Any group of characters enclosed in double quotes is a string constant. A string is an array of characters terminated by a null character. Declaring String: The string that can hold an array of characters can be declared as Char variable_name [size]; Ex: Char name [10], book [10]; Initializing String: A character array can be initialized by a string constant, resulting in the first element of the array being set to first character in the string, the second element to the second character and so on. The array also receives the terminating ‘o’ in the string constant Ex: Char name [9]=”computer”; Char name [9]={‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’o’} Reading String:
  • 33. 1. By using scanf () function: 2. By using getchar () function: 3. By using gets () function: 3. By using loops By using scanf () function: The scanf () function with format string %s can be used to read a string from the user. Ex: Main() { char name[10]; scanf(“%s”, name); } The disadvantage of scanf () function is that there is no way to read a multi-word string into a single character array variable. The scanf () function terminates its input when it encounters a blank space By using gets () function:
  • 34. The gets () function with the array name can also be used to read a string from the user. The gets () function overcomes the disadvantage of the scanf () function, since it can read a string of any length with any number of blank spaces and tabs. Ex: Main() { char name [10]; gets (name); } By using loops: We know that a string is an array of characters, hence a string can also be read, character by character from the user by using loops. STRING LIBRARY FUNCTION: 1. strcpy() - copies a string into another string 2. strcat() - appends one string at the end of another string 4. strcmp()- compares two string 5. strlen() - finds length of a string 6. strrev() - reverse a string
  • 35. The strlen () function: The strlen() function returns the count of number of characters stored in a string. Syntax: x=strlen(str); #include<stdio.h> #include<string.h> void main() { char str[10]; printf(“Enter a string:”); gets(str); printf(“The length of the string is %d”, strlen(str)); } The strcpy() function: The strcpy() function is used to copy the contents of one string to another. The general form is Strcpy(string1,string2); Ex:
  • 36. #include<stdio.h> #include<string.h> void main() { char str[10],cpy[10]; printf(“Enter a string:”); gets(str); strcpy(cpy,str); printf(“The source string is %s”,str); printf(“The copied string is %s”,cpy); } The strcat() function: The strcat() function concatenates the source string at the end of the target string. The strcat() function takes two arguments for concatenating. The general form is: Strcat(string1, string2); Ex: #include<stdio.h>
  • 37. #include<string.h> void main() { char str [10],cat [10]; printf(“Enter a string:”); gets(str); printf(“Enter another string:”); gets(cat); strcat(str,cat); printf(“The concatenated string is :%s”,str); } The strrev() function: The strrev() function is used to reverse a string. This function takes only one argument. The general form is: X=strrev(string); Ex: #include<stdio.h> #include<string.h> void main()
  • 38. { char x[10]; printf(“Enter the string:”); gets(x); printf(“The reversed string is :%s”,strrev(x)); } The strcmp() function: The strcmp() function compares two strings to find whether the strings are equal or not. The general form is: Strcmp(string1,string2); Ex: #include<stdio.h> #include<string.h> void main() { char str[10],cmp[10]; int x; printf(“Enter a string:”); gets(str);
  • 39. printf(“Enter another string:”); gets(cmp); x=strcmp(str,cmp); if(x = = 0) puts(“Strings are equal”); else if (x>0) printf(“String %s is greater than string %s”, str, cmp); else printf(“String %s is greater than string %s”, cmp, str); } FUNCTION: A function is a self-contained program segment that performs some specific well-defined task when called. Function break large computing tasks in to smaller ones. C programs generally consist of many small functions rather than few big ones. Every c program consists of one or more functions, but there should be at least one function which must be main (). C functions may be classified into two categories namely
  • 40. 1. user-defined functions 2. library function The main () function that we have seen so far in the programs is an example of an user-defined function. Printf (), scanf (), etc.. are the examples of library functions. Ex: #include<stdio.h> void func(); void main() { printf(“n Inside main function”); func(); printf(“n again inside main function”); } void func() { printf(“n inside func function”); } Defining a Function:
  • 41. A function definition consists of two parts. 1. argument declaration 2. body of the function Syntax: Return-type function-name (argument list) ->argument decla { declarations; statements; ->body fun return(expression); } Ex: Int add (int x, int y) { Int z; Z=x+y; Return (z); } TYPE OF FUNCTION: A function depending upon the arguments present or not and whether a value is returned or not. There are 4 types of classified
  • 42. 1. Function with no arguments and no return values. 2. Function with no arguments and return values 3. Function with arguments and no return values. 4. Function with arguments and return values. Function With No Arguments And No Return Values: In this type of function no value is passed from the caller function to the called function and no value is returned to the caller function from called function. Ex: #include<stdio.h> void main() { void message (); printf(“n I am in main function); message(); printf(“n I am back in main function”); getch(); } void message() { printf(“nn I am in user defined function”);
  • 43. return; } Function With No Arguments And Return Values: In this type of function no value is passed from the caller function to the called function (user defined function) but some value is returned to the caller function from the called function. Ex: #include<stdio.h> main() { float f; clrscr(); f=area(); printf(“n the area is %f”,f); getch(); } float area() { float a,b,area; printf(“n enter the length and breadth of a rectangle:”); scanf(“%f %f ”, &a, &b); area = a*b;
  • 44. return(area); } Function With Arguments And No Return Values: In this type of function, some values are passed from the caller function and no values are returned to the caller function from the called function. Ex: #include<stdio.h> main() { float a,b; void area_rectangle (float, float); clrscr(); printf(“n enter the length & breadth:”); scanf(“%f %f”, &a, &b); area_rectangle (a,b); getch(); } void area_rectangle(x,y) float x,y; { float area;
  • 45. area=x*y; printf(“n area of rectangle is %f”, area); return; } Function With Arguments And Return Values: In this type of functions some values are passed to the called function from the caller function and some values are passed back to the caller function from the called function. Ex: #include <stdio.h> main () { float area(float, float), f,b,h; clrscr(); printf(“n enter the breadth and height of a triangle:”); scanf(“%f %f”, &b, &h); f=area(b,h); printf(“n the area is %f”,f); getch(); } float area(float b, float h) {
  • 46. float area; area=b*h; return(area); } Example for Type of Function’s: /* FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES #include<stdio.h> #include<conio.h> void name(); void main() { clrscr(); name(); getch(); } void name() { char empname[25]; printf("Enter the employee name:"); scanf("%s", empname); printf("The employee name is %s", empname);
  • 47. } FUNCTION WITH RETURN VALUES AND NO ARGUMENTS #include<stdio.h> #include<conio.h> int sum(); void main() { clrscr(); printf("is %d", sum()); getch(); } int sum() { int i,n,result=0; printf("Enter the limit:"); scanf("%d", &n); printf("Sum of even numbers within %d", n); for(i=2;i<=n;i+=2) { result +=i; } return(result);
  • 48. } FUNCTION WITH ARGUMENTS AND NO RETURNVALUES #include<stdio.h> #include<conio.h> void simple(float,float,int); float principal,rate; int year; void main() { clrscr(); printf("Enter principal, rate of interest & no. of years n"); scanf("%f %f %d", &principal, &rate, &year); simple(principal,rate,year); getch(); } void simple(float principal, float rate, int year) { float simple_interest=0.0; simple_interest = (principal * rate * year)/100; printf("The simple interest is %.2f", simple_interest); }
  • 49. FUNCTION WITH ARGUMENTS AND RETURN VALUES #include<stdio.h> #include<conio.h> int sum(int x); void main() { int n; clrscr(); printf("Enter the limit:"); scanf("%d", &n); printf("Sum of first %d natural numbers is %d", n, sum(n)); getch(); } int sum(int x) { int i, result=0; for(i=1; i<=x;i++) result +=i; return(result); } RECURSION: In c it is possible to call a function. Recursion is a process by which a function calls itself repeatedly until some specified
  • 50. condition has been satisfied. A function is called recursive if a statement within the body of a function calls the same function. Recursion is a process of defining something in terms of itself. Ex: #include<stdio.h> Long fact (long); void main() { long num, fac; printf(“Enter a number:”); scanf(“%ld”, &num); fac=fact(num); printf(“The factorial of %ld is %ld”, num, fac); } long fact (long x) { if(x<=1) return (1); else return(x * fact(x-1)); }
  • 51. NESTED OF FUNCTION: We have seen programs using functions called only from the main() function. But there are situations, where functions other than main() can call any other function(s) used in the program. This process is referred as nested of functions. Ex: #include<stdio.h> void func_1 (); void func_2 (); void main () { printf(“n inside main function”); func_1 (); printf(“n again inside main function”); } void func_1 () { printf(“n inside function 1”); func_2 (); printf(“n again inside function 1”); } void func_2 () {
  • 52. printf(“n inside function 2”); } STORAGE CLASSES: The variables are associated with certain properties such as scope and lifetime in a program. By scope of a variable means that the portions of the program in which it can be used. The lifetime of a variable is the period of time during which the value is available in memory. The four different storage class 1. automatic storage class 2. external storage class 3. static storage class 4. register storage class AUTOMATIC STORAGE CLASS Variables defined inside a block and are local to the block in which they are declared, are refered as automatic variables as local variables. Automatic variables can only be accessed by the block in which they are declared. Any another block cannot access its value. Ex: #include<stdio.h> #include<conio.h>
  • 53. /*void main() { auto int x=5; { auto int x=4; { auto int x=3; clrscr(); printf("%d t",x); } printf("%d t",x); } printf("%d t",x); getch(); } EXTERNAL STORAGE CLASS: Variables that are both alive and active throughout the entire program are called as external variables also refered as global variables. Global variables can be accessed by any function in the program. Global variables are also stored in the memory. When an external variable is not initialized it takes a value of zero. Ex:
  • 54. int value; void main() { value = 100; clrscr(); test1(); test2(); test3(); printf("%dn", value); getch(); } test1() { value += 100; printf("%dn", value); } test2() { value = 1000; printf("%dn", value); } test3() {
  • 55. value += 100; printf("%dn", value); } STATIC STORAGE CLASS: The world static in general refers to anything that is insert to change. In a program if static variables are declared within individual blocks they are local to the block in which they are declared. The static variables retain their values throughout the life of the program. Ex: void main() { clrscr(); sum(); sum(); sum(); sum(); getch(); } sum() { static int x=1;
  • 56. printf("%d", x); x=x+1; }*/ REGISTER STORAGE CLASS: The register storage class is similar to the auto storage class since the variables defined inside a block are local to the block in which it is specified. Register variable can only be accessed by the block in which it is declared. Its value cannot be accessed by any other function Ex: void main() { register int x; clrscr(); for (x=1; x<=10; x++) printf("%d",x); getch(); } STRUCTURES: A structure is a collection of one or more variables grouped under a single name for easy manipulation. The variables in a
  • 57. structure, unlike those in an array, can be of different variable types. A structure can contain any of C’s data types, including arrays and other structures. Each variable within a structure is called a member of the structure. Defining a structure: A structure definition contains keyword struct and a user defined structure-name followed by the members of the structure with in braces. The general form is: Struct structure-name { data-type member-1; data-type member-2; …………….. ……………. data-type member-n; }; Ex: Struct student {
  • 58. int no; int age; char sex; }; Structure declaration: Structure declaration means defining variables to the already defined structure. We can define variables in two ways. 1. variable definition along with the structure definition 2. variable definition using structure-name any where in the program The first general form is: Struct structure-name { data-type member-1; data-type member-2; …………….. ……………. data-type member-n; } variable-1, variable-2,…….variable-n; Ex: Struct student {
  • 59. int no; int age; char sex; }s1,s2,s3; The second general form is: Struct structure-name { data-type member-1; data-type member-2; …………….. ……………. data-type member-n; }; structure-name variable-1, variable-2,…….variable-n; Ex: Struct student { int no; int age; char sex; };
  • 60. student s1, s2, s3; Giving values to structure members: Dot operator or member operator ‘.’ Is used to give data to the structure variables individual members. The general form is; Structure variable . member-name The variable name with a period and the member name is used like any ordinary variable Ex: Struct student { int no; int age; char sex; }s1; the above declaration has a variable s1 having three members. The values or data to the members of the variable can be given by any one of the following method. (i) using keyword;
  • 61. scanf(“%d”, &s1.no); scnaf(“%d”, &s1.age); scanf(“%c”,&s1.sex); (ii) using assignment statement: s1.no = 100; s1.age = 18; s1.sex = ‘m’; Example: #include<stdio.h> #include<conio.h> void main() { struct emp { char sex; int no; float salary; }d1; clrscr(); printf("Give the values to the membersn"); printf("Give the sex......."); scanf("%c", &d1.sex);
  • 62. printf("Give the number...."); scanf("%d", &d1.no); printf("Give the salary...."); scanf("%f", &d1.salary); printf("n"); printf("Employee - details n"); printf("Sex: %cn", d1.sex); printf("Number: %dn", d1.no); printf("Salary: %fn", d1.salary); getch(); } Array of Structures: Array of structures are defined as a group of data of different data types stored in a consecutive memory location with a common variable name called an array of structures. Ex: #include<stdio.h> #include<conio.h> void main() { struct student
  • 63. { int no; int age; char sex; }; struct student s1[2]; int i; clrscr(); for(i=0;i<2;i++) { printf("Enter number,age,sexn"); scanf("%d %d %c", &s1[i].no, &s1[i].age, &s1[i].sex); } for(i=0;i<2;i++) printf("%d %d %cn", s1[i].no, s1[i].age, s1[i].sex); getch(); } Structures with structures [Nested Structure]: When a structure is declared as a member of another structure then it is called structure within structure or nested structure.
  • 64. Ex: #include<stdio.h> #include<conio.h> void main() { struct hostel_detail { int hostel_room_no; char food; int deposit_amount; }; struct student { char name[10]; int no; char branch[5]; struct hostel_detail h1; }; static struct student s1={"Raja", 100, "Ct", 10, 'v', 2000}; clrscr(); printf("%s %d %s %d %c %d", s1.name, s1.no, s1.branch, s1.h1.hostel_room_no, s1.h1.food, s1.h1.deposit_amount);
  • 65. getch(); } Passing Entire Structure To Function: In this method, the entire structure is passed as an argument to the function. Note that when using a structure as a parameter, remember that the type of the argument in the function call statement must match the type of a parameter (list if any), in the function prototype. Since the function is working on a copy of the structure, any changes made to the structure members within the function are not reflected in the orginal structure. Ex: #include<stdio.h> #include<conio.h> void employ(struct employee emp); struct employee { int empno; char empname[10]; }emp1; void main() {
  • 66. printf("Enter employee no and name:"); scanf("%d %s", &emp1.empno, emp1.empname); employ(emp1); } void employ(struct employee emp) { printf("n the employee no is :%d", emp.empno); printf("n the employee name is:%s", emp.empname); } FILES Files are used for permanent storage of large amount of data. A file can be used to write and/or read data from a disk. File handling in C is very simple, since it essentially treats a file as just a stream of characters and allows input and output in a file. So far we used scanf and printf function to read and write data to and from the computers through the console. If computers deal with large amount of data as input and output (read, write) then both methods are not efficient. The best way is to use files to give data to the computers and get data from the computers. Defining a File:
  • 67. A file is defined as FILE in the header file stdio.h therefore all files should be declared as type FILE before they are used. The general form is: FILE *pointer variable; Opening a File: Before we read from a file or write to a file, we must open the file. Opening establishes a link between the program and the operating system. The general form is: FILE *pointer variable; Pointer variable = fopen (“file name”, “mode”); Ex: FILE *a; a = fopen (“exam.txt”, “r”); Closing the file: An opened file must be closed after all operations on it have been completed.
  • 68. The general form is: fclose (pointer variable); Ex: ………………. ………………. FILE *a, *b; a= fopen(“exam.txt”, “r”); b= fopen(“exam.txt”,”w”); ………………….. …………………. fclose(a); fclose(b); Reading a file: fscanf function is used to read data from a file. The general form is: fscanf(pointer variable, “control string”,list); Ex: fscanf(a, “%d%d”, &x,&y);
  • 69. Writing to a file: fprintf function is used to write data into a file The general form is: fprintf (pointer variable, “control string”,list); Ex: fprintf(a,”%d%d”, x,y); Example: #include<stdio.h> #include<conio.h> void main() { int empno; char empname[20],deptname[20]; FILE *ptr; clrscr(); ptr=fopen("exam.dat","w"); printf("Enter ename, eno and edept:"); scanf("%s %d %s", &empname, &empno, &deptname); fprintf(ptr, "%s %d %s",empname, empno, deptname); fclose(ptr);
  • 70. ptr=fopen("exam.dat","r"); fscanf(ptr, "%s %d %s", &empname, &empno, &deptname); printf("n Employee Name:%s", empname); printf("n Employee Number:%d", empno); printf("n Department Name:%s", deptname); fclose(ptr); getch(); } Example: #include<stdio.h> #include<conio.h> void main() { int c; FILE *fptr; clrscr(); printf("Enter the text to store in the filen"); fptr=fopen("example.txt","w"); while((c=getc(stdin))!=EOF) fputc(c,fptr); fclose(fptr); printf("n the contents of the file is n");
  • 71. fptr=fopen("example.txt","r"); do { c=fgetc(fptr); putchar(c); } while (c!= EOF); fclose(fptr); getch(); } Random Access Function: Reading and writing operations on any file are normally sequential. This is achieved by a system-controlled pointer, which points the position immediately, after the last character is read or written. Which points the position immediately, after the last character is read or written. However, with the help of random access functions a C programmer can move the file pointer to any desired position in the file One advantage of a random access file over other files is that, a character can be written or read from the file by specifying the exact location where the operation is to take place.
  • 72. The random access functions used in a file are 1. the fseek() function 2. the ftell() function 3. the rewind() function The fseek() Function: The fseek() function is used to move the file pointer to any desired location within a file. It can be used to increment or decrement the file pointer by any number of positions in the file. The general form is: fseek (fptr, long int offset, int position); Ex: fseek (fptr, 5L, 0); The Position: Value Meaning 0 Beginning of the file 1 Current position of the file 2 End of the file
  • 73. The ftell() Function: The ftell() function returns the current position of the file pointer in the file. The general form is: ftell(fptr); The rewind () function: The rewind () function resets the file pointer to the beginning of the file. The general form is: rewind (fptr); Merging Two Files: Ex: #include<stdio.h> #include<conio.h> void main() { char *a; FILE *f1, *f2, *f3; clrscr();
  • 74. f1=fopen("student.txt","w"); printf("Enter the content of file1n"); gets(a); fputs(a,f1); fclose(f1); f2=fopen("student1.txt","w"); printf("Enter the content of file2n"); gets(a); fputs(a,f2); fclose(f2); f1=fopen("student.txt","r"); f3=fopen("student2.txt","w"); printf("n the content of file1 is n"); while (fgets(a, strlen(a)+1,f1)!=NULL) { fputs(a,f3); printf("%s",a); } fclose(f1); fclose(f3); f2=fopen("student1.txt","r"); f3=fopen("student2.txt","a"); printf("n The content of file2 is n");
  • 75. while(fgets(a,strlen(a)+1,f2)!=NULL) { fputs(a,f3); printf("%s",a); } fclose(f2); fclose(f3); f3=fopen("student2.txt","r"); printf("n the content of file3 is n"); while (fgets (a, strlen(a) + 1,f3)!=NULL) printf("%s",a); getch(); } POINTERS: A pointer is a variable, which represents the location (not the value) of a data item, such as a variable or an array element. Advantages: 1. pointers increase the execution speed of the program. 2. pointers reduce the length and complexity of a program. 3. pointers enable us to access a variable that is defined outside the pointers are used to pass information back and forth between a function and its reference point.
  • 76. Pointer declaration: All pointer variables must be declared before it is used in the program like other variable. The general form is: Data-type * variable; Assigning the address of the variable to pointer variable: The address of the variables can be got with the help of the address operator &. The operator & immediately preceding a variable returns the address of the variable associated with it. Ex: int *a; int x; a = &x; Example: #include<stdio.h> #include<conio.h> void main() {
  • 77. int a=5,b=10, *ptr; clrscr(); ptr=&a; printf("n initial values a=%d &b=%d",a,b); b=*ptr; printf("n changed values a=%d &b=%d",a,b); printf("n value of ptr is %d", ptr); getch(); } Pointers and Array: An array is actually a pointer to its 0th element. Dereferencing the array name will give the value stored in the 0th element of the array. Ex: #include<stdio.h> #include<conio.h> void main() { int i,j,n,a[25],*ptr; clrscr(); printf("Enter the number of elements:");
  • 78. scanf("%d", &n); printf("Enter the array elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); *ptr=a[0]; for(i=0;i<n;i++) if(a[i]>*ptr) *ptr=a[i]; printf("The biggest element in the array is %d",*ptr); getch(); } Pointer to Function: A pointer to a function contains the address of the funcntion in memory. A function, like a variable has an address location in the memory, therefore it is possible to declare a pointer to a function, Ex: #include<stdio.h> #include<conio.h> int sum(int (*) (int),int); int square(int);
  • 79. void main() { int num; clrscr(); printf("Enter any integer:"); scanf("%d", &num); printf("The sum of squares of first %d numbers is %d", num, sum(square, num)); } int sum(int (*fptr)(), int n) { int add, i; for(i=1;i<=n;i++) add += (*fptr) (i); return 0; } int square (int i) { getch(); return(i*i); }