C-Programming

Fundamental of C programming

Header file:

Sentence that begins with a hash sign (#) are directives for the preprocessors. These directives are called header file. They are not executable part of the program but they should be included while writing any program because they contain the definition or meaning of the library functions, key words, and pre-defined constants. The header file can be included by following syntax:

#include<header file name>                   OR

#include”header file name”

e.g.   #include<stdio.h>

          #include”string.h”

 The other header files which we will require for this level are listed below:

  • h
  • h
  • h
  • h
  • h
  • h
  • h
  • h etc.

Statements:

               The sentence which is written in the program to do one work separately is called statement. All the statements in C should be terminated by semicolon (;) which is called terminator. For example: a = b + c; is a statement.

Braces {  }:

               The opening and closing braces are used in the beginning and end of the compound statement respectively. Every functions or the compound statement should contain this braces with appropriate form.

Compound statements:

               The statements written inside the braces which act as a single statement are called compound statement. Generally it consists of more than two statements. For example:

               {

               a= b+c;

               d= a+b;

               } this over all statement which is enclosed by braces is compound statement.

Input/out put functions:

               Those functions which are used to send the data from the user or from the file are called input functions and the functions used to display the result or output are called out put functions. Most common output function is printf ( ) function which is used to display the text in standard output device i.e. monitor. Similarly the most common input function is scanf ( ) function which is used to read the data from the standard input device i.e. keyboard.

Library functions:

               Those functions whose definitions or job are pre-written in the library of the C program are called library functions. printf ( ), scanf ( ), clrscr ( ),getch( ) etc. all are example of the library functions.

Comments:

               The lines written within a program to make the program user friendly are called comments. Comments are non-executable lines in the program. It helps to understand the logic of the program to solve the problem. We can add the comment in the program in two ways:

  1. Single line comment:

If we want to add only one line/single line comment in the program then we can use double division sign for commenting. For example:

// I am going to learn C programming.

  1. Multiple-line comment:

If we want to add the comment more than more than one line then use of single line comment is not efficient. In this case we can use this:

/* …………………comments………………………..*/

Variable:

                   It is the name given to the memory location to hold some value. It is an entity. During the execution of the program value of the variable may changes. For example:

int total;

char name; etc. here total and name are two variables.  

Constants:

                   A value that doesn’t change during the execution of the program is called constant. Constant is sometimes referred to as literal. Whatever the content is there in the variable which is fixed is called constant. It cannot be changed during the execution of the program. Types of the constant can be understood by the following chart:

An integer constant like 1234 is an int. A long constant is written with a terminal l (ell) or L, as in 123456789L; an integer constant too big to fit into an int will also be taken as a long. Unsigned constants are written with a terminal u or U, and the suffix ul or UL indicates unsigned long.

Floating-point constants contain a decimal point (123.4) or an exponent (1e-2) or both; their type is double, unless suffixed. The suffixes f or F indicates a float constant; l or L indicates a long double.

A character constant is an integer, written as one character within single quotes, such as 'x'. The value of a character constant is the numeric value of the character in the machine's character set. For example, in the ASCII character set the character constant '0' has the value 48, which is unrelated to the numeric value 0. If we write '0' instead of a numeric value like 48 that depends on the character set, the program is independent of the particular value and easier to read. Character constants participate in numeric operations just as any other integers, although they are most often used in comparisons with other characters.

The complete set of escape sequences is

 \a   alert (bell) character   \\   Backslash
 \b   Backspace  \?  question mark
 \f   form feed   \'  single quote
 \n   new line  \"   Double quote
 \r   carriage return  \ooo   Octal number
 \t   horizontal tab  \xhh   hexadecimal number 
 \v   vertical tab    

The character constant '\0' represents the character with value zero, the null character. '\0' is often written instead of 0 to emphasize the character nature of some expression, but the numeric value is just 0.

A constant expression is an expression that involves only constants. Such expressions may be evaluated at during compilation rather than run-time, and accordingly may be used in any place that a constant can occur, as in

   #define MAXLINE 1000

   char line[MAXLINE+1];

or

   #define LEAP 1 /* in leap years */

   int days[31+28+LEAP+31+30+31+30+31+31+30+31+30+31];

A string constant, or string literal, is a sequence of zero or more characters surrounded by double quotes, as in

   "it is a string"

or

   ""      /* the empty string */

The quotes are not part of the string, but serve only to delimit it. The same escape sequences used in character constants apply in strings; \" represents the double-quote character. String constants can be concatenated at compile time:

   "hello, " "world"

is equivalent to

   "hello, world"

This is useful for splitting up long strings across several source lines.

Technically, a string constant is an array of characters. The internal representation of a string has a null character '\0' at the end, so the physical storage required is one more than the number of characters written between the quotes. This representation means that there is no limit to how long a string can be, but programs must scan a string completely to determine its length. The standard library function strlen(s) where s is the string and this library function is included into the header file string.h returns the length of its character string argument s which is an integer, excluding the terminal '\0'. For example: Length=strlen(s);

Be careful to distinguish between a character constant and a string that contains a single character: 'x' is not the same as "x". The former is an integer, used to produce the numeric value of the letter x in the machine's character set. The latter is an array of characters that contains one character (the letter x) and a '\0'.

Identifiers:

Identifiers can be defined as the name of the variable, functions, arrays, structures etc created by the programmer. They are the fundamental requirement of any programming language. It consists of letters (a-z, A-Z) and digit (0-9) in any order but the first character must be a alphabet or underscore (_) and should contain at least one letter. Both the lower case and upper case letters are permitted. The following are the valid identifiers:

 A, abc, ab12, _name, roll_no, SCHOOL, etc.

The following names are not valid identifiers for the reason stated:

1st               the first character must be letter.

“name”       illegal character ( “ )

roll-no         illegal character  (- )

roll no         illegal character  (blank space)

Keywords:

              Keywords are the reversed identifiers and they can not used as name for the program variable or other user defined program element. The meanings of the key words have already been given to the compiler. The key words are also called reserved words. There are 32 key words available in C which is listed below:

auto const double float Int short struct unsigned
break continue else for Long signed switch void
case default enum goto Register sizeof typedef while
char do extern if Return static union far

Note that keywords all are should in lower case. Since upper case is not equivalent to lower case therefore upper case keywords can be used as other identifiers. Some compiler contains more than 32 keywords also.

Data types:

              A data type is defined as the set of possible values that a variable can hold on it. This means data type identifies the type of the data i.e. whether the variable is character type or integer type or whether it contains decimal values or not etc. There are mainly three data types which are:

  1. a) Built in data type
  2. b) User defined data type
  3. c) derived data type

We study the user defined data type and derived data type later in the chapters’ structures and arrays respectively. In this part we will study only built in data type.

              It is also called basic or standard or fundamental data type. There are mainly five built-in data types.

  • Integer (int) data type:

              This type of data can store only whole numbers. The key word int is used for integer data type. The valid integers are 446, 421, -123, 2, 3333 etc. The size of integer type data is 2 byte i.e. 16 bits.

  • Character (char) data type:

     The data types which are used to store data of character are called character data type. The key word char is used to represent the character data type. The size of character data type is 1 byte i.e. 8 bits.

  • Floating point (float) data type:

              If a number contains the fractional part then it is called floating point number. This type of data is usually stored on float where float is the key word for the floating point number. Size of this type of data is 4 bytes. For example 12.344 are floating point number. This type data can store the six digits after decimal.

  • Double (double) data type:

              Double data type is used to represent double precision floating point number. It is called double data type because it occupies twice the memory than that of the floating point i.e. 8 bytes and it can stores 12 digits after decimal.

  • empty (void) data type:

                   The void data type specifies as empty set of values. It is used as the return type for function that does not return any value. Generally we don’t declare the variable of type void. We study in more detail about this in FUNCTIONS.

Rules for declaring the variables:

  1. First character of the variable should be letter or underscore. Other extra character is not allowed at the beginning. Then other type of character can be included.

For example:

              int  roll;                      this is valid.

              float  _hello;                       this is valid.

     char 12name; this is not valid because beginning character must be letter.

  1. The name of the variable should not match with the name of the functions or the key words. For example main, int, char, static etc. are invalid variable names because they are key words.
  2. While writing the name of the variable name both upper case and lower case are permitted.
  3. Upper case and lower case are not interchangeable.
  4. Space is not allowed in between the name of the variable.

The printf( ) function:

              This is one of the most common output functions used in C programming. Its main usage is to display the text, or value or both on the standard output device i.e. on the monitor.

Depending upon what is to be displayed, the general syntax of the printf ( ) are as follows:

  1. for displaying text only:

         printf(“your text”);

  1. for displaying value only:

         printf(“formal string/ type specifier”,variablename);

  1. for displaying both text and value:

         printf(“text type specifier ”,variablename);

Examples of each type of syntax are given below:

MY FIRST PROGRAM IN C:

  1. Program for first type syntax:

/*write a program to display the text “This is my first program in C.” */

Linker section

 

Main function

 

#include<stdio.h>

main()

Executable statement

 

 

{

printf(“This is my first program in C.”);

}

Out put of the program:

 

          This is my first program in C.

To run the program please press Ctrl+F9 and after this to see the output of the program press Alt+F5. Before run the program check the compile the program whether the program contains error or not by pressing Alt+F9.

To compile the program

To run the program

  1. Program for second type of syntax:

Before writing the program for this syntax, again look at the syntax once again. There is the term type specifier / formal string. What this means? Let’s know this term. The symbol which specifies the type of the data is called type specifier and this is also called as the formal string. Various type specifier for different data types are shown in the table:

Data type Formal string          
Integer %d
Floating point %f
Character %c
Double %lf

                           

/*write a program to assign a value on A and print the value of A*/

             #include<stdio.h>

             void main()

             {

             int A;

             A=10;         //assigning the value 10 for A

             printf(“%d”,A);

             }

                     The output of the above program is just only 10. This syntax is not user friendly, it means only seeing the out put of the program 10 we can not say what 10 is. Therefore for the more user-friendly the third syntax is used.

  1. Example of the third type of the syntax:

 

                     #include<stdio.h>

          void main()

          {

          int a,b,c;

          a=5;

          b=10;

          c=12;

          printf(“the value of the a is %d”, a);

          printf(“the value of b is %d”, b);

          printf(“the value of c is %d”,c);

          }

         Sample output:

the value of the a is 5the value of b is 10the value of c is 12

We can write the above program as follows:

#inlcude<stdio.h>

void main()

{

int a=5,b=10,c=12;

printf(“the value of a is %dthe value of b is %dthe value of c is %d”,a,b,c);

}

                        Output of this program is same as the above. In these two programs all output will be displayed as the line. If we want to escape the line then the printf( ); statement can be written as:

printf(“the value of a is %d\nthe value of b is %d\n the value of c is %d”,a,b,c);

The output of the program is:

the value of a is 5

the value of b is 10

the value of c is 12

Qualifier:

                   Those words which are used to increase the quality of the data is called qualifier. These words are preserved words i.e. they are key words. They are the words preceding the data type. Syntax:

     qualifier data_type variable;

Example:

 long int sum;

The function scanf ( ):

                        This is the most common data input function used in C. If we want to send the data to the computer then we use this function. It reads the data from the standard input device i.e. keyboard. General syntax of this function is:

                        scanf(“type specifier”,& variable_name);

                        Here the symbol & is called address operator. The function of this symbol can be understood by this example. If you have a bag having many pockets and you have to put a book in the book then where you would put this book? Naturally where the enough space is is in the bag for the book, there you will be put this book. For this you have to search for the space. In the same way to hold a value on the variable, the symbol ‘&’ searches the space /memory location in the computer memory. For simplicity we can say that ‘&’ represents the memory location of the variable and therefore called as address operator.

Scanf (  )/printf( ) format codes:

Code          use for

%d             for integer number

%c              for single character

%f              for floating point number

%h             for short integer

%s              for string

%l               for long

%ld             for long integer

 

Write a program which takes a numeric data from user and displays the data on the monitor.

#include<stdio.h>

void main( )

{

int a;

pritnf(“enter the value of a:   “);

scanf(“%d”,&a);       //reading the data from the keyboard.

printf(“\n\nValue of a is %d.”,a);

}

 

Sample out put of the program:

enter the value of a:    12

Value of a is 12._

Other useful library functions:

Library function                             purpose

  1. clrscr( ); to clear the screen
  2. getch( ); to hold the output of the program of the program unless one key is pressed.
  3. getche( ); to read a character from the standard input device
  4. strcpy( ); to copy the string and assign
  5. sqrt ( ); to find out the square root
  6. abs( ); to find the absolute value
  7. strlen ( ); to find out the no. of characters in the string
  8. strcmp( ); to compare two strings
  9. toupper( ); to change a character in upper case
  10. tolower( ); to change the character into lower case

Programming tools (Prev Lesson)
(Next Lesson) Operators and types
Back to C-Programming

No Comments

Post a Reply

Teacher
Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!