Dec 3, 2019

1 C Programming Basics



Introduction

C is not a very high level language, though it is used in very popularly by programmers due to it's simplicity.  It has been closely associated with the UNIX system, since it was developed on that system.  Dannies M.Ritchie develops C Program in Bell Laboratories.

Features:

Program written in c are portable across various platforms.
C is a structured language which supports modular approach
C offers compartmentalize code and date.
C does not have in-built input/output facilities.  Input and out are achieved by calling a set of functions.

Application Areas:
C is considered to be a general purpose language it is used for writing operating systems, compilers, interpreters, assemblers, editors, communication software, DBMS, spread sheets and word processors, and also for business systems, Animations software, engineering and process control systems.

Structure of C program:
Functions are basic building blocks of c programs.  Every program must have one function with the name main( ).  This function is the entry point of the program.  The main( ) function invokes other functions to perform its job.  Communication between functions takes place through arguments.

Sample C program
#include<stdio.h>
int main( )
{
printf(“\n Hallo, world”);
return 0;
}

General format of a c program:
preprocessor directives 
function prototypes
global variables
void main( )
{
local variables declaration;
program statements;
}

Elements of C program are:


Comments: 
Comments are non executable statements used to convey objective of the program.  All comments are enclosed between /*   */markers  e.g / * my name */ is a comment.

Preprocessor directives: 
A preprocessor directives begins with a # sign is direction to the preprocessor.  It prepares the program file which is to be handed over to compiler for compilation.  It performs jobs of file inclusion, macro substitution and conditional compilation.  The directive # include is a file inclusion directive it includes header file stdio.h into program file before the file is passed to the compiler.  Header files contains function prototype declarations of functions in standard library.  Preprocessor directive help in realizing multiple file program approach thereby keeping main program file neat and hence easier to understand.

Function prototypes: 
C requires declaring beforehand function prototypes of all functions to be used in a program.  Which are declared in various header files.  Hence including header files take care of library function prototype declaration.  Return_type function name(……..); where return type is the type of data the function returns.  Which don’t returns a value are declared as void functions (in such cases return statement is omitted).  The function name is the name by which the function is invoked by other functions. E.g. void display(void); int getchar(void); etc.  where first example gives declaration of display( ) function, it does not take any arguments and don’t returns any value while second example gives declaration of getchar( ) function it does not require any argument but returns an integer.

Global variables: 
All those variables declared at the beginning of the program are global variable and can be accessed by all functions of the program and are terminated with the program termination.

Functions : 
Functions are self-contained program segment to carry out specific, well defined task.  If a program is big and complex, it can be decomposed into smaller manageable parts using functions.  Due to functions writing and debugging a program becomes easier as each functions can be written and tested separately before being integrated in the program.  Modifications are also made easier, because they can be confined to certain functions in the program, leaving the rest of the program intact. Communication between function is performed by passing variables as arguments.  

A function is invoked by making a function call and the arguments are enclosed in the parenthesis, separated by commas.  E.g. printf(“\n two numbers are %d%d”,x,y);.  Functions can also return a value, which may be stored in a variable, if required.  The type of value returned by a function determines the type of the function.  Eg. Ch=getchar( );  in above example getchar( ) functon doesn’t require any argument, but returns a value which is stored in variable ch.

Function Definition: 
All user defined functions should have a function definition which comprises three parts
  • A function header
  • Body of the function


Function header consists of function’s data type, function name and list of arguments and their types separated by commas, enclosed in parenthesis.  Variables declared in the function header are called formal variables.  They receive their initial values from calling function and so changes to these formal variables are not reflected back in the calling function.

If function does not receive any arguments, then pair of empty parenthesis are given.  This followed by the body of the function enclosed in a pair of braces.  The function body may contain executable statements and its own set of variable declarations.  These variables are local variables.  The scope of local variables is the function in which they are declared, they don’t exist outside a given function.

C does not allow functions to be declared inside another function.  All statements and declarations have to be terminated by a semi colon (;).

The return statement is used to return a value back to the calling function. If a function is of type void, control can be transferred back with an empty return. 
E g. Return (value);
Return;

Statements and blocks
Function body can include both simple and compound    statements.  All simple statements are terminated by a semi-colon.

A compound statement or block is syntactically equivalent to a single statement.  Variable declared inside the block are local to the block.  A block does not need a semi colon as terminator.  The right brace acts as terminator for the block.

Variable naming rules
Variables can be formed of upper and lower case alphabetic characters, digits and underscore character (_).  The first character of variable name cannot be a digit.  

There is no limit to the length of a name, but number of significant characters vary from compiler to compiler.

C is a case sensitive language.  Although names can be in any case, all variables and function names are conventionally given in lower case.

Keywords
Keywords are the words that are part of c language and should be used in as defined by c language such names cannot be used as user-defined names.  There are 32 keywords in C they are as follows:

Auto           extern short
char case for
Static  default  continue
if                 switch          long
Union do               while
const unsigned  else
Return       float            volatile
void break goto
Int             enum struct
register double        sizeof
Typedef    signed

Data types
There are two categories of data types i.e. basic and derived data types.  There are four basic data types Char, Integer, Float, and Double.  And in derived data types there are arrays, structures, unions etc.

Character(char): is allocated one byte of storage on 16 bit machine, it is capable of holding one character from local character set..  character variables are declared with the keyword char, more than one variable can be declared with one char  separating them by commas.  They can also be initialized within the same statement.
e.g. char flag;
char ch,yes_no_flag;
char star=’*’,switch_char=’-‘;

Character constants 
Is a single character written quotes e.g. const char ch= ‘t’; the value of a character in machines character set which changes from machine to machine certain non-graphic characters can be presented by escape sequences which are of special combination of characters in quotes.  They are
\n newline        
\a bell         
\t tab
\\ back slash
\v vertical tab
\’  single quote
\b backslash
\” double quote
\r  carriage return
\ooo octal number given by ooo
\f form feed
\xhh hexa number given by hh.

Integers 
Are numbers without fractional parts they are allocated two bytes of storage.  Integer variables are declared with the keyword int.  more than one variable can be declared with one int separating by commas or they can also be initialized with in the same statement.
e.g. int value;
       int x,fig,num;
      int count=100,val=50;
Integer Constants
Consists of digits preceded by an optional minus sign.  If it starts with a zero, it is an octal integer constant otherwise it is a decimal integer.  Constants starting with 0x(or0X) are hexadecimal integer constants.  Which will also include characters ‘a’ to ‘f’ (‘A’ to ‘F’) for values from 10 to 15.  declaration of integer constants is preceded by keyword const.
Const int months=12;

Valid inter Constants.
100 Decimal
051 octal
1234 decimal
0x10 hexadecimal
1 decimal
0x1A2 hexadecimal

Float: 
Float is a single precision floating point number having precision of only 6 digits.

Double : 
Is a double precision number.  These numbers have a precision of 16 to 18 digits.

Floating point variables :
Are declared with the keyword float and are allocated two words of memory.  Double precision numbers are declared with the keyword double and are allocated four words of memory.

The Size of operator( ): 
This operator returns the number of bytes taken up by the variable or data type.  Value returned by this operator can be used to determine the size of a variable. For example
size(int);
sizeof(float);
char(star);
int char_size;
 char_size=sizeof(star);

Qualifiers: 
All variables by default are signed variables .  if variable’s value is not signed then keyword unsigned can precede a variable.  So declaring an unsigned variable is known as a qualifier.
e.g. unsigned int num=341;

Note: while using a qualifier data type can be omitted, which case it defaults to being an integer.

Sometimes it may be possible that when the values to be stored in variables exceed the storage space allocated to them.  If variable is unsigned and a bigger number is to be stored in a variable then the long qualifier can be used.  For example 

long int bignum=123456789;
unsigned long unum;

Two qualifiers with or without variable declaration can also be given.

Basic Input/Output in C

All I/O operations in c are performed by calling functions from the library.

Getchar( ): reads one character from keyboard.  Returns ASCII code of character typed in, which has to assigned to a character variable.

putchar( ): prints one character on the screen.  Takes character to be printed as an argument.
e.g. char = ch;
ch =getchar( );
putchar=(ch);
printf( ): is an output function.
scanf( ): is an input function.

These functions offers facility for formatted Input/Output.
e.g. printf(“Format String”, arguments);

The format string contains the format specifiers, which controls formatBack of the variables to be printed.  Each format specifier has to be preceded with a % symbol.  Following are the format specifiers:
%d signed decimal integer.
%u   unsigned decimal integer.
%c single character.
%s multiple characters.
%f floating point (decimal notation).
%e floating point (exponential notation).
%g floating point (exponential or decimal which ever is shorter).
%x unsigned hexadecimal integer.
%o unsigned octal integer.
%% prints a % symbol.

Format String:  
Can be also contain any text, any number of format specifiers can be given, with equal no of variables.

e.g. printf(“%d”,num);
printf(“total of=%d \n”,total);

scanf( ): 
Allows formatted input.  This function specifies the addresses in the memory, where the arguments have been allocated memory.  So that scanf( ) can directly store input over there using an address operator(&).
e.g. scanf(“%d”, &num);
scanf( ) is purely an input function it does not return any output.

Modifiers for printf( ) and scanf( )
- the value printed will be left justified
m where m is a number, specifies the minimum field width.  If the value is smaller than the specified width, spaces are padded on to fill the extra position
the padding of extra spaces in the above case, is done with zeros
l is used to print long integers or double precesion numbers.
.n where n is a number, specifies the maximum numbers of digits to be printed after decimal point, in case of a real numbers.
, is used when the width is to be taken from a variable at a runtime, in which case this variable is given in the argument list before the actual 
variable to be printed.

e.g. printf(“[%f]\n”,555.55);
printf(“[%e]\n”,555.55);
printf(“[%-f]\n”,555.55);
printf(“[%10.3f]\n”, 555.55);
printf(“[%010.3f]\n”,555.55);
printf(“[%4d]\n”,  55);
printf(“[%*d]\n”,6,55);
printf(“[%0*d]\n”,6,55);

recursive function:  
Recursion is the process by which a function invokes itself.  Such functions are recursive functions.  This function should specify an exit condition otherwise it will go indefinitely.  Recursion is suitable for recursive problem.

e.g. /* facorial non recursive version*/
# include<stdio.h>
void main( )
{
long factorial(int num);
int num;
printf(\n enter number:”);
scanf(“%d”,&num):
printf(“Factorial of %d,%d is”, num,factorial(num));
}
long factorial(int n)
{
long f=1;
while (n)
f*=n--;
return(f);
}

/*Factorial Recursive version*/
#include<stdio.h>
void main( )
{
long factorial(int num);
int num;
printf(“\n enter number”);
scanf(“%d”,&num):
printf(“Factorial of %d,%d is”, num,factorial(num));
}
long factorial(int n)
{
if(n==1)
return(1)
return(n* factorial (n-1));
}

Scope Rules and storage Classes

Storage classes determines the life of a variable in terms of its declaration or its scope.  There are four storage classes in C.  They  are:

1.. Automatic Variable:
Are defined within a function.  Automatic variables looses their value when function terminates.  It can be accessed only in that function.  A variable is declared as an automatic variable with the keyword auto.  Since these variable do not exist after the function, in which they are declared, is over, they can not retain their values over a number of function calls to that function.

e.g. #include<stdio.h>
void print auto(void)
{
auto int I=0;
printf(“before incrementing=%d\n”);
I+=10;
Printf(“After incrementing =%d\n”);
}
void main( )
{
print_auto( );
print_auto( );
print_auto( );
}

2.. Static Variables: 
Are same as auto variables they can be accessed only within the function where they are declared but static variables retain their values over a number of function calls.  The life of a static variable starts with the first time execution of its function and it remains in existence, till the program terminates.  Static variables declared with the keyword static.

e.g. #include<stdio.h>
void print_auto(void)
{
static int I=0;
printf( I before incrementing %d\n”);
I+=10;
printf(“ I after incrementing %d \n”);
}
void main( )
{
print_auto( );
print_auto( );
print_auto( );
}

3.. External variables:  
Different functions of same program can be written in different source files and can be compiled together.  If a global variable declared in a source file is required in a function defined in another source file then external variables are to be used.  External variables are declared with extern keyword.  Any change to the extern variables done by functions of a file are reflected in functions of other files.

4.. Register variables 
Computer have inter registers, used to store data temporarily before any operation can be performed on it.  Intermediate results of calculations are also stored in registers.  Operations can be performed on data stored in registers more quickly than the data stored in memory.  If a particular variable is used often it can be assigned a register, rather than an allocation in the memory.  This done with the keyword register.  Register is assigned by the compiler only if it is free else it is taken as an automatic variable.  Register variables cannot be global variables.

e.g. void loopf( )
{
register int I;
for (I=0; I<<100;++I)
printf(“%d\n”,I);
}




Programs for Chapter 1

1..Simple Hello World Program
 #include<stdio.h> // preprocessor directories
#include<conio.h>
int main()
{
clrscr();
printf("\n Hello World  : ");
return 0;
getch();
}

2..Program to print sum of two numbers

 #include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,c; //Variable declaration

printf("\n Enter first Number  : ");

scanf("%d",&a);
printf("\n Enter Second Number  : ");
scanf("%d",&b);
c=a+b;

printf("\n Additon is %d ",c  : ");
return 0;
getch();
}


3..Program to print ASCII code of keyboard characters
#include<conio.h>
#include<stdio.h>
int main( )
{
clrscr( );
int code;
char symbol;
printf(“\n Enter ASCII code (0 to 127) :- ");
scanf(“%d”,&code);
symbol=code;
printf("\n Symbol corressponding to code is %c :- ",symbol);
return 0;
getch( );
}




4...Program to Print Area Of A Circle
#include<stdio.h>
#include<conio.h>
void main(){
float pi=3.14;
float radius,area;
clrscr();
printf("\n Enter Radius of a Cirlce :");
scanf("%f",&radius);
area=2*pi*radius;
printf("\nRadius of a circle is %f ",radius);
printf("\nArea of a circle is %f",area);
return 0;
getch();
}

5..Program to print avg and result of a student
  #include<stdio.h> #include<conio.h> void main() { char name[10]; int mark1,mark2,mark3; int total,avg; //Variable declaration clrscr(); printf("\n Enter Your name : "); scanf("%s",&name); printf("\n Enter Subject 1 Marks : "); scanf("%d",&mark1); printf("\n Enter Subject 2 Marks : "); scanf("%d",&mark2); printf("\n Enter Subject 3 Marks : "); scanf("%d",&mark3); total=mark1+mark2+mark3; printf("\n The Total Marks acquired is : %d ",total); avg=total/3; printf("\n %s Your Total Marks is %d and Average is %d " ,name,total,avg ); return 0; getch(); }


6..Program to print Salary of an Employee
 #include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char name[10];
float basic,ta,da,hra,netsal;;

printf("\n Enter Your name : ");
scanf("%s",&name);

printf("\n Enter Subject 1 basic  : ");
scanf("%f",&basic);
ta=basic*0.3;
da=basic*0.5;
hra=basic*0.15;
netsal=basic+ta+da+hra;

printf("\n %s Your Basic is %f and Net salary is %f ",name,netsal  : ");
return 0;
getch();

}




Back


No comments:

Post a Comment