Professional Documents
Culture Documents
UNIT I INTRODUCTION
Structure of C program – Basics: Data Types – Constants –Variables - Keywords –
Operators: Precedence and Associativity - Expressions - Input/Output statements,
Assignment statements – Decision-making statements - Switch statement - Looping
statements – Pre-processor directives - Compilation process – Exercise Programs:
Check whether the required amount can be withdrawn based on the available
amount – Menu-driven program to find the area of different shapes – Find the sum of
even numbers.
Programming paradigms
Programming languages can be categorized into programming paradigms
Programming paradigms are the result of people‟s ideas about how computer
programs should be constructed.
Once you have understood the general concepts of programming paradigms, it
becomes easier to learn new programming languages.
Imperative
Procedural
Functional
Object-Oriented
Concurrent Logic
Scripting
C is a high level programming language, General Purpose and Structured
programming.
C is developed by Dennis Ritchie at AT & T Bell Laboratories in 1972 in USA.
C is also called as procedure Oriented Programming Language and
“Compiled language”.
Unix was the first OS written in C
Later Microsoft Windows, Mac OS X, and GNU/Linux were all written in C.
Perl, PHP, Python and Ruby are all written in C.
Most of the operating systems are written in C and C++ language. These include
Windows 95, 98, 2000, XP, Vista, Windows 7, Windows 8, Apple Mac OS X, Symbian
OS and Be-OS, Google Chrome OS, RIM BlackBerry OS 4.x, Apple iPhone iPod Touch
and iPad OS etc.
C is often chosen over interpreted languages because of its speed, stability, and near-
universal availability.
FEATURE OF C LANGUAGE
Different data types also have different ranges upto which they can store numbers.
These ranges may vary from compiler to compiler. Below is list of ranges along with
the memory requirement and format specifiers on 32 bit gcc compiler.
We can use the sizeof() operator to check the size of a variable. See the following C
program for the usage of the various data types:
#include <stdio.h>
int main()
{
int a = 1;
1.5 Constants
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well. Constants are treated just like regular variables except that their values cannot
be modified after their definition.
a) Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned
and long, respectively. The suffix can be uppercase or lowercase and can be in any
order.
Here are some examples of integer literals −
212 /* Legal */
215u/* Legal */
0xFeeL /* Legal */
78 /* Illegal: 8 is not an octal digit */
032UU/* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213/* octal */
0x4b/* hexadecimal */
30 /* int */
30u/* unsigned int */
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is
allocated to day, which is 2. So as a result, 2 is printed. Another example of
enumeration is:
// Another example program to demonstrate working of enum in C
#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
01234567891011
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is
Jan which is 0 and the value of Dec is 11.
Double
1.8 Operator
An operator is a symbol that tells the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following
types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We
a will look into the way each operator works.
a)Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable Bholds 20 then − Show Examples
Operator Description Example
+ Adds two operands. A+B= 30
− Subtracts second operand from the first. A−B=- 10
* Multiplies both operands. A*B= 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an B%A=0
integer division.
b)Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20.
Operator Description Example
== Checks if the values of two operands are (A == B)
equal or not. If yes, then the condition is Not
becomes true. true.
!= Checks if the values of two operands are (A != B)
equal or not. If the values are not equal, then is true.
the condition becomes true.
> Checks if the value of left operand is greater (A > B)
than the value of right operand. If yes, then is not
the condition becomes true. true.
< Checks if the value of left operand is less (A < B)
than the value of right operand. If yes, then is true.
the condition becomes true.
>= Checks if the value of left operand is greater (A >= B)
than or equal to the value of right operand. If is not
yes, then the condition becomes true. true.
<= Checks if the value of left operand is less (A <= B)
than or equal to the value of right operand. If is true.
yes, then the condition becomes true.
b) Logical Operators
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0.
Operator Description Example
&& Called Logical AND operator. If both the (A &&
operands are non-zero, then the condition B) is
becomes true. false.
|| Called Logical OR Operator. If any of the two (A || B)
operands is non-zero, then the condition is true.
becomes true.
! Called Logical NOT Operator. It is used to !(A &&
reverse the logical state of its operand. If a B) is
condition is true, then Logical NOT operator true.
will make it false.
*= Assign product
/= Assign quotient
%= Assign remainder
-= Assign sum
&= Assign difference
^= Assign bitwise AND
|= Assign bitwise XOR
<<= Assign bitwise OR
>>= Assign left Shift
Assign right shift
, Separator of expressions Left to right
1.9 Expression
1. In programming, an expression is any legal combination of
symbols that represents a value.
2. C Programming provides its own rules of Expression,
whether it is legal expression or illegal expression. For
example, in the C language x+5 is a legal expression.
3. Every expression consists of at least one operand and can
have one or more operators.
4. Operands are values and Operators are symbols that
represent particular actions. Valid C Programming Expression :
C Programming code gets compiled firstly before execution. In the different
phases of compiler, c programming expression is checked for its validity.
Expressions
Validity
The file pointers are the means to access the file for reading and writing
purpose. This section explains how to read values from the screen and how
to print the result on the screen.
int c;
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads only a
single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to
by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline
to stdout.
#include <stdio.h>
int main( ) {
char str[100];
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard
input stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard
output stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, and character or float respectively.
There are many other formatting options available which can be used based on
requirements. Let us proceed with a example to understand the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s%d", str, &i);
printf( "\nYou entered: %s, %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then program proceeds and reads the input
and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven, 7
Here, it should be noted that scanf() expects input in the same format as you
provided %s and %d, which means you have to provide valid inputs like "string
integer". If you provide "string string" or "integer integer", then it will be assumed as
wrong input. Secondly, while reading a string, scanf() stops reading as soon as it
encounters a space, so "this is test" are three strings for scanf().
variable = expression;
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:
y is greater than x
void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
Points to Remember
1. In if statement, a single statement can be included without enclosing it into curly
braces { ... }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but if we have more than one
statement inside if condition, then we must enclose them inside curly braces.
2. == must be used for comparison in the expression of if condition, if you use = the
expression will always return true, because it performs assignment not
comparison.
3. Other than 0(zero), all other values are considered as true.
if(27)
printf("hello");
In above example, hello will be printed.
Example:
// Following is a simple program to demonstrate
// syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
Output:
Choice is 2
1.14 Looping statements
Looping statements are the statements execute one or more statement repeatedly
several number of times. In C programming language there are three types of loops;
while, for and do-while.
Types of Loops.
There are three type of Loops available in 'C' programming language.
while loop
for loop
do..while
Difference between conditional and looping statement:
Conditional statement executes only once in the program where as looping
statements executes repeatedly several number of time.
a)While loop
In while loop First check the condition if condition is true then control goes inside
the loop body otherwise goes outside the body. while loop will be repeats in clock
wise direction.
b) For loop
for loop is a statement which allows code to be repeatedly executed. For loop
contains 3 parts Initialization, Condition and Increment or Decrements.
Output
1
2
3
4
c)do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute at
least one time. A do while loop is a control flow statement that executes a block of
code at least once, and then repeatedly executes the block, or not, depending on a
given condition at the end of the block (in while).
Syntax
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
When use do..while Loop
When we need to repeat the statement block at least 1 time then we use do-while
loop.
void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}
Output
1
2
3
4
Nested loop
In Nested loop one loop is place within another loop body. When we need to
repeated loop body itself n number of times use nested loops.
Nested loops can be designed up to 255 blocks.
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20.
Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to
the current source file. The next line tells CPP to get myheader.h from the local
directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful
if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This
will define DEBUG, so you can turn debugging on and off on the fly during
compilation.
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in
programming, the predefined macros should not be directly modified.
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
After compilation executable is generated and we run the generated executable using
below command.
$ ./filename
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly level instructions. Let‟s see through this file
using $vi filename.s.
Linking
This is the final phase in which all the linking of function calls with their definitions
are done. Linker knows where all these functions are implemented. Linker does some
extra work also, it adds some extra code to our program which is required when the
program starts and ends. For example, there is a code which is required for setting up
the environment like passing command line arguments. This task can be easily
verified by using $size filename.o and $size filename. Through these commands, we
know that how output file increases from an object file to an executable file. This is
because of the extra code that linker adds with our program.
Note that GCC by default does dynamic linking, so printf() is dynamically linked in
above program. Refer this, this and this for more details on static and dynamic
linkings.
C PROGRAMS
int main( )
{
int ch ;
do
{
printf(" \n**************************** ") ;
printf(" \nBANKING ") ;
printf(" \n**************************** ") ;
printf(" \n1. Create New Account ") ;
printf(" \n2. Cash Deposit ") ;
printf(" \n3. Cash Withdraw ") ;
printf(" \n4. Low Balance Enquiry ") ;
printf(" \n5. Exit ") ;
printf(" \nEnter your choice : ") ;
scanf("%d ",& ch) ;
switch ( ch)
{
case 1 : creation( ) ;
break ;
case 2 : deposit( ) ;
break ;
case 3 : withdraw( ) ;
break ;
case 4 : lowbal( ) ;
break ;
case 5 : ;
break ;
default : printf(" Choice a Valid option !! ") ;
break ;
getch( ) ;
}
} while( ch != 5 ) ;
}
void deposit( )
{
int no, b = 0, m = 0 ;
int aa ;
printf(" \n**************************** ") ;
printf(" \nCASH DEPOSIT ") ;
printf(" \n**************************** ") ;
printf(" \nEnter your Account Number : ") ;
scanf("%d ",& no) ;
for ( b = 0 ; b < i ; b++)
{
if ( s[b].no == no)
m=b;
}
if ( s[m].no == no)
{
printf("\n Account Number : %d ",s[m].no) ;
printf("\n Name : %s ",s[m].name) ;
printf("\n Deposit : %f ",s[m].dep) ;
printf(" \nDeposited Amount : ") ;
scanf("%f ",& &aa) ;
s[m].dep+=aa ;
printf("\nThe Balance in Account is : %f ",s[m].dep) ;
getch( ) ;
}
else
{
printf("\nACCOUNT NUMBER IS INVALID ") ;
getch( ) ;
}
}
void lowbal( )
{
int no, b = 0, m = 0 ;
int aa ;
printf(" \n**************************** ") ;
printf(" \nFOLLOWING ACCOUNT HOLDER'S BALANCE IS LESS THAN 1000 ") ;
printf(" \n**************************** ") ;
Output of Program:
OUTPUT:
Enter the Number : 10
Sum of all Even Integers is 30