C Programming Language - Always Beginners (BooksRack - Net)
C Programming Language - Always Beginners (BooksRack - Net)
➢ C is highly portable. This means that C program written for one computer
can be run on another computer without any modification or little
modification.
High-Level Language
➢ In high level language programming to refer the memory addresses we use
variable and pointers and there is strict syntax which is to be followed.
➢ Source code firstly compiled and converts into machine code. These
machine codes convert into the code which is understandable by CPU. ➢
High level languages are C, C++, Java etc…
• C PROGRAM STRUCTURE
C language program is consists of following sections.
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( ) Function Section {
}
Subprogram Section
Function 1 (User Define Functions) Function 2
1. Document Section
The documentation section consists of a set of comment lines giving program
information.
2. Link Section
The link section provides instruction to the compiler to link functions from
the system library.
3. Definition Section
The definition section defines all symbolic constants.
4. Global Declaration Section
There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration
section that is outside of all the functions.
• C CHARACTER SET
C language character set denotes any valid character in C programming
language. This character can be alphabet, digit, special symbols and white
spaces. Following table shows the valid alphabets, numbers, special symbols
and white spaces allowed in C language.
Alphabet Digits A, B, . . . . . ., Y, Z. a, b, . . . . . ., y, z. 0, 1, 2, 3, 4, 5, 6, 7, 8,
9
Special Symbols
, comma ; semi colon . period / slash ~ tilde
$ dollar sign
White spaces
Blank space Horizontal tab Carriage return New line
Form feed
• C CONSTANTS
Constants in C refer to fixed values that do not change during the execution
of a program. C language constants are also known as Literals. C supports
several types of constants as under.
Integer constants
Real constants
Real constants are numerical values with fractional part. Valid examples of
real constants are 215.50, .98, +58.90, -0.80
String Constants
• C LANGUAGE VARIABLES ( C
LANGUAGE IDENTIFIERS )
A variable is a data name that may be used to store a data value. Unlike
constants that remain unchanged during the execution of a program, a
variable may take different values at different times during execution. A
variable name can be chosen by the programmer in a meaningful way. A
variable name must follow following rules.
Some examples of valid variable names are John, Value, T_raise, Delhi, x1,
ph_value, mark, sum1, distance
Some examples of invalid variable names are 123, (area), x-y, %, 25th, do
• C LANGUAGE KEYWORDS
In C language, keywords are special words with fixed meaning. These
meanings cannot be changed.
int unsigned int char short int unsigned short int signed char long unsigned
long unsigned char
char 8 bits -128 to 127 signed char 8 bits -128 to 127 unsigned char 8 bits 0
to 255
int 16 bits -32768 to 32767 signed int 16 bits -32768 to 32767 unsigned int
16 bits 0 to 65535 signed short int 8 bits -128 to 127 unsigned short int 8 bits
0 to 255
long 32 bits -2147483648 to 2147483647 signed long 32 bits -2147483648 to
2147483647 unsigned long 32 bits 0 to 4294967295
float 32 bits 3.4 * 10–38 to 3.4 * 10+38 double 64 bits 1.7 * 10–308 to 1.7 * 10+308
long double 80 bits 3.4 * 10–4932 to 3.4 * 10+4932
int i,x;
float f;
double d; long l;
x = l / i + i * f d;
Type Casting
Example :
sum = sum + (float) 1 / i;
Here, value 1 is converted in to float before performing operation with
variable i.
• C LANGUAGE OPERATORS
Operator Description
( ) Function Call
[ ] Array element reference + Unary Plus
- Unary Minus
++ Increment
- Decrement
! Logical Negation
~ One’s Complement * Pointer reference & Address
sizeof Size of an object
(type) Type case (conversion) * Multiplication
/ Division
% Modulus
+ Addition
- Substraction
<< Left shift
>> Right shift
< Less than
<= Less than or equal to > Greater than
>= Greater than or equal to == Equality
!= Inequality
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Conditional expression = *=
/= %=
+= -= Assignment Operators&= ^=
|= <<=
>>=
, Comma operator
L To R 8 L To R 9 L To R 10 L To R 11 L To R 12 R To L 13
R To L 14
L To R 15
• ARITHMETIC OPERATORS IN C
There are five arithmetic operators available in C language.
* Multiplication n1 * n2 / Division n1 / n2 %
Operator Description Example
Modulus n1 % n2 + Addition n1 + n2
- Subtraction n1 – n2
Result
Multiplication of n1 and n2 Division of n1 and n2
Modulus of n1 and n2 Addition of n1 and n2
Subtraction of n1 and n2
#include < stdio.h > #include < conio.h > void main( )
{
int i=3,j=4,k=5;
int a,b,c;
clrscr( );
a= i * i;
printf( “ %d “,a ); // prints 9
b = 4 + 4 / 2 * 3;
printf( “\n%d”,b ); // prints 10 because division and multiplication first. c =
12 % 5;
printf( “\n%d”,c ); // prints 2
}
• RELATIONAL OPERATORS IN C
There are six relational operators available in C language.
Operator Description Example < Less than n1 < n2
void main( ) {
int a,b; clrscr( );
a=10; b=10;
if ( a==b )
printf(“ Both are equal “ );
if ( a!=b )
printf(“ Both are inequal “);
if ( a>=b )
printf(“ a is greater than and equal to b “ );
if ( a>b )
printf(“ a is greater than b “ );
if ( a<=b )
printf(“ a is less than and equal to b “ );
if ( a<b )
printf(“ a is less than b “ );
}
• LOGICAL OPERATORS IN C
There are three logical operators in C Language. Logical operators are use to
join multiple relation conditions.
void main( ) {
float per; clrscr( );
Syntax :
expression1 ? expression2 : expression3
expression1 expression2
void main( ) {
int a,b,c,d;
int i=2,j=2,k=2,m=2;
a=++i;
b=j++;
c= --k;
d= m--;
printf(“\n a=%d b=%d c=%d d=%d”,a,b,c,d ) ; // Returns a=3 b=2 c=1 d=2
printf(“\n i=%d j=%d k=%d m=%d”,i, j, k, m ) ; // Returns i=3 j=3 k=1 m=1
• C LANGUAGE TOKENS
The language elements are called tokens. Identifiers, operators, keywords,
Literals and special symbols are examples of tokens. Identifiers:
The names of variables, functions or arrays in a program are an identifier.
Keywords
The keywords are reserved identifiers used by C language. C language has
total 32 keywords in all. Some of them are do, while, for, break etc… Literals
( Constants )
A literal denotes constant value.
integer : 200 0 -7
real : 3.14 -3.14 3e+5
character : ‘a’ ‘A’ ‘ * ‘ ‘ $ ’
string : “abba” “3.14” “is”
Comments
The compiler ignores everything written in comments. The C language
supports two kinds of comments:
Arithmetic operators ( + , - , * , % , / )
Relational operators ( < , > , >= , <=, == , != )
Logical operators( ! , && , || )
Conditional operator ( ? : )
Special symbols
C language supports special symbols in the program. Some of them are as
under.
#include <stdio.h>
#define LENGTH 10 #define NEWLINE '\n'
void main() {
const int WIDTH=5; int area;
• DECISION STRUCTURES
1. if Statement
The if statement is a powerful decision making statement and is used to
control the flow of execution of statements.
Statements-block; …
}
Statement-x;
if ( i % 2 == 0 )
{
printf(“ Number is divisible by 2 “ );
}
2. if … else Statement
The if … else statement is an extension of the simple if statement.
if ( relational condition -1 ) {
if( relational condition -2 ) {
Statement-1; }
else
{
Statement-2; }
}
else
{
Statement-3;
}
else
discount=amt*0.10; }
else
{
discount=amt*0.05; }
}
4. if … else if Statement
Syntax :
if ( relational condition 1 ) statement – 1;
statement – x;
Example :
#include<stdio.h> void main( )
{
float per;
clrscr( );
printf(“Enter percentage : “); scanf(“%f”,&per);
if( per >= 70 )
int i=2;
clrscr( );
switch ( i ) {
case 1 :
printf( “I am in case 1 \n” ); break;
case 2 :
printf( “I am in case 2 \n” ); break;
case 3 :
printf( “I am in case 3 \n” ); break;
default :
printf( “I am in default \n” ); }
}
• LOOP STRUCTURES
During looping a set of statements are executed until some conditions for
termination of the loop is encountered. A program loop therefore consists of
two segments one known as body of the loop and other is the control
statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
In entry-control loop, the control conditions are tested before the start of
loop execution. If conditions are not satisfied then the body of the loop will
not be executed.
In exit-control loop , the control conditions are tested at the end of loop
body and therefore the body is executed unconditionally for the first time.
The test may be either to determine whether the loop has repeated the
specified number of times or to determine whether the particular condition
has been met.
The C language provides for three loop constructs for performing loop
operations. They are:
….
….
Statements;
….
….
expression that change conditional variable value;
Here the given test condition is evaluated and if the condition is true then the
body of the loop is executed. After the execution of the body, the test
condition is once again evaluated and if it is true, the body is executed once
again. This process of repeated execution of the body continues until the test
condition finally becomes false and the control is transferred out of the loop.
On exit, the program continues with the statements immediately after the
body of the loop. The body of the loop may have one or more statements. The
braces are needed only if the body contained two are more statements
Example :
int i;
clrscr( );
i=1;
while ( i <= 10 ) {
printf(“%d\n”,i); i=i + 1;
}
2. The Do while statement:
The do while loop is also a kind of loop, which is similar to the while loop in
contrast to while loop, the do while loop tests at the bottom of the loop after
executing the body of the loop. Since the body of the loop is executed first
and then the loop condition is checked we can be assured that the body of the
loop is executed at least once. It is exit control loop
Syntax : initialization; do
{
….
….
Statements;
….
….
expression that change conditional variable value
} while ( relational condition );
int i;
clrscr( ); i=1;
do
{
printf(“%d\n”,i); i=i + 1;
} while ( i <= 10 ); 3. The For loop statement:
The for loop provides a more concise loop control structure. It is entry
control loop. The general form of the for loop is:
Syntax :
for( initialize; condition ; expression ) {
….
statements; ….
When the control enters for loop the variables used in for loop is initialized
with the starting value such as I=1. The value which was initialized is then
checked with the given test condition. The test condition is a relational
expression, such as I <=10 that checks whether the given condition is
satisfied or not if the given condition is satisfied the control enters the body
of the loop or else it will exit the loop. The body of the loop is entered only if
the test condition is satisfied and after the completion of the execution of the
loop the control is transferred back to the expression part of the loop. The
conditional variable is incremented using an assignment statement such as
I++ and the new value of the control variable is again tested to check whether
it satisfies the loop condition. If the value of the control variable satisfies then
the body of the loop is again executed. The process goes on till the control
variable fails to satisfy the condition.
Example :
int i;
clrscr( );
for ( i=1;i<=10;i++) {
printf(“%d\n”,i); }
• BREAK, CONTINUE
STATEMENTS IN C
1. break Statement
Example:
void main( )
{
clrscr( );
for(i=1 ; i <= 100 ; i++) {
printf( “%d”,i );
if( i == 50 ) break; }
}
2. continue Statement
Example:
void main( )
{
clrscr( );
for(i=1 ; i <= 100 ; i++) {
if( i % 5 == 0 ) continue; printf( “%d”,i ); }
• ARRAY
Definition :
An array is a collection of elements having same name, same data type and
different index value.
Declaring Arrays
We can declare an array by specify its data type, name and the number of
elements the array holds between square brackets immediately following the
array name.
Here is the syntax:
data_type array_name[size];
For example, to declare an integer array which contains 100 elements we can
do as follows:
int a[100];
Initializing Arrays
To initialize an array, you provide initializing values which are enclosed
within curly braces in the declaration and placed following an equals sign
after the array name.
Here is an example of initializing an integer array.
{
printf(“Element a[%d] = %d “,i , a[i] );
}
}
Multidimensional Arrays:
An array with more than one index value is called a multidimensional array.
The entire array above is called single-dimensional array. To declare a
multidimensional array you can do follow syntax
data_type array_name[][][];
The number of square brackets specifies the dimension of the array. For
example to declare two dimensions integer array we can do as follows:
int matrix[3][3];
int matrix[3][3] = {
{11,12,13}, {21,22,23}, {32,31,33},
};
Program for Store and Print Two Dimension Array Elements:
#include<stdio.h>
void main( ) {
int a[3][3],i,j; clrscr( );
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf(“Enter element a[%d][%d] = “,i,j); scanf(“%d”,&a[i][j]);
}
}
// Print values in an array
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
printf(“%3d “,a[i][j] ); }
printf(“\n”);
}
}
CHARACTER ARRAY AND STRING IN C
15 columns.
char b[5][25] Declares an array of 125 character elements in 5 rows
and 25 columns.
char c[10][20] Declares an array of 200 character elements in 10 rows
and 20 columns.
char nm[50];
clrscr( );
printf(“Enter Your name “);
gets(nm); // stores character values in an array
nm
printf(“Your name is ”);
puts(nm); // display inputed values on the screen
}
Program for read and display string Multi Dimensional Array:
#include<stdio.h>
void main( ) {
char nm[5][25]; int i,j;
clrscr( );
puts(nm[i]); }
• LIBRARY FUNCTIONS OF
<STRING.H>
strlen( )
Description: counts no of characters present in the string excluding null
character.
Example :
#include<stdio.h>
#include<string.h>
void main( )
{
}
strcpy( )
Description: copy one string to another string.
Example :
#include<stdio.h>
#include<string.h>
void main( )
{
}
strcat( )
Description: Appends copy of one string to another string.
Syntax : strcat(string1,string2)
String2 is append to an end of String1.
Example :
#include<stdio.h>
#include<string.h>
void main( )
{
char s1[25]= “Turbo”;
char s2[10]=”C++”;
strcat(s1,s2);
printf(“\n String 1 = %s”,s1); // TurboC++ printf(“\n String 2 = %s”,s2); //
C++
strcmp( )
Description: The string comparison starts with first character in each
Value 0
>0
<0
Description
Both strings are equal.
First string is large than second string. First string is small than second string.
Example :
#include<string.h> void main( )
{
strlwr( )
Description : strlwr converts all uppercase ( A to Z ) in to lowercase ( a to z ).
All other characters remain unchanged.
Syntax : strlwr(string1)
String1 is converted to lowercase.
Example :
#include<stdio.h>
#include<string.h>
void main( )
{
strupr( )
Description : strupr converts all lowercase ( a to z ) in to uppercase ( A to Z ).
All other characters remain unchanged.
Syntax : strupr(string1)
String1 is converted to uppercase.
Example :
#include<stdio.h> #include<string.h>
void main( ) {
char s1[25]= “James Bond 007”;
}
strrev( )
Description : strrev changes all characters in a string to reverse order, except
the terminating null character.
Syntax : strrev(string1)
String1 is reversed.
Example :
#include<stdio.h>
#include<string.h>
void main( )
{
Example :
#include<ctype.h>
void main( )
{
char ch;
int result;
printf(“Enter Any character : “);
scanf(“%c”,&ch);
result=isalpha(ch);
if ( result != 0 )
isdigit( )
Description : This function checks whether the given character is
digit( 0 to 9). Function returns non zero value on success and zero on failure.
Syntax : isdigit(char c)
Example :
#include<ctype.h>
void main( )
{
char ch;
int result;
clrscr( );
printf(“Enter Any character : “); scanf(“%c”,&ch);
result=isdigit(ch);
if ( result != 0 )
printf(“Your character is a digit”);
else
printf(“Your character is not a digit”);
isalnum( )
Description : This function checks whether the given character is
Example :
#include<stdio.h>
#include<ctype.h>
void main( )
{
char ch;
int result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
result=isalnum(ch);
if ( result != 0 )
printf(“Your character is an alpha numeric”); else
printf(“Your character is not an alpha numeric ”); }
isspace( )
Description : This function checks whether the given character is
space , new line, carriage return or tab. Function returns non zero value on
success and zero on failure.
Syntax : isspace(char c)
Example :
#include<stdio.h>
#include<ctype.h>
void main( )
{
char ch;
int result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
result=isspace(ch);
if ( result != 0 )
isupper( )
Description : This function checks whether the given character is an
Example :
#include<stdio.h>
#include<ctype.h>
void main( )
{
char ch;
int result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
result=isupper(ch);
if ( result != 0 )
Example :
#include<stdio.h>
#include<ctype.h>
void main( )
{
char ch;
int result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
result=islower(ch);
if ( result != 0 )
toupper( )
Description : This function converts character to uppercase if it is in
Example :
#include<stdio.h>
#include<ctype.h>
void main( )
{
char ch;
char result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
printf(“Your character is : %c”,ch); result=toupper(ch);
printf(“After toupper function : %c”,result);
}
tolower( )
Description : This function converts character to lowercase if it is in
char ch;
char result;
clrscr( );
printf(“Enter Any character : “);
scanf(“%c”,&ch);
printf(“Your character is : %c”,ch); result=tolower(ch);
printf(“After tolower function : %c”,result);
printf ( )
Description : Sends formatted text output to standard output device( generally
monitor ).
Example :
#include<stdio.h>
void main( )
{
printf(“Hello World”);
}
scanf ( )
Description : Accepts formatted data from standard input device and stores it
in memory location.
Example :
#include<stdio.h>
void main( )
{
int no;
printf(“Enter any number : ”);
scanf(“%d”,&no);
}
gets( )
Description : Accepts string from standard input device and stores it in
memory locations.
Example :
#include<stdio.h>
void main( )
{
char nm[25];
printf(“\nEnter Your Name : ”);
gets(nm);
printf(“My name is : “);
puts(nm);
}
puts( )
Description : Prints string to standard output device ( Screen ). Example :
#include<stdio.h>
void main( )
{
char nm[25];
printf(“\nEnter Your Name : ”); gets(nm);
printf(“My name is : “);
puts(nm);
LIBRARY FUNCTIONS OF <CONIO.H>
getch( )
Description : getch reads a single character directly from the keyboard
without echoing to the screen.
Example :
#include<conio.h>
void main( )
{
char ch;
printf(“\nEnter Any Character : ”);
ch=getch();
printf(“\n Your character is %c “, ch);
}
getche( )
Description : getch reads a single character directly from the keyboard and
echoes it to the screen.
Example :
#include<stdio.h>
#include<conio.h>
void main( )
{
char ch;
printf(“\nEnter Any Character : ”);
ch=getche();
printf(“\n Your character is %c “, ch);
}
getchar( )
Description : getchar reads a single character from standard input. The
getchar is line buffered that means characters are available after enter key.
Example :
#include<stdio.h>
#include<conio.h>
void main( )
{
int ch;
printf(“\nEnter Any Character String : ”); while((ch=getchar( ))!=’\n’)
{
printf(“%c”,ch);
}
}
clrscr( )
Description : clrscr clears current text window and places the cursor in the
upper left corner.
• By using UDF, you can divide complex tasks into smaller manageable tasks
and test them independently before using them together.
Structure of UDF
return type <function name> (<parameter list>) {
Statements; }
• Function name; function name is a sequence of letters and digits, the first
of which is a letter, and where an underscore counts as a letter. The name of a
function should meaningful. for example result(),
Types of UDF:
Basically three types of UDF
1) No argument no return value 2) With argument no return value 3) With
argument with return value
For example:
#include<stdio.h> #include<conio.h>
void sum1( );
void sum2(int, int); int sum3(int, int); void main()
{
Function Declaration
Function Calling
}
int sum3(int, int)
{
return (x+y); }
OUTPUT:
No Arg. No Return Sum :=3 With Arg. No Return Sum :=40 With Arg. with
Return Sum :=300