Wednesday, 24 December 2014

Data types and I/O functions in C

Data types in 'C'  

There are 4 basic data types in 'C'.
char - for character type of data, this can hold a single character. It takes 1 byte in the memory. Declaration is
char ch;
 int - for storing decimal integer numbers. It takes 2 bytes in the memory. declaration is
int mnum;
float - for storing numbers with floating point. this can give 6 digits of precision. It takes 4 bytes in the memory. Declaration is
float mum;
double - for storing numbers with floating point. this can give 10 digits of precision. It takes 8 bytes in the memory. Declaration is
double mnum;
void - it is type less and generally used with user defined functions returning no value.  

Modifiers with basic data types:-
 A modifier is used to alter the meaning of base data type to fit various situations. Accept for void the basic data types can have various modifiers preceding them. These are signed, unsigned, long and short. All of these can be applied to char and int base types. long can also be applied to double.
Declarations are as follows:
long int mnum; or long mnum;
- used when a length of more than the normal integer length is required.
short int mnum; or short mnum;
 - used when a length of less than the normal integer length is required.
unsigned int mnum;
signed int mnum;
Identifier names: - The names of variables, functions, labels and various other user defined objects are called identifier names. These names can be of one or more characters. The first character should be an alphabet or an underscore (_). The subsequent characters must be alphabets, numbers or underscores. An identifier name can't be the same as 'C' keyword, a function written by a programmer or in built in the library.


Data Type      size in bits           range

char                                 8                           - 128 to 127(in ASCII)
unsigned char                 8                             0 to 255(in ASCII)
signed char                     8                           - 128 to 127(in ASCII)
int                                   16                           -32,768 to 32,767
unsigned int                    16                            0 to 65,535
signed int                        16                           -32,768 to 32,767
short int                           16                          -32,768 to 32,767
unsigned short int            8                              0 to 65,535
signed short int                8                           -32,768 to 32,767
long int                            32                          -2147483648 to 2147483647
signed long int                 32                          --"--
unsigned long int             32                          0 to 4294967295
float                                  32                          6 digits of precision
double                               64                         10 digits of precision
long double                       128                       10 digits of precision

Input and output functions:-

i) printf() - It prints the comment and/or output in the specified format on the screen.
ii) scanf() - It accepts input from the user in the specified format.
iii) getchar() - It reads a character from the keyboard and waits for carriage return.
iv) getche() - It reads a character from the keyboard with echo and does not wait for carriage return.
v) getch() - Reads a character without echo and does not wait for carriage return.
vi) gets() - Reads a string from the keyboard.
vii) putchar() - It writes a character to the screen.
 viii) puts() - It writes a string to the screen.
examples :-
              1)  char chi ;
                ch = getchar() ;
                putchar(ch) ;

            2)  char str[80] ;
                gets(str) ;
                puts(str) ;
            3) puts("Hi ! How are you ?") ;
            4) printf("this is %c and %s", 'C', "Softech") ; 

Format specifiers used with printf() :-

Code         Format

%c         character
%d         signed decimal integers
%i         signed decimal integers
%e         scientific notation (lowercase e)
%E         scientific notation (uppercase E)
%f         decimal floating point
%g         uses %f or %e whichever is shorter
%G         uses %f or %E whichever is shorter
%o         unsigned octal
%s         string of characters
%u         unsigned decimal integers
%x         unsigned hexadecimal (lowercase characters)
%X         unsigned hexadecimal (uppercase characters)
%p         displays a pointer
%%         prints a % sign

Format specifiers used with scanf() :-

Code         Format
%c         reads a character
%d         reads a signed decimal integer
%i         read signed decimal integers
%e         reads a floating point number
%f         reads a floating point number
%g         reads a floating point number
%o         reads an octal number
%s         reads a string of characters
%u         reads an unsigned decimal integer
%x         reads a hexadecimal
%p         reads a pointer
%[]        scan for a set of characters
examples :- 1) char ch = 'a' ;
               printf("%d", ch) ;
output is 97 (Ascii value for 'a')
            2) #include <stdio.h>
               main()
               {
               char abc[50] = "Hi ! How are you ?" ;
               float num = 708.89 ;
               int full = 801 ;
               printf("%s friend ", abc) ;
               printf("no. in signed integer :%d", full) ;
               printf("no. in floating :%f", num) ;
               printf("no. in unsigned integer :%u", full) ;
               printf("no. in scientific notation :%e", num);
               printf("no. in unsigned octal :%o", full);
               printf("no. in unsigned hex :%x", full);
               }

Escape sequence characters :-  Used with printf() only.

Code            Meaning

\b              Backspace
\f              Form feed
\n              New line
\r              Carriage return
\t              Horizontal tab
\"              To print double quote
\'              To print single quote
\0              Null
\\              To print backslash
\v              Vertical tab
\a              Alert (beep sound)
\N              To print octal constant (where N is any octal
                constant)
\xN             To print hexadecimal constant (where N is any
                hex. no.)

examples :- ) printf("Life is \t very short \n & \n there's
              \t no time.");
output is - Life is       very short
            &
            there's       no time.

Format modifiers :-

Many format specifiers works with modifiers that alter their meaning slightly. Modifiers are placed between the percent sign and the format specifier. minimum and  maximum field width, the no. of decimal places, left justification and many other kind of formatting can be specified using modifiers.
Modifier for minimum field width –
e.g.
#include <stdio.h>
main()
{
float num;
num = 13.4485;
printf("No. is : %f", num);
printf("No. padded with 10 spaces is :%10f", num);
printf("No. padded with 0's is :%010f", num);
  }

The program will give following output :
No. is :13.4485
No. padded with 10 spaces is : 13.448500
No. padded with 0's is :013.448500

The precision specifier
e.g. 1)  %12.5f - used with float
type of data, outputs the no. with minimum 12 digits and 5
decimal places.
2) %8.12s - used with char. type, outputs the
string with minimum 8 chars. and not exceeding 12 chars.
3) %.2f - Displays the output in floating point number with only 2 decimal places.
Modifier to justify output - By default numeric output is right justified. To make it left justified do the following :
e.g.       float num ;
           num = 12.456;
           printf("The no. is :%5.2f", num);
The output is : The no. is : 12.45
after using modifier to left justify output :
           float num ;
           num = 12.456;
           printf("The no. is :%-5.2f", num);
The output is : The no. is :12.45

Modifier for maximum field width - example as follows :
char str[80] ;
printf("\nenter a string:") ;
scanf("%10s", &str);
The above segment accepts only the string which is maximum of 10 characters.
Scanset ([ ]) specifier - e.g.
1) char str[10] ; scanf("%[abcd]", &str) ;  - Here if you input "alpha", then it will accept only "aa" because it prohibits to accept the char. other than a,b,c or d.
2) char str[10] ; scanf("%[^abcd]", &str) ;  - Here if you input "alpha", then it will accept only "lph" because it prohibits to accept the char. a,b,c or d.
3) char str[10] ; scanf("%[a-z]", &str) ;  - Here if you input "alpha", then it will accept the whole string "alpha" because it is meant for accepting all the characters in the range  'a' to 'z'. But it does not accept "ALPHA".
Some additional modifiers
 1) %ld - for long integer. It applies to specifiers d, u, x
2) %hd - for short integer. It applies to specifiers d, u, x
3) * modifier - e.g. printf("The no.is :%*.*f", 8, 2,130.45);
output is - The no.is:  130.45
- here first * is replaced with 8, second * is replaced with 2  and no. 130.45 is displayed using these modifiers.
* modifier can also be used for suppressing input. e.g.
scanf("%d %*c %d", &a, &b) ;
In the above segment, first number will be accepted in variable 'a', then a char. is accepted and discarded and second number will be accepted in 'b'. i.e. if you give 1-10
1 gets stored into a and 10 gets stored into b, - is accepted and discarded.






Tuesday, 23 December 2014

Introduction to programming

Date : 24/12/2014

Hi friends,

As you all know, Programming is a technical art. To be an efficient developer, you need to write efficient programs. Efficient in the sense of logic, memory and processing. Programming is not related with any language or so. But, still its good to start with C. So lets start with basics of C language.

Chapter 1
Fundamentals of computers and Introduction to C

Data :- Data are facts & figures about an entity.
Entity :- Any existing thing in the world.
      The aim of computer is to accept data, process it and generate information. Just like a manufacturing concern, which  processes raw materials in order to create finished product. For the data processing different software is available. Programming Language is such a software, which is useful for data processing.  C is one of the programming languages.
      By using a Programming language user can specify the procedure for input, process and output in the required format. This specified procedure is called as a program.

                          Introduction to C

'C' was written by Dennis Ritchie at the Bell Laboratories of AT & T Co. in U.S.A. in 1972. 'C' was the result of a development process which started with an older language BCPL, developed by Martin Richards. BCPL influenced a language 'B' written by Ken Thompson, which was the predecessor of 'C'. It provides a variety of data types. 'C' is not tied to any one operating system or machine. It can be used in any area of application e.g. Engineering, Science, Education, Business etc.
Features: - 1) 'C' is a middle level language. It can be used for writing application programs as well as it can provide the functionalism of low level language
E.g. it allows direct manipulation of bits, bytes, words, pointers. Thus it combines the elements of low level and high level languages.
2) 'C' is a structural language - It sections off the program using braces. It provides modular approach using user defined functions, labels etc.
3) 'C' is used for designing Operating System, OS Support Utilities, Compilers, Editors, Word Processors etc. DOS, UNIX are designed in 'C'.
4) 'C' supports several loop constructs like FOR, WHILE, DO-WHILE and conditional statements like IF and SWITCH.

The 'C' program structure:-

Rules –
1)      All keywords should be in lower case.
2)      'C' is case sensitive i.e. ALPHA is different from alpha.
3)       Keywords can not be used for any other purpose like for variable names, function names, label names etc.
4)      main() is always the first function called when any 'C' program execution begins.
5)      Each function or code of block is separated by delimiters or braces ({,}).
6)      Each statement should be terminated with a semicolon (;). There may be more than one statement on the same line but each one of them should be terminated by semicolon.
7)      Comment line should start with /* and should end with */. If the user forgets to end the comment the whole program will be treated as a comment.
The 'C' library: - All 'C' compilers come with a standard 'C' library of functions that perform most commonly needed tasks. In some implementations the library exists in one large file while in others it contains in many small files.
If you want to use a particular function you have to include the library file which provides that function. A function written by a programmer which is used by many programs can also be placed in the library file and can be used as and when required.

Steps in compiling and running a program:-
1)      Editor or word processor - for writing the source code (program).
2)      The source code is passed through the 'C' pre processor. The pre processor acts on some special statements called directives which start with a # sign. The pre processor expands the shorthand of the directives and produces a code; this is called expanded 'C' source code. It passes to 'C' compiler.
3)      Compiler converts the expanded source code into object code (.OBJ file) and provides input to the linker.
5)      Object code along with support routines is linked together by the linker to an executable code (.EXE file).
6)      The executable code runs using the system's loader.

Sample C Program :- 

#include <stdio.h>
void main()
{
printf("\nHello friends!!!Welcome to C Programming");
}