0% found this document useful (0 votes)
3 views

C-Programming-Notes (1)

The document provides an overview of C programming, including important points such as the use of specific software for coding, the structure of a C program, and the characteristics, advantages, and disadvantages of the C language. It details the development stages of a C program, rules for writing code, and the elements of a C program, including data types, variables, constants, and preprocessor directives. Additionally, it covers keywords, identifiers, and format specifiers used in C programming.

Uploaded by

anoopagrahari022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C-Programming-Notes (1)

The document provides an overview of C programming, including important points such as the use of specific software for coding, the structure of a C program, and the characteristics, advantages, and disadvantages of the C language. It details the development stages of a C program, rules for writing code, and the elements of a C program, including data types, variables, constants, and preprocessor directives. Additionally, it covers keywords, identifiers, and format specifiers used in C programming.

Uploaded by

anoopagrahari022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C Programming

Important points to remember


1. To do programming in C, "Dev C++, Turbo C, etc." software are used.
2. We cannot use 'Notepad' for coding the C program because it is not compiler based
program/software.
3. When we save the program in C, we should type extension '.c ' with filename.
4. To run / execute the program, we should click on Execute >> Run (F10) or Compile and Run (F11).

Short notes on C Language:


C language is one of the most powerful language. This language is easy to understand and have
high speed, so it is also termed as Middle Level Language or Intermediate Language. This type of language
is used to prepare system software as well as application software. It is a kind of general purposed,
structured programming language. It is sometimes called modular programming.
C language has been designed and developed by Dennis Ritchie at Bell Laboratories in 1972. It is
an offspring (version) of the "Basic Combined Programming Language" called 'B' developed in the year
1960 at Cambridge University. C language is associated (related) with UNIX operating system i.e. the
source code for the UNIX OS is coded in C. C programs are efficient, fast and highly portable programming
language. It is relatively small and requires less memory than other languages. C is independent language,
it supports the program written in any computer with little or no modification.
The C language is so named because its predecessor was called B. The B language was developed
by Ken Thompson of Bell Laboratories. The development of UNIX in C language made it uniquely
portable, improvable and flexible. The C language was formalized in 1989 by the American National
Standard Institute (ANSI). So the ANSI C has become the recognized standard for C language.

Characteristics / Features
1. It is a structured (modular) programming language. So any large programs can be erased easily.
2. It is small size and requires less memory than other languages programs.
3. It is platform independent language.
4. It is procedural programming language because the program is divided into number of functions.
5. It is general purpose structured programming language.
6. It is internationally standardized programming language.
7. It inherits or invisible functionality (memory management, CPU-register manipulation, etc.)

Advantages
1. It is easy for debugging, testing and maintaining.
2. It is portable programming language.
3. It is fast for executing.
4. It is compact programming language. The statement in C language are generally short but very
powerful.
5. It is simple / easy. It supports both HLL and LLL.
6. It has only 32 keywords so that easy to remember.
7. Its compiler is easily available.
8. It has ability to extend itself. Users can add their own functions to the C Library.
9. It can use to design middle type of software.

Disadvantages
1. There is no runtime checking.
2. There is no strict type checking. (Example: We can pass an integer value for the floating data type)
[Note: Floating point: a) Single precision (!) = Number with decimal value up to 7 digits.
b) Double precision (#) = Number with decimal value up to 15 digits.
3. As the program extends it is very difficult to fix the bugs.
4. It may be compile time overhead due to the misplacing and excessive use of pointers.
5. It does not use to develop complex type of software now-a-day.

Development stages of C program


1. Editing / writing program code
2. Pre-processing and compiling
3. Linking
4. Executing

Rules for writing code in C


1. Generally C statements are written in small letters.
2. There must be semi-colon (;) at the end of each C statement.
3. The execution of C program must start from main ( ) function so there must be at least one main
function.
4. In the program, a set of statement must be in between the start '{' and end '}' brackets.

C program layout
C program consists of two sections.
1. Pre-processor directives
2. Main function

Example:
#include<stdio.h> Pre-processor directives

int main()
{
printf("Hello World");
Main function
return 0;

Structure of C program
1. Header files 4. Declaration part 7. Comments
2. Global declaration 5. Executable part 8. Function header
3. Main() 6. User defined functions
 Comment line: It indicates the purpose of the program. It is represented as:
For single line comment: // comment
For multi-line comment: /* comments */
Comment line is used for increasing the readability of the program. It is enclosed within the
decimeters. Comment line can be single or multiple line but should not be nested.

 Pre-processor Directives: #include<stdio.h> tells the compiler to include information about the
standard input/output library. It is also used in symbolic constant such as #define PI 3.14 (value).
The stdio.h (Standard Input Output header file) contains definition and declaration of system
defined function such as printf(), scanf(), pow(), etc. Generally, printf() function is used to display
and scanf() function is used to read value.

 Global Declaration: This is the section where variable are declared globally so that it can be access
by all the functions used in the program. And it is generally declared outside the function:

 main() : It is the user defined function and every function has one main() function from
where actually program is started and it is encloses within the pair of curly braces. The
main() function can be anywhere in the program but in general practice it is placed in the
first position. The main() function return value when it declared by data type as:
int main()
{
return 0
}
The main() function does not return any value when void (means null / empty) as void
main(void) or
void main()
{ Output: C Language
printf("C Language");
}
The program execution start with opening brace and end with closing brace.

 Declaration Part and Executable Part: These both parts lies in between the two braces. And at the
end of each line, the semi-colon is given which indicates statement termination.

[Note: 1) Syntactic Error: The error that arises in an expression due to unbalanced parenthesis are
called syntactic error.
2) Semantic Error: The error that arises due to the use of undefined variable are called semantic
error.
3) Building: The process of compiling and linking a program is often called building.]

Header Files: Header files are standard files that are compulsory in C program and contains the
function definition of library functions.
(i) #include<stdio.h>: It is standard input output header file. It contains the function definition
of input output functions such as scanf(), printf(), etc.
(ii) #include<conio.h>: conio stands for CONsole Input Output header file. It is a header file
which is included in the program this is used to use, clrscr(), getch(), etc. We do not need
to include this file in C program. It is necessary for C++ programs.
(iii) #include<math.h>: This header file is used for mathematical functions such as pow(), sqrt(),
sin(), tan(), cos(), etc.
(iv) #include<graphics.h>: It is graphic header file. It contains the function definition of graphic
processing functions such as line(), circle(), rectangle(), etc.
(v) #include<string.h>: It is string header file. It contains the function definition of string
processing functions such as strlen(), strcat(), strcpy(), etc.
Elements of C Program

1. #include<stdio.h>: At the first line of the program you can see the #include<stdio.h>. It is called
the pre-processor directive or pre-processor instruction. This instruction must include at the
starting of the every C program. It instructs the C compiler to include information from the
standard input/output (stdio.h) library header file.
2. int main(): Below the pre-processor instruction, there is int main(). It is a function or sub-program.
There may use number of functions in a C program but there must be included at least one main()
function. Execution of any C program starts from the main() function. It is not possible to execute
any C program without main() function.
The int before main() specifies the function declaration is integer data type and its return type is
integer value. That means it can return an integer value.
The ( ) parenthesis that follow the function name may contain list of values to be used by that
function is called parameters or arguments. If main(void) is given as a parameter which refers that
it does not take any arguments.

{
…………………….
…………………….
}
The curly braces { } contains the program statements to be executed whenever the function is
called. Each statement must be terminated by a semi-colon (;). The '{' open curly brace represents
the beginning of the function body and the '}' close curly brace represents its termination.

3. printf() : It is C library function that instructs the computer to display characters or a string
enclosed by the quotation marks on the monitor screen. Items enclosed by the parenthesis are
called arguments.
4. return 0 : At the end of function main(), we have to include 'return 0' statement because function
main is defined to return a value of integer type. The return 0; statement returns a value from main
to the operating system.

C Preprocessor
Preprocessor is a program that processes the code before it passes through the compiler. It operates under
the control of preprocessor command lines and directives. Preprocessor directives are placed in the source
program before the main line before the source code passes through the compiler it is examined by the
preprocessor for any preprocessor directives.
Preprocessor directives follow the special syntax rules and begin with the symbol # and do not require
any semicolon (;) at the end. A set of commonly used preprocessor directives are listed below:
Directives Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies a file to be included
#ifdef Tests for macro definition
#else Specifies alternatives when # if tests fails

Fundamentals of C
 Character Set : Character sets are the letters, digits and special characters and white spaces that
form words, numbers and expressions.
Character-set
a) Letters : A – Z, a – z
b) Digits: 0 – 9
c) Special characters: , . ; : ? ' " ! / \ $ %, etc
d) White spaces: Blank space, Horizontal space, Carriage Return, New Line, Form feed

Comments: It is not compulsory in C program but it makes easy to study the programs. Comments
can be written in two forms:
(i) // single line comments
(ii) /*multi-line comments*/

Tokens: Tokens are fundamental parts of C program from which other parts are formed. C programs
are written using tokens. There are six types of C tokens that are given below:
(i) Operators
(ii) Keywords
(iii) Identifiers
(iv) Constants
(v) Strings
(vi) Special symbols

 Keywords / Reserved Words: Keywords are those special words that are pre-defined in C
programming language. These keywords cannot be used as identifiers (variables) in the program.
Here is the list of keywords used in Standard C.

auto double int struct break else long


switch case enum register typedef char extern
return union const float short unsigned continue
for signed void default goto sizeof volatile
do if static while

Identifiers : Identifiers are the names given to program unit such as variable, structure, function,
etc. They are not defined in programming language but are used to define by the programmer.
Some basic rules to define identifiers are given below:
(i) First character must be an alphabet underscore then digits or alphabets.
(ii) It must consist of only letters, digits and underscore.
(iii) Any standard C language keyword cannot be used as identifier name.
(iv) It should not contain a space.
(v) It allows both uppercase and lowercase characters.

Data types in C: Data types are classified into two categories:


(i) Primary data types : Character, Integer, Float, Double, Void
(ii) Secondary data types : Array, Pointer, Structure, Union, Enum, etc
Variable type Keyword
Character char
Integer int
Short Integer short int
Long integer long int
Float float
int : It stores the integer value. It means it does not calculates decimal values. Example: 1, 2, 3, -
100, 10000, 5+5.5=10.
float : It stores decimal values too and calculates. Example: 1.5 + 5.2 = 6.7
char : It stores characters or string. Example: A-Z, a-z, symbols like @,#,$,%,etc.

User defined type declaration: C language supports a feature where user can define an identifier
that characterizes an existing data type.
Syntax: typedef <type> <identifier>
Example: typedef int number;

Type Format Specifier: The format specifiers are used in C for input and output purposes. Using
this concept, the compiler can understand that what type of data is in a variable during taking
input using the scanf() function and printing using printf() function. Here is a list of format
specifiers.
Format specifier Type
%c Character
%d Signed integer
%f Float values
%s String
%l or %ld or %li Long integer
%lf Double integer
%Lf Long double integer

 Variables: It is a name of the memory location used to store a data value. It is a value that can
change any time.
Example: int a,b,c;
int a=3, b=4, c=5;
char d, e;
Here, a, b, c are integer variable and d, e are character type variable.
Rules for using variables:
a) They must always begin with a letter, alphabet or character.
b) The length of a variable must not be more than 8 characters.
c) White space is not allowed.
d) A variable should not be a keyword.
e) It should not contain any special characters.

Some invalid variables: 123, (area), 6th, %abc, etc.


Some valid variables: sum, number, salary, emp_name, average1, etc.
Types of variables:
a) Numeric variable: The variables that store numeric type of data only is called numeric variable.
Example: age, roll_no, ward, etc.
b) String variable: The variables that store string or alphanumeric type of data are called string
variable. Example: 'a', 'g', "College", "125xy", etc.

 Constant: Those data values which does not change during program execution.
Example: radius = 3.14 is a constant
#define pi 3.1415
#define length 5.5
There are several types of constants:
a) Integer constant: It consists of a set of digits 0 to 9 preceded by an optional + or – sign.
Examples: 123, -21, 0, 5632, +78, etc.
b) Floating point constant: It is a number that can be written either in decimal form or an
exponent form or both. It must have at least one digit before decimal point and at least
one digit after the decimal. Examples: 7.0, 17.6, -14.5, 0.8, etc.
c) Single Character constant: It stores only single character. It is enclosed by single
quotation mark. Examples: 'A', 'B', 'h', '2', '5', etc.
d) String constant: It is a set of characters enclosed in double quotation marks which may
include alphabet, number, special character and blank space. Examples: "bibek", "123",
"Good Bye", "!......?", etc.

Difference between variable and constant:


Variable Constant
It is a name whose value can be changed It is a value which cannot be changed during
during program execution. program execution.
Its purpose is to allocate memory space inside Its purpose is to allocate memory space inside
computer's memory. computer's memory and assign value in it.
Example: int a; Example: int a=5;
float b; float b=10.9;
Syntax: datatype variablename; Syntax: data type constantname=value;

Escape sequences: The non-printing characters started with slash (\) are called escape sequences.
They are special characters used in output functions.

Escape Sequence Meaning


\a Audible alert (Bell)
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quote
\" Double quote
\? Question mark

 Statements: It causes the computer to carry out some action.


Types of statements:
1) Simple statement: Simple statements are those statements which are ended with semicolon and
ready to perform some action.
Example: a=33; c=a+b;
printf ("Sum=%d",sum);

2) Compound statement: A compound statement consists of several individual statements enclosed


within a pair of braces { }. There should not be semicolon at the end of compound statement.
Example:
{
pie=3.141593;
circumference = 2*pie*radius;
area = pie*radius*radius;
}

3) Control Statement: They are used to create special program feature such as logical tests, loops
and branches.
Example: for (c=1; c<=10; c++)

 Operators: An operator is a symbol which helps to do a certain mathematical or logical operations


such as +, -, *, /, etc.
Types of operators:
a) Arithmetic operators (Binary operator)
b) Relational operators (Comparison operator)
c) Logical operators (Boolean operator)
d) Assignment operators
e) Unary operators (Increment/decrement operator)
f) Conditional operators (Ternary operator)
g) Bitwise operators
h) Special operators

a) Arithmetic operators (Binary operator): Those operators that performs simple arithmetic
calculations such as addition, subtraction, multiplication, division, modulus, etc. It uses two
operands so that it is called binary operator.
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b

b) Relational operators: Those operators that compares the relationship between operands and bring
out a decision and program accordingly.
Operator Meaning Example
< is less than a<b
<= is less than or equal to a<=b
> is greater than a>b
>= is greater than or equal to a>=b
== is equal to a= =b
!= is not equal to a!=b

c) Logical operators: Those operators that are used to give logical value either true or false.
Operator Meaning Example
&& Logical AND (a>b)&&(a>c)
|| Logical OR (a>b) || (a>c)
! Logical NOT !(a= = b)
d) Assignment operators: Those operators that are used to assign the value of expression into variable.
The most commonly used assignment operator is '='. It is written in the form of:
variable = expression
Example: x = a+b
where, x is a variable and a+b is an expression. Here the value of a+b is evaluated and substituted to
the variable x .

Shorthand operators: It is a combination of arithmetic operators and assignment operators so that it


can perform the task of arithmetic operation and assignment operation. It is written in the form of:
var oper = expression;
Here, var is a variable, oper is a C binary arithmetic operator. The operator oper = is known as
shorthand assignment operator.

Shorthand Assignment

Operators Simple assignment Shorthand operator


operator
+= a=a+1 a+=1
-= a=a-1 a-=1
*= a=a*1 a*=1
/= a=a/2 a/=2
%= a=a%b a%=b

e) Unary (monadic) operators: A class of operators that act upon a single operand to produce a new
value, which is called unary operator. It is mostly used in loops.
There are two types of unary operators:
(i) Increment operator:
++variable name (prefix):
Example: m = 5;
y = ++m;
In this case, the value of y and m would be 6 because a prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left.

variable name ++ (postfix):


Example: m = 5;
y = m++;
In this case, the value of y will be 5 and that of m will be 6 because a postfix operator first
assigns the value to the variable on the left and then increments the operand.

(ii) Decrement operator:


- - variable name (prefix):
Example: m = 5;
y = --m;
In this case, the value of y and m would be 4 because a prefix operator first subtract 1 to the
operand and then the result is assigned to the variable on the left.

variable name - - (postfix):


Example: m = 5;
y = m--;
In this case, the value of y will be 5 and that of m will be 4 because a postfix operator first
assigns the value to the variable on the left and then decrements the operand.

f) Conditional (Ternary) operators: An expression that makes use of the conditional operator (?) and
(:) is called conditional operator. It can be written in the form:
expression1 ? expression 2 : expression 3
Example: a = 10;
b = 15;
c = (a>b) ? a:b
Here, expression 1 (a>b) is evaluated first. If expression 1 gets true then the value of c will be the
value of a, otherwise the value of c will be the value of b. In this example, the value of b is assigned
to c.

g) Bitwise operators: Those operators which supports special operators for manipulation of data at bit
level is called bitwise operators. It operates on each bit of data. It may not be applied to a float or
double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive
<< Shift left
>> Shift right

h) Special Operators: C supports some special operators of interest such as comma, size of operator,
pointer operator (& and *) and member selection operators (. and ->).
i) Size of operator: The operator 'size of ' gives the size of the data type or variable in terms of bytes
occupied in the memory.
Example: m = size of (sum);
n = size of (long int);

 Expression: An expression is a combination of variables, constants and operators written according


to the syntax of C language.
Algebraic Expression C Expression
ab+b(c+d) a*b+b*(c+d)
(x+y)(x-y) (x+y)*(x-y)
3x+5 3*x+5
x +y
4 3
x*x*x*x+y*y*y or pow(x,4)+pow(y,3)
x (x+1)
3
x*x*x*(x+1) or pow(x,3)*(x+1)

Type Casting and Conversion


Type casting is the process to convert a variable from one data type to another data type. For
example, if we want to store a integer value in a float variable then we need to typecast integer
into float.
Types of data conversion:
a) Implicit type conversion: The automatic conversion of any intermediate values to the proper
type so that the expression can be evaluated without losing any significance is called implicit
type conversion.
Example: float a;
int b,c;
b = 3, c = 2;
a = b/c;
printf("%f ",a);

Output: 1.000000
b and c are integer, and division is also integer, but final value is converted to float because a
is float.

b) Explicit type conversion: If we want to convert any type of single variable or mixed variable
into another type then it is known as explicit type conversion.
Example: float x;
int num1, num2;
num1=10, num2=3;
x= (float)num1/(float)num2; /* num1 and num2 are converted into float */
printf ("%f",x); /* The result is 3.333333 */

Library Functions
The functions that are pre-defined in programming language are called library functions. Some library
functions are used for input/output operations, some are for string processing operations, and some are
for mathematical operation and so on. Each library function can perform specific task and return specific
value. Some library functions are printf( ), scanf( ), strlen( ), clrscr( ), getch( ), sqrt( ), etc.

Library function Meaning


abs(n) Returns the absolute value of n
exp(n) Raise to power
sqrt(n) Returns the square root of n
getchar( ) Enter the character from the standard input device
printf( ) Display data from standard output device
scanf( ) Enter data from standard input device
putchar( ) Display a character to standard output device
strupr( ) Convert letter to uppercase
strlwr( ) Convert letter to lowercase
pow(n1,n2) Return n1 raised to the n2 power
fmod(n1,n2) Return the remainder when n1 is divided by n2

Input / Output (I/O) Functions


Input functions or streams are used to read different type of data (such as numeric, string or character)
from the keyboard. We can use more than one type of input functions in the program.
scanf( ) : It is the input function of standard library. We need to include the 'stdio.h' header file to use
this function. This function reads the data from keyboard.
Syntax: scanf("list of format specifier",&listofvariables);
Example: scanf("%d %d",&a,&b);
Output function are used to display different type of data (such as numeric, string or character) and results
on the screen. We can use more than one type of output function in the program.
printf( ) : It is the output function of standard library. We need to include the 'stdio.h' header file to use
this function. This function displays any types of data from standard output device such as monitor.
Syntax: printf("list of format specifier and escape sequence",listofvariables);
Example: printf("%d\t %d\t",a,b);

Some other library functions are:


a) gets( ): It is a library function that can use to input string data from standard input device
Syntax: gets(string expression);

b) puts( ): It is a library function that can use to display data from standard output device.
Syntax: puts(string expression);

Example of gets( ) and puts( ):

#include<stdio.h>
#include<conio.h>
void main()
{
char a[10];
printf("Enter a string: ");
gets(a);
printf("The string entered is: ");
puts(a);
getch();
}

Control Structures
Control statements are those statements that help to jump from one part of the program to another. These
statements are mainly used to select statements, to repeat the statements number of times and to jump
from one part to other parts inside a program.
There are three types of control statements:

Control Statement

Selection statement Jumping statement Looping statement

conditional statement break statement for statement

switch statement continue statement while statement

goto statement do…while statement


1) Selection statement:
a) Conditional statement: A statement that is executed only when a certain condition within a
program has been met is called conditional expressions. It is used for mainly decision making.
Some conditional statements are:
(i) if….statement: It is used to control the flow of execution of statements. It is basically a
two-way decision statement.
Syntax: if(condition)
{
Block of statement;
}

(ii) if….else statement: In this statement, if the condition is satisfied(true), then the true
statements are executed otherwise the else statement(false) are executed.
Syntax: if(condition)
{
Block of statement 1;
}
else
{
Block of statement 2;
}

(iii) if…..else if statement (multi-way condition of if statement): It can be used to choose


one block of statements from many blocks of statements. The condition which is true
only its block of statements is executed and remaining are skipped.
Syntax: if(condition 1)
{
Block of statement 1;
}
else if(condition 2)
{
Block of statement 2;
}
…………………
…………………
else
{
Block of statement n;
}

(iv) Nested if statement: In nested if statement if the first, if condition is true the control
will enter inner if. If this is true the statement will execute otherwise control will come
out of the inner if and the else statement will be executed.
Syntax: if(condition)
{
if(condition 1)
{
Block of statement 1;
}
else
{
Block of statement 2;
}
else
{
block of statement n;
}

b) Switch case statement: It is alternative of nested if else. It is executed when there are many
choices and only one is to be executed.
Syntax: switch(expression)
{
case 1:
block of statement 1;
break;
case 2:
block of statement 2;
break;
…………
…………
case n:
block of statement n;
break;
default:
default-block of statement;
break;
}

2. Looping (Iteration): The process of repetition of the statement until the condition is satisfied.
Types of looping:
a) For loop
b) While loop
c) Do while loop

For loop: For loops are used when the number of iterations is known before entering the loop. It is also
known as counter-controlled loop.
a. setting a loop counter to an initial values
b. testing the loop counter to determine whether its value has reached the number of repetition
desired.
c. increasing, decreasing the values of loop counter each time the program statement within the
loop has been executed.
Syntax: for(initial value; final value; increment/decrement)
{
Block of statement;
}
a) While loop: It executes one or more statements while the given condition remains true. It is
useful when number of iterations is unknown. The while loop is an entry control (pre-test)
loop.
Syntax: while(expression)
{
Block of statement;
}

b) Do while loop: do…..while loops are useful where loop is to be executed at least once. In do
while loop condition comes after the body of loop. This loop executes one or more statements
while the given condition is true. It is an exit control (post-test) loop.
Syntax: do
{
Block of statement;
}
while(expression);

Nested for loop: A loop within a loop is called nested loop. In this the outer loop is used for counting rows
and the internal loop is used for counting columns. Any loop can be used as inner loop of another loop.
Syntax: for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
statement (s);
}
}

Examples:
1) #include<stdio.h> Output
#include<conio.h> 123
void main( ) 123
{
123
int i,j;
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}
2) #include<stdio.h> Output
#include<conio.h>
void main( ) 111
{ 222
int i,j; 333
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}

3) #include<stdio.h> Output
#include<conio.h>
void main( ) 1
{ 12
int i,j; 123
for(i=1; i<=3; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}

4) #include<stdio.h> Output
#include<conio.h>
void main( ) 1
{ 22
int i,j; 333
for(i=1; i<=3; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}
5) #include<stdio.h> Output
#include<conio.h>
void main( ) 54321
{ 5432
int i,j; 543
for(i=1; i<=5; i++) 54
{ 5
for(j=5; j>=i; j--)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}

6) #include<stdio.h> Output
#include<conio.h>
void main( ) 11111
{ 2222
int i,j; 333
for(i=1; i<=5; i++) 44
{ 5
for(j=5; j>=i; j--)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}

7) #include<stdio.h> Output
#include<conio.h>
void main( ) 55555
{ 5555
int i,j,a=5; 555
for(i=5; i<=1; i--) 55
{ 5
for(j=1; j<=i; j++)
{
printf(“%d”,a);
}
printf(“\n”);
}
getch( );
}
8) #include<stdio.h> Output
#include<conio.h>
void main( ) 5
{ 55
int i,j,a=5; 555
for(i=1; i<=5; i++) 5555
{ 55555
for(j=1; j<=i; j++)
{
printf(“%d”,a);
}
printf(“\n”);
}
getch( );
}

Infinite Loop: A loop is said to be infinite if it never terminates. To come out from loop we have to press
reset.
Loop Interruption:
1. break statement
Syntax: break;
statement;
Example:
#include<stdio.h>
#include<conio.h> Output
void main( )
0 1
int a;
for(a=0; a<5; a++)
{
if(a==2)
break;
printf(“%d”,a);
}
getch( );
}
2. continue statement
Syntax: continue;
statement;
Example:
#include<stdio.h> Output
#include<conio.h> 0 1 3 4
void main( )
int a;
for(a=0; a<5; a++)
{
if(a==2)
continue;
printf(“%d”,a);
}
getch( );
}

String Function
String is a collection of character or group of character which is enclosed within double quotation
symbol (“ ”). Strings are always enclosed within double quotes whereas character is enclosed
within single quotes (‘ ’) in C.

String manipulation function


C has several built (library) function, such as: strupr( ), strcat( ), strlwr( ), strrev( ), strlen( ),
strcmp( ), strcpy( ), etc for manipulating strings. To use these functions, “string.h” header file must
be included.

1. String length i.e. strlen( ): It returns the length of given string (including spaces).
Syntax: strlen(string);

2. String concatenation i.e. strcat( ): It is used to concatenate (join/combine/merge) two strings


resulting to a single string.
Syntax: strcat(string1, string2);

3. String copy i.e. strcpy( ): It is used to copy content of a string to another string. It takes two
arguments.
Syntax: strcpy(string1, string2);

4. String reverse i.e. strrev( ): It is used to reverse a string. It takes only one string and returns in
reverse order.
Syntax: strrev(string);

5. String uppercase i.e. strupr( ): It is used to convert the lowercase into uppercase. It takes only
one string.
Syntax: strupr(string);

6. String lowercase i.e. strlwr( ): It is used to convert the uppercase into lowercase. It takes only
one string.
Syntax: strlwr(string);

7. String compare i.e. strcmp( ): It is used to compare two string character by character. It accepts
two string as parameters and returns an integer whose value is:
< 0 if the first string is smaller than second string.
> 0 if the first string is greater than second string.
= = 0 < if the first string equal to second string.

Array
An array is a collection of similar data type that can hold value of a particular data type for which it has
been declared.
Types of array:
a) Single dimensional array: It has only one subscript / suffix. A subscript is a number in a bracket
that follows an arrays name.
Example: int n[1000];
Here, it means n[0], n[1], n[2], …….., n[999]

b) Multi-dimensional array: It is an array that can use to store similar types of data in a common
name. It consists of two subscript / suffix in which first gives number of row size and second
gives number of column size.
Example: int n[3][3];
Here, it means: n[0][0] n[0][1] n[0][2]
n[1][0] n[1][1] n[1][2]
n[2][0] n[2][1] n[2][2]

Examples:
1) WAP to input any 10 numbers and display.
Using single dimensional array
#include<stdio.h>
#include<conio.h>
void main( )
{
int n[10],i;
printf(“Enter 10 numbers: ”);
for(i=0; i<10; i++)
{
scanf(“%d”,&n[i]);
}
printf(“You entered\n”);
for(i=0; i<10; i++)
{
printf(“%d\n”,n[i]);
}
getch( );
}

Using multi-dimensional array


#include<stdio.h>
#include<conio.h>
void main( )
{
int n[10][10],i,j;
printf(“Enter number: ”);
for(i=0; i<10; i++)
{
for(j=0; j<10; j++)
{
scanf(“%d”,&n[i][j]);
}
}
printf(“You entered\n”);
for(i=0; i<10; i++)
{
for(j=0; j<10; j++)
{
printf(“%d\n”,n[i][j]);
}
}
getch( );
}

You might also like