C Programming

Contents
• What is C
• Getting Started with C
(The C Character Set
Constants, Variables and Keywords
Constants
Variables
C Keywords)
•  C Programs



What is c




C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie. In the late seventies C began to replace the more familiar languages of that time like PL/I, ALGOL, etc. No one pushed C. It wasn’t made the ‘official’ Bell Labs language. Thus, without any advertisement C’s reputation spread and its pool of users grew. Ritchie seems to have been rather surprised that so many programmers preferred C to older languages like FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that's what happened.
Possibly why C seems so popular is because it is reliable, simple and easy to use. Moreover, in an industry where newer languages, tools and technologies emerge and vanish day in and day out, a language that has survived for more than 3 decades has to be really good.



Getting Started with C






The C Character Set
A character denotes any alphabet, digit or special symbol used to represent information. Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C.

Constants, Variables and Keywords
A constant is an entity that doesn’t change whereas a variable is an entity that may change.
In any program we typically do lots of calculations. The results of these calculations are stored in computers memory. Like human memory the computer memory also consists of millions of cells. The calculated values are stored in these memory cells. To make the retrieval and usage of these values easy these memory cells (also called memory locations) are given names. Since the value stored in each location may change the names given to these locations are called variable names.
Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning a new value 5 to the same memory location x. This would overwrite the earlier value 3, since a memory location can hold only one value at a time. This is shown in Figure 1.3.






Since the location whose name is x can hold different values at different times x is known as a variable. As against this, 3 or 5 do not change, hence are known as constants.



C Keywords
Keywords are the words whose meaning has already been explained to the C compiler (or in a broad sense to the computer). The keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to the keyword, which is not allowed by the computer. Some C compilers allow you to construct variable names that exactly resemble the keywords. However, it would be safer not to mix up the variable names and the keywords. The keywords are also called ‘Reserved words’.
There are only 32 keywords available in C. Figure 1.5 gives a list of these keywords for your ready reference. A detailed discussion of each of these keywords would be taken up in later chapters wherever their use is relevant.


Datatypes in C


Integer types:(%d or %i)

Integers are whole numbers with a range of values, range of values are machine dependent. Generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32767 (that is, -215 to +215-1). A signed integer use one bit for storing sign and rest 15 bits for number.
To control the range of numbers and storage space, C has three classes of integer storage namely short int, int and long int. All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the bits for the magnitude of the number. Therefore the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies 4 bytes of storage space.


Syntax: int <variable name>; like
int num1;
short int num2;
long int num3;


Example: 5, 6, 100, 2500.

Integer Data Type Memory Allocation

Floating Point Types:(%f and %lf)

The float data type is used to store fractional numbers (real numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision and takes double space (8 bytes) than float. To extend the precision further we can use long double which occupies 10 bytes of memory space.


Syntax:          float <variable name>; like
float num1;
double num2;
long double num3;


Example:      9.125, 3.1254.

Floating Point Data Type Memory Allocation

Character Type:(%c)

Character type variable can hold a single character. As there are singed and unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.


Syntax: char <variable name>; like
char ch = ‘a’;


Example:      a, b, g, S, j.

Void Type:

The void type has no values therefore we cannot declare it as variable as we did in case of integer and float.


The void data type is usually used with function to specify its type. Like in our first C program we declared “main()” as void type because it does not return any value. The concept of returning values will be discussed in detail in the C function hub.





First C program

#include<stdio.h>
#include<conio.h>
void main(){
clrscr();
printf("Hello World!!");
getch();
}
# -known as pre-processor. Perform required operations before compilation.

include<...>- will add the header file with the program before compiling it.

stdio.h- Standard Input/Output. It contains
1.printf- To print message on screen.
2.scanf- To take input from keyboard.

conio.h- Console Input/Output. It contains
1.clrscr()- To clear the screen.
2.getch()- To get character from the screen and to hold the screen.

void - It is a datatype described above in datatypes which means no return value.

main()- It is a functions, execution of every c program. It is an entry for compiler.

{ }- It represents the scope of the function.


What is header files?
Header file contains different predefined functions, which are required to run the program. All header files should be included explicitly before main ( ) function.
It allows programmers to seperate functions of a program into reusable code or file. It contains declarations of variables, subroutines. If we want to declare identifiers in more than one source code file then we can declare such identifiers in header file. Header file has extension like '*.h'. The prototypes of library functions are gathered together into various categories and stored in header files.


Followings are the some commonly used header files which plays a vital role in C programming :

Assert.h

Ctype.h

Math.h

Process.h

Stdio.h

Stdlib.h

String.h

Time.h

Graphics.h





Type Casting
Manually converting one datatype into another

int /int =int

float/int=float

int/float=float

float/float=float

Consider a program :

int a=3;
int b=2;
int c=a/b;
float d=a/b;
float e=(float)a/b;                        // Type Casting
printf("c=%d d=%f e=%f",c,d,e);

Output:
c=1 d=1.000000 e=1.500000


Note: We can control decimal points in float
"%.2f" gives only 2 decimal points




Circular Property of Integer Datatype


 Range of Integer datatype is from -32768 to 32767.
If we add 1 to 32767 then compiler will not give any error instead give the result as:


Consider a program:


int a=32767;
a=a+1;
printf("a= %d",a);


Output:
a= -32768


Escape Sequences


Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.


\a Bell (alert)
\b Backspace
\f Formfeed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\ "Double quotation mark
\\ Backslash
\? Literal question mark

                     Control Structures in C

n1.Sequence is a series of statements that execute one after another
n2.Selection (branch) is used to execute different statements depending on certain conditions
n3.Repetition (looping) is used to repeat statements while certain conditions are met.

Sequence

n>Can contain any symbol except for the decision or loop symbol
n>Steps are executed in sequence with no instruction changing the order
n>Flow lines connect each instruction


Selection
if Selection Statement
if is the primary tool of selection structure. if is used when we want a single or a group of statements to be executed if the condition is true. If the condition is false, the statement is skipped and program continues by executing the first statement after the if selection structure. The flowchart illustrates the function of if selection.

Lets look at an example that implement if selection structure. The program asks the user to input a number between -10 and 10. Then it message if the number is a positive number.



Extending the if Statement
Lets revise the last session, if statement allows a statement to be executed if the condition is true. If it is false the statement will be skipped. What if we want the program to execute certain statement if the condition is false. Remember the previous program's if statement.


The message will be displayed only when the condition is true. Lets make a few modification to the if selection structure.
The full program and the sample output are given below. The sample output shows two different outputs for positive number and negative number.
switch Selection Statement
The switch statement allow us to select one from multiple options. It is especially useful when we want to write a code that makes a selection based on an expression or a variable. switch selection structure consists of a series of case label sand optional default case as shown below.



String Functions

'string.h' is a header file which includes the declarations, functions, constants of string handling utilities. These string functions are widely used today by many programmers to deal with string operations.
Some of the standard member functions of string.h header files are,

Function NameDescription
strlen -Returns the length of a string.
strlwr -Returns upper case letter to lower case.
strupr -Returns lower case letter to upper case.
strcat -Concatenates two string.
strcmp -Compares two strings.
strrev -Reverse the string.
strcpy -Copies a string from source to destination.



Program :



#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
 char str[50];
 clrscr();
 printf("\n\t Enter your name : ");
 gets(str);
 printf("\nLower case of string: %s",strlwr(str));
 printf("\nUpper case of string: %s",strupr(str));
 printf("\nReverse of string: %s",strrev(str));
 printf("\nLength of String: %d",strlen(str));
 getch();
}


Output :

Enter your name : Vinod
Lower case of string: vinod
Upper case of string: VINOD
Reverse of string: DONIV
Length of String: 5

What is the difference between gets() and scanf()?

char name1[20],name2[20];
printf("Enter name1 ");
scanf("%s",&name1);
printf("\nEnter name2 ");
gets(name2);
printf("name1=%s \n name2=%s",name1,name2);

Output:
Enter name1 Vinod Adwani
Enter name2 Vinod Adwani
name1=Vinod
name2=Vinod Adwani

Hence gets function is used in case of strings while scanf is used in case of inputing Characters.


Program to Check whether the  String is Palindrome or not.



#include<stdio.h>
#include<string.h>
#define size 26

void main()
{
char strsrc[size];
char strtmp[size];
clrscr();
printf("\n Enter String:= ");
gets(strsrc);
strcpy(strtmp,strsrc);     //Copies string strsrc in strtmp
strrev(strtmp);
if(strcmp(strsrc,strtmp)==0)
printf("\n Entered string "%s" is palindrome",strsrc);
else
printf("\n Entered string "%s" is not palindrome",strsrc);
getch();
}

Output:
Enter String:=Nitin                                                         Enter String:=Vinod
Entered string Nitin is Palindrome                                   Entered string Vinod is not Palindrome