Read more
UNIT 4
Programming Language
THE HISTORY OF C
The C language was developed at Bell Laboratories (now
AT& T’: American Telegraph & Telephone) in the early 1970’s by a system
programmer named Dennis Ritchie. It was written originally for programming
under an operating system called UNIX, which itself was later rewritten almost
entirely in C.
Its name encrypted as C, derives from the fact that it is
based on an earlier version written by Ken Thompson, another Bell Laboratories
systems engineer. He adapted it from a language that was known by the initials
BCPL (Basic Combined Programming Language). Thompson derived his programming
language name as B, the first of the initials BCPL.
When the language was modified and improved to its
present state, the second letter of BCPL, C was given to it. The C language is
often described as a middle-level language. It permits programs to be written
in much the same style as that of most of the high-level programming languages.
It also interacts with the inner workings of the computer.
The American National Standards Institute has established certain standards for
C, which are known as ANSI C in addition to the original version of C developed
by Dennis Ritchie. Another popular version of C is Turbo C.
Merits of C Programming Language
In computer programming, different high-level programming
languages are used. There are some programming languages specially designed to
write programs for special kind of solutions such as simulations, games, space
research, etc. Here are some merits of using C programming language.
1. C is general purpose programming language. You can
generate different kind of software such as billing system, games, utilities,
word processor, etc.
2. C is the structured programming language. It uses
structured statements such as while, for, etc.
3. C is a standardized programming language. For example
ANSI (American National Standards Institute) C is a standard programming
language.
4. The C language can run in any computer system. It is
system independent.
5. It has the small range of data types of detailed data
manipulation statements with power data definition methods.
6. It is a language of few words such that the programmer
can remember them easily.
7. It is a highly efficient programming language since C
compilers are generally able to translate source code into efficient machine
instructions.
Structured programming
In 1965, a Dutch Professor E. W Dijkstra suggested the
elimination of the GO TO statement. In 1966, a paper presented in Italian (and
later translated into English by C. Bohm and G. Jacopini) defined the
theoretical framework for structured programming. The paper stated that any
program solution can be expressed in three fundamental control blocks: a
processing box, a decision symbol of the IF… THEN… ELSE type and some form of
looping procedure.
These three components are the basis for structured
programming solutions. The identification of these three structures, namely (a)
used to follow a sequence of steps (b) select alternative paths and (c)
establish program loops formulated the foundation of structured programming.
Some advantages of structured programming are:
1. Complex programs may be divided into simpler and more
manageable elements.
2. Simultaneous coding of modules by several programmers is
possible.
3. A library of modules may be created and these modules can
be used in other programs.
4. Reduced testing and debugging time
5. Increased programmer productivity.
6. Less complexity in programs that are essentially
maintained and modified.
7. Increased clarity by reducing complexity.
Features of C Programming Language
The C language was successful in developing UNIX
operating systems. It has special reasons to become very popular in the
programming world.
·
Portability: This refers to the ability of a program to run in
different environments. Some programming language compilers such as FORTRAN and
Pascal could be used in those computers containing the same compilers. Since, C
languages have different compilers almost in all systems, a C is termed as the
most portable language.
·
Flexibility: The C language combines the convenience and portable
nature of high-level language with the flexible nature.
·
Wide acceptability: The C language is known to the entire world. The
language is suitable for projects at the system level and at the application level.
Program Characteristics
Although many programs are written by many programmers,
some common characteristics of program which makes it readable and portable
are:
1. The program should maintain its integrity. It should be
accurate in calculations.
2. The program should be clear in reading. It should be
accurate in calculations and enhance the readability of the program for future
reference.
3. The program should be designed in a simple logic. Simple
logic is easy to understand.
4. It should be executed very fast and utilize the memory
efficiently.
5. The program should be broken down into pieces or modules.
A modular program is easy to handle and read.
6. The program should be general with reasonable limits.
Elements of C
Before we begin about different aspects of C programming
language, let us discuss on some of the important elements of C. Every C
program consists of one or more modules. These modules are called functions.
One of the functions must be called main ().
The program will always begin by executing the main function.
This function may access other functions. There can be many functions. Each
function should be defined separately. The user defined functions are either
defined ahead of the main function or within the main function. Each function
must contain the following:
1. A function heading, which consists of the function name
(including the arguments if present)?
2. A list of argument declarations if the arguments are
included in the heading.
3. A compound statement, which comprises the remainder of
the function.
The arguments are also called the parameters. Each
compound statement is enclosed within a pair of braces i.e. { }. The Comments
or remarks may appear within the program anywhere within the delimits /* and
*/. The comments help to read the program and make convenient during debugging
the program errors.
Example 1:
#include <stdio.h> #include <conio.h> Void main () { Printf (“\n Hello Learner.\n”); Printf (:\n Bye”); Getch(); |
Explanation
#include directive: This is an essential directive. A directive is linked to a header file.
The header file make full use of the I/O functions of the standard C library.
Here, stdio.h is a header file and # sign is known as processing directive.
Void main() function: This is the main function that must appear in every C program. Main
without void is used when where there are no arguments main() without any
parameters has an argument.
Printf () function: The letter f in print function stands for formatted. This function is used
to print out the messages, either on screen or paper.
{} braces surround the body of the function used to group
statements together.
\n represents new line sequence or new line start. This
is also known as the escape sequence and every line is terminated with a
semicolon (;) in C programming language. Without \n, the characters are printed
on the same line without any spaces.
Return 0 makes the compiler happy.
get () function holds from screen scrolling. It is
defined in stdio.h header file.
C language users small letter or lowercase letters. No
capital letters are used unless it is specified as in define statement.
The above program
is rewritten to understand the function of void and return statements.
#include <stdio.h> main () { Printf (“\n Hello C”); Printf (“\n Bye”); Return 0; } |
In this case, the
compiler is happy to execute the program. The above program is rewritten in a
different way. It gives the same output as we did with previous programs.
………………………………………………………………………………………………………………………………………………………….
Character Set of C Programming Language
Character Set
The C character set consists of upper and lowercase
alphabets, digits, special characters and white spaces. The alphabets and
digits are altogether called as the alphanumeric character.
1. Alphabets
A B C D E F ………..Z
a b c d e f ………….z
2.
Digits
0 1 2 3 4 5 6 7 8 9
3.
Special Characters
, comma | . period | ; semicolon |
: colon | # number sign | ‘ apostrophe |
“ quotation mark | ! exclamation mark | | vertical bar (pipe) |
~ tilde | < opening angle bracket | > closing angle bracket |
_ under score | $ dollar sign | ( left parenthesis |
) right parenthesis | % percent sign | ? question mark |
& ampersand | ^ caret | * asterisk |
- minus | + plus sign | [ left bracket |
] right bracket | { left brace | } right brace |
/ slash | \backslash |
4.
White space characters
Blank space newline carriage return
Form feed horizontal tab vertical tab
Escape Sequence: The escape sequence is
used in C programming language. The escape sequence helps in managing the
programs. These are also known as backslash character constants
Character | Escape Sequence | ASCII Value |
bell (alert backspace horizontal tab the new line (line feed) vertical tab form feed carriage return a quotation mark (“) apostrophe (‘) a question mark (?) backslash (\b) null octal number hexadecimal number | \a \b \t \n \v \f \r \” \’ \? \\ \0 \o0 \xhh | 007 008 009 010 011 012 013 034 039 063 092 000 Eg., \5, \005, \123, \177 Eg., \x5,\x53, \x7f |
Identifiers and Keywords
Every word in C programming language is classified either
as identifier or keyword. Identifiers are used to name the variables, symbolic
constants, function, etc. Keywords are reserved words and they have predefined
meanings and cannot be changed by the user. Identifier names have particular
rules, such as:
1. Identifier name must begin with a letter and must be a
sequence of letters and digits.
2. The underscore character (‘_’) is considered as the
letter.
3. All the keyword must be in small letters. They have
reserved works and they cannot be treated as a variable in the program. They
use specified syntax.
4. The C language is case sensitive. For example, rate, Rate
and RATE are treated as three different types of data.
5. For any internal identifier name, at least 31 characters
are significant.
The keywords are:
·
Auto double int struct
·
Break else long switch
·
Case enum registers
typedef
·
Char extern return union
·
Const float short
unsigned
·
Continue for
signed-unsigned
·
Default go to size of
volatile
·
Do if static while
Variables
A variable is an entity that has a value and is known to
the program by name. The value of the variable changes during each execution.
The variable definition associated with memory location is with the variable
name. A variable can have only one value assigned to it in every time of
execution of the program. Its value can change in different executions.
Example
F= 1.8 * c +32
The above example tells that f and c are the variables.
Their values will be changed while the program executes.
Naming a Variable
Since, a variable has a name, let us give some example of
valid variables.
I, rank, max, min, class_mark, stud_name,emp_no, Mark,
StudName, etc. are valid variables names.
Here are some invalid variables names.
·
Sun’s illegal character
(‘)
·
Fine doubled blank space
not allowed
·
5square first character
should be letter
·
teacher, sal comma not
allowed
The variable described above can be put into two
categories, namely, globally variable and local variable. The variables defined
before the main () are considered as the global variable and the variables
within the function or program modules are local variables.
The global variable can be accessed from any subprogram
or module or function whereas the local variables are confined within the same
module or function.
Example:
#include <stdio.h> #include <conio.h> Int a; Void main() { Program codes } |
In the above example, int a is the declaration of a
variable. The variable “an” is considered as a global variable which has effect
throughout the program and it can be used anywhere in the program.
Same Data Types
The C language uses various data types. Some of the most
important and common data types are listed below:
·
Char a single byte that
can hold one character
·
Int an integer
·
Float a single precision
floating point number
·
Double a double
precision floating point number
Note: Precision refers to the number of significant
digits after the decimal point. In another sense, it is the accuracy to a
certain decimal number.
Qualifier
A qualifier alters the characteristics of the data types
such as size or sign. The qualifier that alters the size is short and long.
They are applicable to the integers.
Example of Size Qualifier
·
Short int integer
represented by a lesser number of bits (usually 16)
·
Long int integer
represented by a greater number of bits (usually 32)
·
The qualifier long can
be used along with the double precision floating point type.
·
Long double an extended
precision floating point number
Examples of Sign Qualifier
The sign qualifiers are signed and unsigned. The sign
qualifiers combine the inter-data types (int, short int, and long int)
resulting in six more type of data.
·
signed chart int
·
unsigned short int
·
signed int
·
unsigned int
·
signed long int
·
unsigned long int
·
The sign qualifier can
be used with the character also.
·
signed char
·
unsigned char
Note: The size qualifier short and long cannot be applied
to the data types char and float, and sing qualifies signed and unsigned cannot
be applied to float, double and long double.
The following
table gives us the idea of the total numbers of bits and number range that can
be used in all IBM PC.
Data Type | Bits Used | Range of Numbers |
int short int long int unsigned int unsigned short t int unsigned long int | 16 16 32 16 16 32 | -32, 768 to 32, 767 Same as above -2, 147, 483, 684, to 2, 147, 483, 0 to 65,535 0 to 65,535 0 to 4, 294, 967, 295 |
Declaration of Variables
The variables are necessarily defined before they are
used. For this purpose, we use the following conventions.
data type v1,v2, …… vn;
Here, data type refers to the type of the data and v1,v2,
etc.., respectively represent different data in single line.
Example: The following way declaring variables are more appropriate.
int count; int number, total; double ratio; int no=10; |
The last example, int no=10, represents the assignment of
10 to a variable no which is integer type of data. This is an assignment
operation. Similarly, the other assignments are:
int filament =100;
char no = ‘x’;
double balance = 25. 28;
The process of giving the initial value to variables is
called initialization. C allows the initialization of more than one variable in
one statement using multiple assignment operators.
Example of Multiple Assignments
P = q = r = 0;
a = b =c = min;
Example of Assignments
Float x, p;
double y, q;
unsigned k;
Example of Declarations
int m = 5444;
long int n = 12345678;
Example of Assignments
x = 1.23456;
y = 9.887654;
k = 54321;
P = q = 100;
Example of Printing
printf(“\nm = %d”,m);
printf(“\nmn= ”,n);
printf(“\nx = %f”,x);
printf(“\ny = %2.12f”,y);
printf(“\nk = %u”
p = %f q = % 1.21f”, k,p,q);
Displaying Variables
The output of the program is 10. The variable num is
defined before it is used. A value 10 is assigned to the variable num and
finally %d tells that the value is in integer format. The %d is the format
string. It tells the printf that the output is an int. The second parameter num
provides the actual value to be output.
Example:
#include <stdio.h> void main () { int num; num = 10; printf (“\n %d”, num); } |
Reading Variables
The scanf function reads the values of variables from the
keyboard and stores them in variables.
Example: Reading values from the keyboard
#include <stdio.h> void main () { Float years, seconds; Printf (“\n Input your age in years: Scanf (“%f”,& years); Printf(“\n You have Lived for %f } |
The output will be:
Input your age in years: 12
You have Lived for 378432000.000000 seconds.
Value Initialization Variables
We can declare an integer variable i by the statement:
int i;
This can be initialized in two other methods.
int i;
i = 10;
Or,
int i = 5;
If you want more than one variable to be initialized at
the same time, use the following convention.
int i = 100, j = 15;
Now, i and j both are a same (int) type of data which
have already assigned values.
Characters and Character String
A character variable %c can hold only one character which
can be alphabet or symbol. Let use examine the following example.
Example:
#include <stdio.h> main () { /* declare a character */ Char c; /* assigning a character to the c =” # “; printf( “\n This is the hash symbol: } |
Example: Printing ASCII code.
#include <stdio.h> void main () { int code; char symbol; printf (“\n Input an ASCII code (0 scanf (“%d”,& code); symbol = code; printf ( “\n The symbol } |
In the above example, we have seen the single character that can be input to
the computer and that can be displayed. Let us examine how the strings are
accessed from the keyboard and displayed. A string in C is a sequence of
consecutive characters in the memory, the last one being the null character. A
null character has an ASCII code 0 and is called the end of string marker in C.
Example: Using String
#include <stdio.h> void main () { char mystring [20] =”My Nepal My printf (“\n The string is : %s”, } |
In the above
example, mystring [20] defines the number of characters that can be stored in
the string variable. The %s sign is used for string formatted output. The
characters of above string placed in sequence as follows
String | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
Char | M | y | N | e | p | a | 1 | M | y | P | r | I | d | e | \0 | |||
ASCII Code | 77 | 121 | 32 | 78 | 101 | 112 | 97 | 108 | 32 | 77 | 121 | 32 | 112 | 114 | 105 | 100 | 101 | 0 |
Now, let us examine how the string is scanned from the
keyboard with the help of the following example.
Example:
#include <stdio.h>
void main ()
{
char mystring [20];
scanf (“%s”, & mystring);
printf (“\n The string is: %s”, mystring);
}
In this example, if you enter a string with spaces, the
string before the first space only will be the output. This is suitable when a
long string without blank spaces is used. All the characters after the first
blank (space bar) will be truncated.
To print the entire sentence with more characters and
blank spaces, we use gets () and puts (). This is illustrated with the
following example.
Example:
#include <stdio.h> void main () { char mystring [20]; printf (“\n Enter a string: “); gets (mystring); printf(“\n The string is :”); puts (mystring); } |
While running above program, as you enter a string within
20 characters long, it is accepted by gets () function prints the string on the
screen.
Qualifiers
Qualifiers modify the behavior of the variable type to
which they are applied. Some examples of qualifiers we discussed earlier are:
int i;
signed int i;
unsigned int i;
There are two size qualifiers that can be applied to
integers: short and long. In any ANSI C complier, the size of short int, int
and long int follow the restrictions given below:
1. The maximum size of a short int is 16 bits.
2. The size of an int must be greater than or equal to that
of a short int.
3. The size of a long int must be greater than or equal to
that of an int.
4. The maximum size of a long int is 32 bits.
The size of each type on your compiler can be tested by
using size of operator. It gives the size of any data type in bytes.
Example:
#include <stdio.h> void main () { printf (“size of a short int is %d printf(“size of a long int is %d } |
The output of the program is:
size of a short int is 2 bytes
size of an int is 2 bytes
size of a long int is 4 bytes
The following format specifies are used for displaying
short and long integers.
Example:
#include <stdio.h> Void main () { short int shorti; long int longi; printf (“\n Input short int: “); scanf (%hd”, &shorti); printf (“\n Input long int: “); scanf (“%d”, &long); printf (“ shorti = %hd and longi = } |
A sample run output is given below:
input short int: 45
input long int: 600000000
shorti =45 longi = 600000000
The typedef Statement
The typedef statement is used to give new names to
exiting types. For example,
Typedef unsigned long ulong;
This statement declares ulong a new type, equivalent to
unsigned long. It can e used just any other type in program. Eg., ulong u;
Similarly, typef int integer;
Creates integer as a synonym for int. Then, you can use
integer to define variables of type int, as;
integer count;
typedef Example typedef int age;
In this example, the declaration age is a user-defined
data type, which is equivalent to type int. Hence, the varaiable declaration,
age male, female
Is equivalent to writing int male, female;
In other words, male and female are regarded as variables
of type age, though they are actually integer-type variables.
The typedef feature is particularly convenient when
defining structures, as it eliminates the need to repeatedly write struct tag
whenever a structure is referred.
Promotion and Typecasting
Promotion is the type of data conversion when the
variable of lower type is converted to a higher type i.e. the variable that
holds lower range of values or has lower precision is converted to a variable
that holds higher range of values or higher precision.
Example:
int i;
float f;
i = 5;
f = i;
Here, the last statement assigns i to f. Since, i is an
integer, while f is floating point variable, the integer i is converted to
float automatically. This is data type promotion. Another type of promotion is
the conversion of a character to an integer. This particular type of promotion
is called internal promotion.
Example:
int i;
char c;
c = ‘a’;
i = c;
The value present in the character c, i.e., the ASCII
code of the character a is assigned to the integer i.
Assignments of variables of higher types to those of
lower types result in truncation.
Example:
f = 7.8;
i = f;
Results in the fractional part (0.8) discarded. The value
7 is assigned to the integer i.
When we explicitly convert integer value i to floating
point number, the explicit type of conversions are called typecasting.
Example:
int i;
Float f;
i = 12;
j =5;
f = i/j;
Printf(“%f\n”,f);
To obtain the floating point division, we have to convert
either i or j into floating point of data. This can be done by using the
following relation.
f = float (i/j);
Constant
INTRODUCTION
A constant is fixed entity. It does not change its value
during the entire program execution. Constants can be classified as:
1. Integer constants
2. Floating point constants
3. Character constants
4. Enumeration constants
5. String literals
1. Integer Constant
An integer constant is an integer-valued number. It
consists of a sequence of digits. Integer constants can be expressed in three
ways. They are:
A Decimal Integer: A decimal integer constant can consist
of any combination of digits which is taken from the set of 0 to 9 digits.
Example: 0 1 234 5654 etc.
An Octal Integer: An octal integer constant can consist of any combination of digits which is
taken from the set of 0 to 7 digits. However, the first digit must be 0, in
order to identify the constant as an octal number.
Example: 0 01 077
Hexadecimal Integer: A hexadecimal integer constant must begin with either 0x or 0X. It can
then be followed by any combination of digits taken from 0 to 9 and also
through f (uppercase or lowercase).
Example: 0x 0x1 0x7ABC 0xabc
Unsigned and Long Constants: Unsigned integer constants exceed the magnitude of ordinary integer
constants by approximately a factor of 2 and they should not be negative. Long
integer constants need more memory. The letter appending L to the end of the
constant can create long integer constant.
Example: 5000u decimal
unsigned
1234567L decimal long
01234L octal long
0xffful hexadecimal unsigned long
2. Floating-Point Constants
A floating point constant is a base 10 number (decimal
number) that contains either a decimal point or an exponent or both.
Example: 0.00 1.00 12.56
876.567
2E-8 0.006e-3 1.66e+8 .121e12
3. Character Constants
A character constant is a single character enclosed in
single quotes (single quotation mark).
Example: ‘a’ ‘A’ ‘?’
4. Enumerated Constants
An enumeration is a user defined type with values ranging
over a finite set of identifiers called enumeration constants. For example,
Defines color as a new type having three values red, blue
and green. Each of these is an enumeration constant. Let us examine how it
works.
color c; declares c to be of type color
c = blue;
printf (“As an int, C has the value %d\n”,c);
Will print,
As an int, c has the value 1
Similarly, we can define enum type of data as follows:
enum daysofweek { sun, Mon,Tue, Wed, Thu, Fri, Sat} ;
5. String Literals (String Constants): A string literal is a sequence of characters enclosed in
double quotes. The characters may consist of letters, numbers, escape sequences
and spaces.
Example:
“C is hard for learning” string literal
“ C” is hard for learning” string literal
Symbolic Constant
A symbolic constant is a name that substitutes for a
sequence of characters. The characters may represent a numeric constant, a
character constant or a string constant. Hence, a symbolic constant allows a
name to appear in place of a numeric constant, a character constant or a
string.
Symbolic constants are generally defined at the beginning
of the program. The symbolic constant can appear after this, in place of
numeric constants, character constants,etc.
#define name text
Example:
#define PI 3.1416
#define TRUE 1
#define friend “Bhimsen”
The const Qualifier
The const qualifier defines the constant such that the
compiler uses its value and it cannot be modified anywhere in the program. This
can be achieved either by using #define preprocessor directive or using the
const qualifier.
Example:
#include <stdio.h> void main () { const float tax_rate=0.05; float sal, tax; printf (“Salary: “); scanf (“%f”, &sal); tax = sal*tax_rate; printf (“\ntax =%f\n”, tax); } |
Now, let us to
examine the same program using #define directive.
#include <stdio.h> #define tax_rate 0.05 void main () { float sal, tax; printf (“Salary: “); scanf (“%f”, &sal); tax = sal*tax_rate; printf (“\ntax =%f\n”, tax); } |
While executing the both programs, you will get the same
result.
Operators and Expressions
Every expression evaluates to a value. Every expression
results in some value of a certain type that can be assigned to a variable. The
data items that operators act upon are called operands. An operator is a symbol
that operates on a certain data type. The operator generally remains between
the two operands. An expression is a combination of variables, constants, and
operators written according to the syntax of the language.
Based on their utility, the operators are classified into
different categories in C. Some of the most common operators are listed below.
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and Decrement Operators
6. Conditional Operator
7. Bitwise Operator
8. Comma Operator
9. Other Operator
1. Arithmetic Operator
The arithmetic
operators perform arithmetic operations and can be classified into unary and
binary arithmetic operations. The arithmetic operators can operate on any
built-in data type. A list of arithmetic operators and their meanings are given
below:
Operator | Meaning |
+ - * / % | additional or unary plus subtraction or unary minus multiplication division modulo division (returns remainder |
Note: for writing the power, there is no special
operator. However, the function pow(x,y) exists in math.h which return x^x.
2. Relational Operator
The relational
operators help to compare two similar quantities and depending on their
relation, take some decisions. If the condition is true, it evaluates to an
integer 1 and zero if the condition is false. The basic types of relational
operator are:
Operator | Meaning |
< > <= >= == != | less than greater than less than or equal to greater than or equal to equal to not equal to |
In order to study the relational operators, it is desired
to have knowledge of if statements. Here, if it is followed by the condition
and the condition is built up from the relational operators in between the
operands.
3. Logical Operator
The logical operator is used to compare or evaluate
logical and relational expressions. There are three logical operators.
An expression that contains both && and || is
called compound expression.
4. Assignment Operator
One of the most common assignment operators is an equal
sign. The character or value on the right is assigned to the variable on the
left of equal to sign. The other forms of assignment operators are:
1. += evaluates the expression to its right and adds the
resulting value to the variable on its left.
2. -= evaluates the expression to its right and subtracts
the resulting value to the variable on its left.
3. /= evaluates the expression to its right and divides the
resulting value to the variable on its left.
4. *= evaluates the expression to its right and multiplies
the resulting value to the variable on its left.
5. a<<=5 shifts the bits of a to the left by 5-bit
positions.
6. a>>=5 shifts the bits of a to right by 5-bit
positions
5. Increment and Decrement Operators
The increment and
decrement operators are very commonly used in C language. The increment
operators and decrement operators are extensively used in the loops using
structures such as for, while, do, etc. The syntax of the operators is given
below.
++<variablename> --<variablename> <variablename>++ <variablename)-- | preincrement predecrement postincrement postdecrement |
The preincrement operator increases the value of the
variable by 1 and then the processing does whereas post increment first
processes and increase the value of it by 1.
6. Conditional Operator
A conditional operator is very rarely used. This can be
carried out with the conditional operator (? : ) An expression that makes use
of the conditional operator is called a conditional expression. This can
replace the if-else statement. The syntax of conditional operator is:
Expression_1 ? expression_2: expression_3
During evaluating
the conditional expression, expression_1 is evaluated at the first step. If
expression_1 is true (nonzero), then expression_2 is evaluated and this becomes
the value of the conditional expression.
Library Functions
INTRODUCTION
In C language, a number of library functions are used.
They carry out various commonly used operations or calculations. Some functions
return a data item to their access point and others indicate whether a
condition is true or false. Some other functions carry out special operations
on data items.
Library functions that are functionally similar and
usually grouped together as object programs (compiled) in separate library
files. These library files are supplied as a part of each C compiler.
A library function is accessed simply by writing the
function name, followed by a list of arguments that represent information being
passed to the function.
The arguments must be enclosed in parentheses and
separated by commas. These arguments can be constants, variable names, etc.
Some important functions are given below.
List of Library Functions
Function | Type | Purpose |
abs(i) ceil(d) cos(d) cosh(d) exp(d) fabs(d) floor(d) fmod(d1,d2) getchar() log(d) pow(d1,d2) printf(…) putchar(c) rand() sin(d) sqrt(d) srand(u) scanf(…) tan(d) toascii(c) tolower(c) toupper(c) | int double double double double double double double int double double int int int double double void int double int int int | Return the absolute value of i. Round up the next integer value Return the cosine of d. Return the hyperbolic cosine of d. Raise e to the power d. Return the absolute value of d. Round down the next integer value Return the remainder Enter a char from the standard input Return the natural logarithm of d. Return d1 raised to the power d2. Send data items to the standard Send a character to the standard Return a random positive integer Return the sine of d. Return the square root of d. Initialize the random number Enter data items from a standard Return the tangent of d. Convert value of an argument to Convert the letter to lowercase. Convert the letter to uppercase. |
Data Input/output
The most common library functions responsible for input
and output operations in C are: getchar (),
Putchar (), scanf (), printf (), gets (), and puts ().
The getchar () and putchar () are the functions used to accept a single
character from the keyboard and display on the monitor. The scanf () and printf
() functions are flexible.
They can accept values, characters, and strings and use
suitable format specifier that can be displayed. Knowing the structure of these
functions one can write many C programs in a simple form. Let us examine each
of them.
The getchar () Function
Single character can be entered into the computer using
the C library function getchar (). This is a part of the standard I/O library.
It returns a single character from the standard input device (keyboard). The
function does not require any arguments but empty parentheses must follow the
keyword getchar.
Syntax:
Character variable = getchar ();
While using getchar () with file handling functions, if
an end-of-file condition is encountered with reading a character with the
getchar function, the value of the symbolic constant EOF will automatically be
returned.
# Write a program to input a character form the keyboard and print.
#include <stdio.h> main() { char c; printf(“\n Enter a character: “); c = getchar (); printf(“\n The character input is putchar (c); } |
The putchar () Function
The putchar () function is used to display single
characters. It is a part of standard C I/O library. It transmits a single
character to the standard output device (monitor). The character being
transmitted will normally be represented as a character-type variable. It must
be expressed as an argument to the function, enclosed in parentheses, following
the word put char.
Syntax:
Putchar ( character variable);
# Write a program to test and verify putchar () function.
#include <stdio.h> main() { char c; printf (“\n Enter a character of c = getchar (); printf(“\n The character that you putchar (c); } |
While executing the program, if you enter a word, the
first character is only displayed. This is due to the fact that single
character is passed to the character-type variable c.
String Input/output Functions
The above discussed functions can print the characters
only. You can use a scanf() function to read a line of text but during
printing, the characters before the white space are only printed. Let us
examine the following program.
# Write a program to accept a string of 80 characters long and print it.
#include <stdio.h> #include <ctype.h> main() { char string [80]; printf(“\n Enter a string:”); scanf(“%s”,&string); printf(“\n The string accepted is } |
While executing the above program if you enter a word of
80 characters long without any spaces, it will be printed. But if you supply
space before at any place, only the first word will be printed.
The gets() and puts() Function
The gets() and puts() functions are used to input
complete sentences with comma, semicolon, etc. and that can be printed on the
screen.
Example
#include <stdio.h> main() { char ch [80]; gets (ch); …….. ……… } |
The above segment of the program has defined ch variable
with 80 characters as an array. The gets() function contains the same variable
in the parentheses.
Here, puts() is an output function which lets to display
the output on a suitable device. This function is generally used to display the
output that has been accepted from the keyboard.
Write a program in C to accept a sentence with comma and semicolon and
print on the screen.
#include <stdio.h> void main () { char c[ 80]; printf(“\n Enter a sentence:”); gets (c); printf(“\n The entered sentences puts (c); } |
We can use an alternative form of entering a line of text
using the following convention.
# Write a program to input a line of text without using gets () and puts ()
function.
#include <stdio.h> #include <conio.h> main () { char line [80]; printf(“\n Enter a line of text:”); scanf(“% [^\n”, line); clrscr (); printf(“\n You have entered the line printf(“\n\n %s”, line); } |
General Input: The scanf() Function
The C library function scanf() is used for entering the
data from the standard input device such as a keyboard. This function can be
used to enter any combination of numerical values, single characters, and
strings.
Syntax:
scanf(“control string”, arg1, arg2, ………, argn);
Here, the control
string (also called format string) includes the group of characters with one
group of characters for each input data. Each character group begins with a %
sign. A single character group consists of the % sign followed by a conversion
character that indicates the data type. Different types of data items and
conversion character are given in the below table.
Conversion Character | Meaning |
%c %d %e %f %g %h %i %o %s %u %x [……..] | Data item is a single character Data item is a decimal integer Data item is a floating point value Data item is a floating point value Data item is a floating point value Data item is a short integer Data item is a decimal, hexadecimal Data item is an octal integer Data item is a string followed by a Data item is unsigned decimal Data item is a hexadecimal integer Data item is a string which may |
Example: Test for input of a decimal number.
#include <stdio.h> main () { int i; printf(“\n Enter an integer:”); scanf(“%d”,&i); printf(“\n The input decimal value } |
General Output: The printf () Function
The output data can be given to the monitor from the computer
using the printf() function. This function is useful for printing any numerical
values, single characters, and strings. It is similar to the scanf() function
but it is used to display the data on the suitable standard output device. The
printf() function moves the data from computer’s memory to the output device.
Syntax
Print(“control string”, arg1, arg2, ……., argn);
The control string is also known as a format string. The
format string contains text, commas and a format specifier such as %c, %d, %f,
etc. which receive the data from the arguments respectively.
Example: Test of a format string and format specifier.
#include <stdio.h> main () { int i; printf(“\n Enter an integer:”); scanf(“%d”,&i); printf(“\n The input decimal value } |
Let us examine the line:
printf(“\n The input decimal value %d”,i);
This line
contains %d within the double quotes which is format specifier and receives the
value from i.
……………………………………………………………………………………………………………………………………………………….
Control Structures
INTRODUCTION
C programs are written in the linear fashion. The linear
programs have almost no logical comparison. A realistic C program may require
that a logical test is carried out at some particular point within the program.
One of the several possible actions will then be carried out, depending on the
outcome of the logical test.
The outcome obtained by making comparisons and moving
further calculations is known as branching. Logical statements are tested from
several available groups of statements within the program. The program which
forms repetitions for a certain number of time is known as looping.
All these branching, selection, and looping are the
fundamental necessities of the program without which one cannot make decisions
and the program remains incomplete. Structures use different kinds of signs and
symbols for constructing the control flow within the program. The logical
expressions, relational operations, assignment operators are extensively used
in the different program.
The common relational operators are: <, <=, >,
>=, the equality operators are: = = and !=. The logical connectives are
logical operators such as && (And), || (OR). The conditional operator ?
: is also used in the expression in the program.
There are three different kinds of statements in C;
expression statements, compound statements and control statements. An
expression statement consists of an expression followed by the semicolon. A
compound statement consists of a sequence of two or more consecutive statements
enclosed in braces ({ and }).
The enclosed statements can be expression statements,
other compound statements or control statements. Most control statements
contain expression statements or compound statements including embedded
compound statements.
Thus, control statements are two types They are:
1. Decision-making statements
·
if statement
·
else statement
·
switch statement
2.
Looping statements
·
for loop
·
while loop
·
do-while loop
The if Statement
A single line if statement makes a decision about a
single condition.
Syntax:
If (condition)
statement;
# Write a program to check whether a given number is divisible by 4.
#include <stdio.h> void main() { int i; printf(“\n Enter a number:”); scanf(“%d”,&i); if (i%4=0) printf(“\n The number given is } |
# Write a program to convert a given time number into seconds.
#include<stdio.h> void main() { float years, secs; int success; printf(“\n Input Your Age in scanf(“%f,&years); success = years; if (successs ==0) { printf(“\n The input value is not } if success !=0) secs = years *365*24*60*60; printf(“\n You have lived for %f } |
In above program, if statement justify the same condition
for two times. The program becomes longer. The judgment takes place two times
and if you have such conditions repeatedly in the program it slows down the
program.
# Write a program to determine the largest number among three input
numbers.
#input <stdio.h> void main() { float a, b, c, big; printf(“\n Input First Number:”); scanf(“%f”,&a); printf(“\n Input Second Number:”); scanf(“%f”,&b); printf(“\n Input Third Number:”); scanf(“%f”,&c); /* making comparison and computing big = a; if (b>big) big =b; if (c>big) big =c; printf(“\n Largest Number among } |
For a condition,
the program need to execute more than one line should be placed compound or
placed within the compound statements as:
If (condition) { Statement; Statement; } |
The if..else Statement
The if..esle statement is the statement which compares
the given condition. If the condition is true, the execution takes place
immediately after the if clause. If the condition is false, the execution takes
place immediately after the else clause. The statements within after if and
else can be compounded. If the statements are not compounded, the first
statement immediately after the clause will be executed.
It is a condition testing statement. As long as the
statement 1; a group is not included in the compound statement, only the first
line will be executed. If you want to execute multiple lines under the given
condition use if clause or else clause.
# Write a program to test whether the given input is zero or non-zero.
#include<stdio.h> void main() { int input; printf(“\n Enter a number:”); scanf(“%d”,&input); if(input) printf(“\n It is non-zero.\n”); else printf(“\n It is zero.\n”); } |
Compound Statement
A compound statement is set of statements enclosed within
a pair of curly braces. The curly braces are:{ and}. The {braces is opening
brace and } is closing brace. We have discussed these compound statements in
our previous examples.
A compound statement is not simply sequences of
executable statements. They can also contain variable declarations at the
beginning. The variables declared explicitly within the compound statements
have local scope.
Example: Test of variables within the compound statements
#include<stdio.h> void main() { int i = 10; printf(“\n In the main, i is %d.\n”, /* beginning of a compound statement { /* variable declared */ int i = 20; printf(“\n Inside the compound i++; printf(“\n After incrementing the } printf(“\n In the main() the value } |
# Write a program to check whether a given number is a prime number.
/* check prime number */ #include<stdio.h> #include<conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number:”); scanf(“%d”,&a); n = a; if (a==1 | | a==2 | | a==3) printf(“The num %d is prime while (b! = (a-1) { aa: r = a%b; b=b+1; if ( r ==0) { printf(“\n The num %d is not a prime break; else if (b!= (a-1) { goto aa; else printf(“\n The num %d is a prime } } |
# Write a program to check whether a given number is odd or even.
#include <stdio.h> #include <conio.h> main() { int a,r; printf(“\n Enter a number:”); scanf(“%d”, &a); r=a%2; if(r==0) printf(“\n The given number %d is else printf(“\n The given number %d is getch(); } |
# Write a program to check whether the given number is larger than 100.
#include <stdio.h> #include <conio.h> void main () { int a; printf(“\n Enter a number:”); scanf(“%d”, &a); if (a>=100) printf(“\n The number is larger than else printf(“\n The number is smaller |
# Write a program to check whether a student can enroll
in grade XI where the conditions are:
Students must score more than 70 in Math, Science and English.
#include <stdio.h> #include <conio.h> void main () { clrscr(); int sc, math, eng; printf(“\n Enter marks scored in scanf(“%d”,&sc); printf(“\n Enter marks scored in scanf(“%d”,&math); printf(“\n Enter marks scored in scanf(“%d”,&eng); if (sc>=70 && math>=70 printf(“\n You are selected.”); else printf(“\n You are not selected.”); } |
The Switch Statement
INTRODUCTION
The switch statement causes a particular group of
statements to be chosen from several available groups. The switch statement is
useful when a variable is to compare with different constants, and in case it
is equal to a constant, a set of the statement are to be executed. The
constants used in the case can be of char or int data type only.
Syntax:
Switch (n) { Case 1: Statement 1; Statement 2; Break; Case 2: Statement 1; Statement 2; Break; Case 3: Statement 1; Statement 2; Break; ………… …………. default: statement ; statement; } |
Note: If you are using a character in place of n in above
syntax example, the case should be enclosed in a single quote as case ‘1’ :,
case ‘2’:, etc.
# Write a program to accept choice to find the cost price for traveling
from Kathmandu to different destination.
#include <stdio.h> #include <conio.h> void main () { int choice, num; float rate, total=0; printf(“\n Enter your choice: \n”); printf(“\n 1. Pokhara “); printf(“\n 2. Biratnagar “); printf(“\n 3. Birgunj“); printf(“\n 4. Exit“); scanf(“%d”, &choice); switch (choice); { case1: rate =350; printf(“\n Number of persons: “); scanf(“%d”,&num); total = rate * num; printf(“\n The cost is : %5.2f”, break; case 2; rate =300; printf(“\n Number of persons : “); scanf(“%d”, &num); total = rate *num; printf(“\n The cost is %5.2f”, break; case 3; rate =250; printf(“\n Number of persons : “); scanf(“%d”, &num); total = rate *num; printf(“\n The cost is %5.2f”, break; case 4: break; default: puts (“Thank you”); break; } |
Design a program to input two integer numbers from keyboard. On the basis
of choice, find out product, sum and difference.
#include <stdio.h> #include <conio.h> main () { clrscr (); /* use of case, switch and getch () int a, b, t=0; char ch; printf(“\n Enter first number :”); scanf(“%d”,&a); printf(“\n Enter second number :”); scanf(“%d”,&b); again: printf(“\n Enter choice : 1, 2 or ch = getch (); switch (ch) { printf(“\n Enter choice : 1, 2 or ch = getch (); switch (ch) { case ‘1’: t=a*b; printf(“\n Product is: %d”,t); break; case ‘2’: t=a+b; printf(“\n Sum is : %d,t); break; case ‘3’ : t=a-b; printf(“\n Difference is: %d”, t); break; default: printf(“\n Wrong entry.”); goto again; } } |
# Write a program to find area and perimeter of a triangle.
#include <stdio.h> #include <math.h> main () { float a, b, c, base, height, area, int k; printf(“\n Enter 1 for 3 sides of scanf(“%d”, &k); switch (k) { case 1: printf(“\n Enter 3 sides a, b & scanf(“ %f %f, &a, &b, p = a+b+c; s=p/2; area = sqrt ((double) (s* (s-a)* printf( “\n Perimeter = %6.2f printf(“\n Area = %7.2f\n”, area); break; case 2: printf(“\n Enter height and base of scanf(“ %f %f, &height, area = (base*height) /2; printf(“\n Area = %7.2f\n”, area); break; } |
Looping Constructs
A loop is structured construct which repeats for given
number of times. Looping makes a program more flexible. The number of times the
loop passes is known as iteration. The iteration is initialized at the
beginning whereas the last value of the loop is known as the sentinel value.
The loop repeats till the sentinel value. For the
construction of the loop, the loop variable should be initialized, incremented
or decremented and assigned the last value of the loop. Basically, there are
two types of loops.
1. Finite Loop and
2. Infinite Loop
A finite loop has a certain number of repetitions. It
stops when the last value is reached. But, the infinite loop does not stop
because it does not have the last value assigned. The infinite loop, in this
case, is useless. But, some system programmers use infinite loops for system
delay and operational delay inside the processor.
A loop consists of two segments known as control
statement and the body of the loop. There are three kinds of loops. They are:
1. For loop
2. While loop
3. do …while loop
For loop: Before using
for loop, let use to examine the structure of statement.
Syntax:
for ( initialization expression; { statement 1; statement 2; ………………...3; …………………..; statement n; } |
Initialization expression is the expression which
initiates the first value of the loop.
Test expression determines the last value of the
expression.
The updated expression is the increment or decrement from
the initialization so that the last value or test expression could be reached.
The infinite loop, where beginning and ending are not
expressed there is no initialization, text and update expressions.
# Write a program to find sum of given three numbers using for loop
construct.
/* Program to find sum of given #include <stdio.h> #include <conio.h> int main () { int i=1, a[3]; float sum=0; float avg=0; for (i=1; i<=3; i++) { printf(“\n Enter %d number: “i); scanf (“%d", &a [i]); } avg=sum/3; printf(“Sum of given numbers is : printf(“\n Average is %4.2f”, avg); } |
# Write a program to print first ten even numbers.
#include <stdio.h> main () { int n=2,c =1; for (c=1; c<=10; c++) { printf(“%d\t”,n); n=n+2; } } |
# Write a program to find the factorial of a given number.
/* finding factorial of a number */ #include <stdio.h> #include <math.h> void main () { int n, i, fact; printf(“\n Enter a number:”); scanf(“%d”,&n); if (n= =0) { printf(“\n Factorial of %d is 1”,n); } else { fact =1; for (i=1; i<n; i++) { fact =fact *i; } printf(“Factorial of %d is %d”, n, } } |
# Write a program to print first 10 number of Fibonacci series of order 2.
#include <stdio.h> #include <conio.h> #include <math.h> void main () { int a=1,b=1,c=0,d; for (d=1; d<=10; d++) { printf(“%d”,a); c=a+b; a=b; b=c; } |
Looping With while statement
The while statement is used to carry out looping
operation, in which group of statements is executed repeatedly until some
condition has been satisfied.
Syntax:
while (expression) { statement 1; statement 2; ………………….; statement n; } |
The statement will continue as long as the expression is
true. The statement can be simple or compound though it is usually compound
statement. It should be noted that within the compound statement, the
expression should be changed for stopping the loop. Let us examine a program
below.
# Write a program to print the numbers is prime number. A prime number is
divisible by 1 and itself.
/* check prime number */ #include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =a; if (a==1 || a==2 || a==3) printf(“The num %d is prime number”, while (b!=(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n The num %d is not a prime break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime } } |
# Write a program to check whether given number is Armstrong number.
Armstrong number is the number which is equal to the sum of the cubes of its
individual digits.
/* Check for Armstrong number */ #include <stdio.h> void main () { int a, n, r, sum=0; printf(“\n Enter a number:”); scanf(“%d”,&a); n=a; while (n!=0) { r=n; if (r!=0) { sum +=r*r*r; } n =n/10; } printf(“\n Sum of cubes of given if (sum==a) { printf(“\n Given number %d is equal printf(“\n The number is Armstrong } else printf(“\n The number is not a an |
…………………………………………………………………………………………………………………………………………………………..
Looping with do…while Statement
We have come to across the use of while statement. It is
top tested, i.e., it evaluates before executing any of the statement in its
body. The do..while loop evaluates the condition after the execution of the
statements in its construct. At least one time the do…while statement executes.
Hence, do…while statement is known as bottom tested loop.
Syntax:
do { statement 1; statement 2; ………………….; statement n; } while (test expression); |
If the program loop should pass through 1 time or single
iteration, do…while statement would look like;
do
Statement 1;
While (test expression);
# Write a program to print the following numeric pattern.
1
12
123
1234
12345
#include <stdio.h> #include <conio.h> void main () { clrscr (); int outloop=1; do { int inloop =1; do { printf(“%d”,inloop); inloop = inloop +1; } while (inloop <=outloop); outloop = outloop+1; printf(“\n”); } while (outloop <=5); } |
# Write a program to check whether a number is palindrome or not.
#include <stdio.h> #include <conio.h> void main () { int n, num,digit, sum=0, rev=0; printf(“\n Enter a number”); scanf(“%d”,&num); n= num; do { digit = num ; sum+= digit; rev =rev*10+digit; num /=10; } while (num !=0); printf(“\n Sum of the digits = M”, printf(“\n The reversed number is: if (n==rev) printf(“\n Given number is else printf(“\n Given number is not } |
The break Statement
A break statement
is used in the program to breaking from the current point. It terminates the
execution of the current loop and the control is transferred to the statement
immediately by following the loop.
while (1) { scanf(“%d”, &i); if (I ==-1) break; sum+=1; num++; } |
This program segment has used the break statement. If the
input value is -1, the condition i==-1 is true and the break statement is
executed. Otherwise, the program continues.
# Write a program to check whether a given number is a prime number.
/* check prime number */ #include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =a; if (a==1 || a==2 || a==3) printf(“The num %d is prime number while (b!=(a-1)) { aa: r= a%b; b=b+1; if (r ==0) { printf(“\n The num %d is not prime break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime } } |
# Modify the above program and recheck whether a given number is prime
number using different logic.
#include <stdio.h> #include <conio.h> void main () { int a, b=2, r, n; clrscr (); printf(“\n Enter a number: “); scanf(“%d”, &a); n=a; if ((a==1 || (a==2 || (a==3)) printf(“\n The number %d is prime if (a>3) { while (b!= (a-1)) { aa: r= a%b; b= b+1; if (r==0) { printf(“\n %d is not a prime number”, break; } else if (b! =(a-1)) goto aa; else printf(“\n The num %d is a prime } } } |
The continue Statement
As its name implies, it is used to continue the normal
flow of programe statement execution in loop; skipping parrticular iteration in
the loop as soon as certain condition is satified. The continue statement is
used to bypass the remainder of the current pass through a loop. The loop does
not terminate when continue statement is encountered. Instead, the remaining
loop statement is skipped and the computation proceeds directly to the next
pass through the loop.
Syntax:
#include <stdio.h> #include <conio.h> void main () { int i=1,num, sum=0; for (i=0; i<5; i++) { printf(“\n Enter an integer:”); scanf(“%i”, &num); if (num<0) { puts (“\n You have entered a continue; } sum+=num; } printf(“\n The sum of the positive getch (); } |
When you execute the above program, at the time you enter
a negative number, you will be prompted for negative entry of any number. It
allows you to go to next iteration. Thus, you can enter a new value for five
iterations. When you finish entering 5 positive integers, you will get the
result as you desire.
Difference
between break and continue statement
Break statement | Continue statement |
When break statement is encountered the entire loop or switch statement terminated. | when continue statement is the entire loop is not terminated only that particular itration is |
It is used with loop and switch case statement. | It is used only with loop structure. |
It uses a keyword break. | It uses a keyword continue. |
The goto Statement
The goto statement is common in GWBASIC and QBASIC.
Although QBASIC is structured it resembles in many cases with the procedural
programming concept. The goto statement in programming allows you to jump from
one place to another without any conditions. This is an unconditional transfer
to another part of the program.
Syntax:
goto label name; |
Use: Unconditional jump from one point to another part of
the program.
# Write a program to check whether a given number is a prime number or not.
#include <stdio.h> #include <conio.h> main () { int a, b=2, r, n; printf(“\n Enter a number :”); scanf(“%d”, &a); n =; if (a==1 || a==2 || a==3) printf(“ The num %d is prime while (b! =(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n The num %d is not a prime break; } else if (b!= (a-1)) { goto aa; } else printf(“\n The num %d is a prime } } |
# Modify the above program and recheck whether a given number is prime
number using different logic.
#include <stdio.h> #include <conio.h> void main () { int a, b=2, r, n; clrscr (); printf(“\n Enter a number :”); scanf(“%d”, &a); n=a; if ((a==1 || (a==2) || (a==3)) printf(“\n The number %d is prime if (a<3) { while (b!=(a-1)) { aa: r=a%b; b=b+1; if (r==0) { printf(“\n %d is not a prime break; } else if (b! =(a-1)) got aa; else printf(“\n The num %d is a prime { } } |
Nested Control Structures
Loops like if…else, for, do…while and while statements
can be nested, one within another. A loop inside another loop is nested loop.
While constructing nested loops, it is necessary to have the same type of
looping structure. The number of loops within a loop as many as you desire but
some systems limits to its memory limitation.
# Write a program to print multiplication table of number from 1 to 10 up
to 10 multiples.
/* multiplication table */ #include <stdio.h> #incldue <conio.h> void main () { int pro, i, j; for (int i=1; i<=10; i++) { for (int j=1; j<=10; j++) { pro=i*j; printf(“%d\t”, pro); } } } |
# Write a program to print the following pattern.
*
**
***
****
*****
#include <stdio.h> #include <conio.h> void main () { int i, j; char c=’*’; for (i=1; i<=5; i++) { for (j=1; j<=I; j++) { printf (“%c”, c); } printf(“\n”); } } |
# Write a program to print the following numeric pattern
(using do…while condition).
1
12
123
1234
12345
#include <stdio.h> #include <conio.h> void main () { clrscr (); int outloop=1; do { int inloop =1; do { printf(“%d”,inloop); inloop = inloop +1; } while (inloop <=outloop); outloop =outloop+1; printf(“\n”); } } |
……………………………………………………………………………………………………………………………………………………………..
Functions
INTRODUCTION
A number of statements grouped into a single logical unit
are called as function. It is true that C program is the collection of
functions. The function main() in the program is executed first. The other
functions are executed when the function main() calls them directly or indirectly.
It is necessary to have a single function main () in
every C program along with other functions. It is observed that the main()
function is also user defined function. It is executable with suitable
parameters.
We are aware of syntax and use of commands, statements,
and function in programming languages. C supports the use of library functions
which are used to carry out a number of commonly used operations or
calculations.
A C program can be modularized through the use of
intelligence of such functions. Hence, it is a modular programming. The C
language has two types of functions. They are:
1. Built-functions or C library functions
2. User-defined functions.
1. Built-function-or-C-Library-Functions:
The library functions are made available to the programmer in the inclusion of
the software product. They are precisely constructed to determine the type of
data they accept and the return type.
The library functions such as pow (), sqrt(), strcmp(),
etc, are located in the Lib folder by default.
2. User-defined Functions:
These are the functions determined by the
users. They are created for calculating different tasks. The general features
and facilities obtained from the use of user-defined functions are:
1. The repeated instructions can be placed within a single function
which can then be accessed whenever it is needed.
2. A different set of data can be transferred to the
function each time if it is accessed.
3. The use of a function avoids the need for redundant
(repeated) programming of the same instructions.
4. Functions provide the logical clarity resulting from the
decomposition of the program into several concise functions.
5. The use of functions also enables a program to build a
customized library of frequently used routines.
6. Function avoids repetitive programming between programs.
7. It also promotes portability since programs can be
written that are independent of system-dependent features.
Let us examine a function defined by the user.
int cube (int i) { Int retval; Retval = i* i * I; Return retvl; } |
This function is capable of returning a value (integer)
since it is explicitly declared in the definition line. The word cube is the
function name. The body of the function computes the cube of the value given to
i and returns the integer type of value through the variable reveal.
# Write a program to find the cube of 10 during function call and cube of
different integer value.
#include <stdio.h> #include <conio.h> int cube (int i) { int retval; retval = i*i*I; return retval; } void main () { int inputval; /* Cube of constant integer: */ /* function call with fixed value 10 printf(“\n The cube of 10 is %d\n”, /*Cube of input integer: */ Printf(“\n Input an inter:”); scanf(“%d”,&inputval); printf(“\n The cube of given value } |
You can predict the output. The program will give the
cube value of 10 and cube of a given number.
Use of Function
The functions are used to enhance the program. The user
defined functions help to calculate the values and return them. The functions
can be used in different programs as required. The basic three fundamental
properties of function are:
1. Functions help to divide the program into a number of
parts.
2. Reduces the size of a program because it can be called
independently.
3. Makes easier to find errors and debug them.
While writing a program, it is split into smaller
programs or functions in C. A main program is split into different programs or
functions .
The major activities of the function while programming
is:
1. Function declaration
2. Function call
3. Function definition
1. Function Declaration
The function is generally written above the main()
function. It is true that main is the main function without other functions
cannot execute. It is the entry point. A complete function can be written
before the main () function and that can be called from within the main()
function.
The generalized concept about the declaration of function
could be as follows:
·
Declare function to
inform the compiler that the function would use at the later point.
·
Declare function at the
beginning of a program.
·
Function declaration
includes function name, arguments, and their types, and return type of data.
Example
Void sum(); /*function declaration without parameter or
arguments*/
Syntax:
Type specifier, function name (arguments);
Here,
Type specifier refers to the type of the function such as
void, int, float, etc.
Function is the name of the function which can have as
many as 40 characters arguments could be int, float, int pointer, etc. which
indicates the type of return value in the function.
The function is generally declared before the main(). It
may be defined anywhere in the program but it should be declared at the
program.
2. Function Call
This is the part which executes the function. The
function is called from within the main().
The function and its parameters are explicitly included
within the function. Let us examine the function call as stated in above
program. The last section of this line cube (inputval) is the function call.
Although, it could be called in various ways, one of the simplest ways of
calling function is shown at this level.
A function can be accessed or called by specifying its
name followed by a list of arguments enclosed in the parentheses and separated
by commas. If the function call does not require any arguments, an empty pair
of parentheses must follow the name of the function.
The arguments appearing in the function call are referred
to as actual arguments. In the normal function call, there will be one actual
argument for each formal argument. The programmer needs to mention at least the
following points about calling a function.
·
Call from the main
program with arguments or without arguments.
·
Functionname ();
indicates function defined.
·
During function calling,
control transfers to the called function. Eg. Sum(); calls sum() function.
3. Arguments
The actual arguments must correspond to the formal
arguments in the function definition, i.e., the number of actual arguments must
be the same as the number of formal arguments and each argument must be of the
same data type as its corresponding formal argument.
·
Arguments are the
variables within the function.
·
The arguments can be
either passed by value or by reference.
·
During argument passed
by value, the numbers are explicitly defined.
·
The references take the
values through the variables.
…………………………………………………………………………………………………………………………………………..
Function Definition
Function Definition
The body of the function begins just like in the same
fashion as the main () function. The body of the function contains various
statements, calculation modules, logic to determine different values and
processing and return value. The return value is the type of value that should
have been declared in the function declaration part. The general concept of a
function definition is given below.
Parameter declaration
{ Body of function; Return expression; } |
Note:
·
Generally, the function
is defined before mains ().
·
The function is
generally called from the main ().
·
The function defined
before main follows a semicolon.
·
The function definition
contains function body and calculation section.
While defining a function, one has to remember the
followings.
·
Contains the actual
codes for the program.
·
The body of the function
follows function declaration.
·
Function declaration and
a name of the function definition should be same with the same arguments and
same return data type.
·
Function declaration
terminates with the semicolon (;).
·
Function definition
terminates without semicolon (;).
Example:
void main () { /* function definition*/ Program codes; } |
Function Prototype
The
functionprototype is the outline of a general function. The prototype given
below illustrates the different parts of a function.
#include <stdio.h> ......... .......... /* function declaration or prototype void function1 (); void function2 (); .......... ......... main () { ............. ........... /* calling function */ function1 (); function2 (); ............ ........... } /* function definition */ function (parameters) { ...................; body of the function; .....................; } |
# Write a program to find the sum of two numbers with a function sum ().
#include <stdio.h> #include <conio.h> void sum (); void main (); { printf(“/n Example of calling sum (); /* function is called */ printf(“/n return from function”); } /* function defition */ void sum () { int a, b, t; printf(“\n print first number:”); scanf(“%d”, &a); printf(“\n print second number:”); scanf(“%d, &b); t=a+b; printf(“\n Sum of the two is %d”, } |
Functions handle the variables. The variables within the
function itself are local to the function. A variable explicitly declared
outside the function (outside main () also) is known as the global variable.
Global variables are accessed by all the functions in the program. The use of
global variable are with the help of scope resolution operator.(::) which is
beyond this text.
Illustration of global variable the above program is changed to accept a
global variable.
#include <stdio.h> #include <math.h> Float t; Void sum (); Void main () { Printf(“\n Example of calling Sum; /* fucntion is called */ Printf(“\n Sum of the two is %4.2f”, Printf(“\n return from function”); } /* function defition */ Void sum () { Int a,b; Printf(“\n Print first number:”); Scanf(“%d”, &a); Printf(“\n Print second number:”); Scanf(“%d”, &b); t=a+b; } |
Function argument passed by value
#include <stdio.h> #include <conio.h> #include <math.h> sum (int,int); main () { printf(“\n Example of calling sum (15, 10); printf(“\n Return from the return 0; getch (); } sum (int a, int b) { int t; t=a+b; printf(“\n Value of A = %d”,a); printf(“\n Value of B =%d”, b); printf(“\n sum of %d and %d is } |
Parameter passed by value
#include <stdio.h> #include <math.h>\ sum (int, int); main() { int tot; printf(“\n Example of calling tot=sum (10, 15); printf(“\n Return from function\n”); printf(“\n The sum is %d”, tot); return0; } /*function definition */ sum (int a, int b) { int t; printf(“\n Value of a =%d\n”, a); printf(“\n value of b =%d\n”, b); t=a+b; return (t); } |
Function call with parameter passing by value.
#include <math.h> #include <conio.h> void change (int, int); void main () { int a = 15, b = 10; clrscr (); printf(“\n Before calling printf(“\n Value of a = %d”, a); printf(“\n Value of b = %d\n\n”, b); printf(“\n After calling function”); change (a, b); printf(“\n After returning from printf(“\n Value of A = %d”, a); printf(“\n Value of b = %d, b); } /* function definition */ void change (int a, int b) { int t; t=a; a=b; b=t; printf(“\n Value of a = %d”, a); printf(“\n Value of b = %d\n\n”, b); } |
Parameter passing by reference
#include <stdio.h> #include <math.h> #include <conio.h> void change (int &, int &); /* main() { int a=15, b=10; clrscr (); printf(“\n Before calling funtion printf(“\n value of A = %d”, a); printf(“\n value of B = %d\n\n”, b); printf(“\n After function is change (a,b); /* function called by printf(\n After returning from printf(\n Value of A = %d, a); printf(“\n Value of B = %d”, b); } /* function definition */ void change (int &a, int &b) { int t; t=a; a=b; b=t; printf(“\n Value of A = %d”,a); printf(“\n Value of b = %d\n”, b);\ } |
Interchanging the input values in the program using function. Here, the
function is preceded by the main () function.
#include <stdio.h> /* interchanging the value */ void swap (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void main () { int i, j; printf(“\n Enter first number:”); scanf(“%d”, &i); srintf(“\n Enter second number:”); scanf(“%d”, &j); printf(“\n Before swapping %d %d swap (&i, &j); printf(&i, &j); printf(“\n After swapping %d %d”, i, } |
Function That Returns a Value
A function with a return value produces a value and
returns it to the statement within the function that call it. Function with
return values requires that a return statement is used so that the value is
returned to the calling statement.
C does not place any restriction on the type of return
values except that the value cannot form an array. Hence array cannot be the
return type. A pointer to an array can be returned. But a function can return
an array that is a part of a structure.
# Write a program to find the factorial of a number with the help of a
function fact (unsigned int).
#include <stdio.h> #include <conio.h> long fact (unsigned int); /* void main (void) { unsigned int Num; long factorial; printf(“\n Enter a positive scanf(“%u”, &Num); factorial = fact (Num); printf(“\n The factorial of %u is } long fact (unsigned int n) { long fact (unsigned int n) { long 1fact; int i; if (n==0) 1fact = 1; /* Factorial of 0 is 1 */ else { 1fact = 1; for (i=2; i<=n;i++) 1fact = 1fact *i; } return 1fact; } |
# Write a program to check whether a given word is palindrome by using
function.
#include <stdio.h> #include <string.h> #include <ctype.h> enum Boolean{ false, true}; enum Boolean IsPalindrome (char { int left, right, len=strlen enum boolean matched = true; if (len == 0) return true; left = 0; right = len-1; /* compare the first and last while (left <right && { if (string [left] != string[right]) matched =false; else { left++; right--; } } return matched; int main (void) { char string [40]; printf(“\n Program to test the given printf(“\n Enter a string:”); scanf(“%s”, string); if (ispalindrome (string) printf(“\n The given string %s is a else printf(“\n The given string %s is return 0; } Array INTRODUCTION It is true that many applications Each array element or individual It is true that strings characters Define An Array can be defined as the Int age [15]; This definition is one-dimensional int is data type of the array, age is the name of the array and [15] is the maximum number of Accessing For accessing a particular element Note: · · · · Initialization One dimensional array is the int number [10] ={1, 2, 3, 4, 5, 6, Here, int is the data type of the array the number is the name of the array [10] indicates the maximum number of {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; are Then, number [1] = 1 number [2] = 2 number [3] = 3 etc. If a program requires a 1. 2. Accessing While accessing one-dimensional &arrayname [expression]; The expression is the position at # Write a program to read an print
In the above program, int a [10] Array Int a[5] ={2, 4, 6, 8, 10};
Example of an array initialization
# Write a program to read the static
In the above program, the array # Write a program to accept 10
In this program, the definition int # Write a program to accept ages of
# Write a program to sort the given
# Write a program to initialize 10
……………………………………………………………………………………………………………………………………………………………… Two Dimensional In the mathematics, we sometimes The rows are thought of as numbered The row subscript is always written The two-dimensional array declared Int a[3] [4]; Just as with the one-dimensional If you are declaring the Int a[3] [4] [5]; The total number of elements in this Two-dimensional int values [3] [4] = The first number within the square Int values [3] [4]; { {1,2,3}; {5,6,7,8}; {9,10,11,12}; }; Accessing While inputting and accessing the &arrayname[ expression1] Here, &arrayname is the name of the [expression1] is the row position [expression2] is the column position # Write a program to sort numbers in
# Write a program to sort array
# Write a program to insert an
# Write a program to define a two
# Write a program to demonstrate
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, Array The array can be passed as arguments a[0], a[1],………..a[n] Two parameters are required an array int sum(int a[], int n) The parameter declaration for the # Write a program to demonstrate the
Using The base address of array elements Passing array elements with an · · Array A pointer is a variable that can # Write a program to pass array of
# Write a program to find the
Arrays A string is the sequence of It is true that some characters C compilers include library # Write a program to accept a
# Write a program to convert
# Write a program to accept a
# Write a program to print the first
After running this program, you will The format specifier %s accepts a # Write a program to enter name of 5
In the above program, the line char # Write a program to sort the given
…………………………………………………………………………………………………………………………………………………. String Generally, the early programmers · This function is used to measure the Syntax : # Write a program to reverse a
· This function is used to reverse the Syntax: # Write a program to demonstrate the
· The strlwr() function converts the Syntax: # Write a program to test the
· The strcpy() function is used to Syntax: Demonstrate strcpy() function
In the above program, the content of · This function is generally used to Syntax: # Write a program to right
· The strcmp function compares two Syntax: # Write a program to compare two
# Write a program to input various
# Write a program to count number of
…………………………………………………………………………………………………………………………………………………………… Dereferencing INTRODUCTION A pointer variable points to the address 1. A pointer variable is dereferenced Void The programmer should note that a Pointer It is true that the size of the data The C language allows arithmetic Valid 1. 2. 3. 4. Invalid Pointer 1. 2. 3. 4. Pointers A pointer is a variable. It is a The general format of pointing to <data_type> ** Here, data_type is the type of pointer **indicates pointer to pointer Ptr_to_ptr is the variable name of Pointers When we declare an array, the array # Write a program to find the
Above program holds a set of array Facts regarding 1. 2. 3. Passing At the time of manipulating arrays # Write a program to demonstrate
The function sortit actually sorts Write a program to find the smallest
Pointer The pointers can be used to locate 1. 2. 3. Example:
Array of An array of pointers is similar to Example:
Pointers As in integer array, in character # Write a program to find the
Pointers A pointer is a variable that represents the Uses 1. They are used to pass information back and 2. They provide a way to return multiple date 3. They provide alternate way to access When we declare a variable say x, the computer Ex: if x=3 and px=&x then *px=3 Declaration and Initialisation A pointer variable is to be declared initially. Data type *pointer variable Int *p declares the variable p as pointer The value stored in q is got by *p. If y is a pointer variable to x which is of Ex: float a; float *b; b=&a; Note : here in ‘b’ address of ‘a’ is stored and Passing pointers to a function Pointers are also passed to function like Ex: ): #include void f(int*px, int *py main() { int x = 1; int y=2; f(&X,&y); printf(“\n %d%d”, x,y); } Void f(int *px, int *py); *px=*px+1; *py=*py+2; return;} Note: 1. here the values of x and y are increased by 2. arithmetic operations *, +, -, / etc can be Passing function to other function A pointer to a function can be passed to Pointer and one dimensional arrays An array name is really a pointer to the first int x[100],n; for (i=1 ; i<=n; ++i) scanf (‘%d”, x + i ) (in the place of scanf Note : the values stored in the array are got Dynamic memory allocation Usually when we use an array in c program, its Ex; to assign sufficient memory for x we use the x= (int *) malloc (n* sizeof (int) ) , for in Similarly in the place of float y [100] we use Example to read n numbers and find their sun main() { int *x, n, i, sum=0; printf(“\n Enter number of numbers”); scanf(“%d”, &n); x=(int *)malloc(n * sizeof(int)); for(i=1;i<=n,++i) { scanf(“%d”, x+i): sum += *(x+i); } Printf(“\nThe sum is %d ”, sum); } Structures and Unions We know an array is used to store a collection Defining a structure. In general it is defined with the syntax name Struct structure_name { Data type variable1; Data type variable2; … } For example : 1. Struct { int account no. char name[50]; float balance; }customer[20] Note :1 here account no., name and balance are 2. struct { int month; int day; int year; }dateofbirth; In these examples customer is a structure array For example struct date { int day; int month; int year; } Struct biodata { name char[30]; int age ; date birthdate; }staff[30]; Here staff is an array of structure of type Note: we can declare other variables also of Struct biodata customer[20]; , Struct biodata Processing a structure The members of a structure are themselves not If staff[] is structure array then the details staff[1].name, staff[1].age, staff[1].birthdate.year . we can assign name, staff[1].age=26 staff[1].birthdate.day=11 staff[1].birthdate.month=6 staff[1].birthdate.year=1980 If ‘employee’ is a structure variable of type biodata employee; The details of employee are got by Structure initialisation Like any other variable or array a structure Struct record { char name[30]; int age; int weight; } Static struct record student1={“rajan”, 18, 62} Here student1 is of record structure and the 1.Write a c program to read biodata of students Solution #include main() { Struct biodata { Char name[30]; Char Place[40]; Int pin; Long Int phone; Char grade; }; Struct biodata student[50]; Int n; Prinf(“\n no of students”); Scanf(“%d”,n); For(i=1;i<=n;++i) { Scanf(“%s”,student[i].name); Scanf(“%s”,student[i].place); Scanf(“%d”,student[i].pin); Scanf(“%ld”,student[i].phone); Scanf(“%c”,student[i].grade); } } User Defiined Data Type This is to define new data type equivalent to typedef type new-type. Here type refers to existing data type For example Ex1: Typedef int integer; Now integer is a new type and using this type Integer x; Integer mark[100]; Ex2: Typedef struct { Int accno; Char name[30]; Float balance; }record; Now record is structure type using this type Record customer; Record staff[100]; Passing structures to functions Mainly there are two methods by which 1 Transfer structure members individually 2 Passing structures as pointers (ie by Example 1 #include Typedef struct { Int accno; Char name[30]; Float balance; }record; Main() { ….. Record customer; . . . . . Customer.balance=adjust(customer.name,customer.accno,balance) . . . . . } Float adjust(char name[], int accnumber, float { Float x; . . . . . X= . . . . . Return(x); } Example 2 #include Typedef struct { Int accno; Char name[30]; Float balance; }record; Main() { Record customer; Void adjust(record *cust) . . . . . . Adjust(&customer); Printf(“\n } Void adjust(record *cust) { Float x; . . . . Cust->balance=… . . . . Return; } In the first example structure members are Unions Union is a concept similar to a structure with Union var { Int m; Char c; Float a; } Union var x; Now x is a union containing three members FILE HANDLING (Data Data Files are to store data on the memory 1 Stream Oriented data files 2 System Oriented data files Stream oriented data files are either text Opening and Closing data files The first step is to create a buffer area where File *fp; Here fp is the pointer variable to indicate the The syntax is fp=fopen(filename,filetype) the filetype can be 1.‘r’ ( to open an existing file for reading 2.‘w’ ( to open a new file for writing only. If 3.‘a’ ( to open an existing file for appending. 4.‘r+’ ( to open an existing file for both 5.‘w+’ ( to open a new file for reading and 6.6 ‘a+’ ( to open an existing file for reading For writing formatted data to a file we use the Fprintf(fp,”conversion string”, value); For example to write the name “rajan” to the File *fp; Fp=fopen(“st.dat”,’w’); Fprintf(fp,”%[^\n]”,”rajan”); The last step is to close the file after the fclose(fp); Example 1 To create a file of biodata of students with #include #include Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; biodata student; fp=fopen(“st.dat”,’w’); Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place); Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day); Scanf(“%d”,&student.birthdate.month); Scanf(“%d”,&student.birthdate.year); Fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.age,student.birthdate.day, Fclose(fp); } Example 2: To write a set of numbers to a file. #include main() { file *fp; Int n; float x fp=fopen(“num.dat”,’w’); Printf(“Input the number of numbers”); Scanf(“%d”,&n); For(i=1;i<=n;++i) { Scanf(“%d”,&x); Fprintf(fp,”%f\n”,x); } Fclose(fp); } Processing formatted data File To read formatted data from a file we have to file *fp; fp=fopen(“st.dat”, ‘r+’); For reading formatted data from a file we use Example: Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; biodata student; fp=fopen(“st.dat”,’r+’); fscanf(fp,”%s”,student.name); printf(“%s”,student.name); fclose(fp); } Processing Unformatted data files For reading and writing unformatted data to The syntax for writing data to file ‘st.dat’ Fwrite(&student, sizeof(record),1,fp); Here student is the structure of type biodata Example: To write biodata to a file Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; fp=fopen(“st.dat”,’a+’); biodata student; Printf(“Input data”); Scanf(“%[^\n]”,student.name); Scanf(“%[^\n]”,student.place); Scanf(“%d”,&student.age); Scanf(“%d”,&student.birthdate.day); Scanf(“%d”,&student.birthdate.month): Scanf(“%d”,&student.birthdate.year); Fwrite(&student,sizeof(record),1,fp); Fclose(fp); } Example 2: To read biodata from the file. Tpedef struct { Int day; Int month; Int year; }date; Typedef Struct { char name(30); char place(30); int age; date birthdate; }biodata; Main() { File *fp; fp=fopen(“st.dat”,’a+’) biodata student; fread(&student,sizeof(record),1,fp); printf(“%s\n”,student.name); printf(“%s\n]”,student.place); printf(“%d\n”,&student.age); printf(“%d\n”,&student.birthdate.day); printf(“%d\n”,&student.birthdate.month): printf(“%d\n”,&student.birthdate.year); fclose(fp); } Some problems and solutions of C: 1.WAP to input an integer and check whether Ans: #include #include void main() { int a; printf(“Enter a value for a: ”); scanf(“%d”,&a); if(a>=51) { printf(“%d is greater than 50”,a); } else { printf(“%d is less than or equal to 50”,a); } getch() } 2.WAP for finding factorial of a given number Ans: #include #include void main() { clrscr(); int number; long int factorial=1; printf(“\nEnter the number:”); scanf(“%d,&number); while (number>1) { factorial=factorial * number –; printf(“\nThe factorial is %d”, factorial); } getch(); } Output: Enter the number =4 The factorial is 24 3.WAP in C to input any five number in an Ans: #include #include void main() { clrscr(); int a[5],ar,s=0,i,j; printf(“Enter any five number”); for (i=0;i50) { printf(“Good”); else printf(“Bad”); } Output: Enter any five numbers 1 4 10 15 25 Bad Discussion: In this program first five numbers is asked to 4.WAP in C to accept a string and check if the Ans: #include #include #include void main() { clrscr(); char a[20],b[20]; puts(“Enter a string”); gets(a); strcpy(b,a); strrev(a); if (strcmp(a,b)=0) printf(“The entered string is palindrome”); else printf(“The entered string is not palindrome”); getch(); } Output: Enter a string pen The entered string is not palindrome. Enter a string: dad The entered string is palindrome. |
0 Reviews