Programming with C
Programming with C
PROGRAMMING WITH C
Program: Program is a set of instructions, which solve a particular problem with in the computer. While
instruction is a request selected by the programmer for developing the related operation within the program.
Types of programming languages: All programming languages can be divided into two categories. They are:
i) Low level languages
ii) High level languages
Low level languages: Computer understands one and only one language i.e. machine language. Machine language
is a collection of 0’s and 1’s, which is also known as Binary language.
Ex: Machine language, Assembly language
❖ Instructions of a machine language program are immediately executable because the computer understands
these instructions directly and no conversion is required.
❖ It is difficult to write the program using binary code so a new language is introduced, called as High level
languages.
High level languages: In these languages, instructions are written in English like languages which we can
understand.
Ex: COBOL, FORTRAN, PASCAL, C++ and JAVA.
❖ It is easy to write the program.
❖ Instructions of High level language program are not immediately executable, because the computer does
not understand English. So these languages require translation steps to translate from English code to
Machine language code. So the program execution is slow.
*** C is also a language. In C instructions are written in English like languages. Since it comes under High level
language category. Even though it is High level language, it is called as Machine level language because of
following reasons. Even though it is High level language, it is called as Machine level language because of
following reasons.
i. C satisfies the advantages of both Low level and High level languages.
ii. C can be used to write both system programs as in Low level languages and general purpose
programs in High level languages.
History of C language:
By 1960, there were only few computer languages are present; almost each language is used for a specific
purpose. For example, COBOL was used for solving the problems of Business applications. FORTRAN is used
for solving Engineering and Scientific applications. The people at this stage started thinking that instead of
learning so many languages, why not we use only one language where any type of application problems can be
Page 1
Programming with C
solved.
Year Language Developed by
1960 ALGOL International Committee
Translators: Translators are the programs which converts the instructions written in High level language to
Machine understandable language. The translators are: Compilers and Interpreters.
i) Compiler: It is one of the translators that translate a program written in High level language to Machine
instructions. Compiler translates all the lines from source program to machine code known as object code. Some
of the languages that use compiler as their translators are C, C++, COBOL, etc.
ii) Interpreter: Some High level languages often use Interpreter instead of compiler to translate instructions into
machine code.
Interpreter translates one line after the other into machine language. Some of the languages that use interpreter as
their translators are: dbase, basic, etc.
***** C uses compiler as its translator. There are different types of compilers available in the market. Among
them few are TurboC, BorlandC, ANSIC, and QuickC.
Page 2
Programming with C
Page 4
Programming with C
C tokens
1. Identifiers: The names of variables, functions, Labels and other user defined items are called as Identifiers.
An identifier can include Alphabets (a-z, A-Z), digits (0-9) and Underscore (_) symbol.
The length of an identifier can vary from one to several characters.
It starts with a letter or underscore.
It cannot include spaces.
Uppercase and lowercase identifier names are treated as different. C is a case sensitive language.
Ex: a1, rno, emp_name, etc.
2. Keywords: Keywords are defined by C compiler and each keyword has a special meaning. These are the
reserved words and cannot be used as names of variables or functions or labels. C has 32 keywords.
auto break case char const continue default
do double else enum extern float for
Page 5
Programming with C
Constants
Numeric constants: The constants which are related to numbers are called as Numeric constants.
i. Integer constants: Integer constants are numbers without decimal points.
Ex: 123, 1003, -2345
ii. Floating point constants: Floating point constants are numbers with decimal points.
Ex: 120, 123.456, -4123.8695, etc
123.456=1.23456x102=1.23456E2 it is called as exponential notation.
Exponential notation: Mantissa E exponent
Alphanumeric constants: The constants which are related to characters are called as alphanumeric constants.
i. Single character constants: A single character constant can be an alphabet or a digit or a special
symbol which is enclosed with in single quotes (‘ ’).
Ex: ‘a’, ‘3’, ‘*’, etc.
ii. String constants: A string constant is a sequence of characters enclosed with in double quotes(“ ”).
Ex: “program”, “ravi”, “student123”, etc.
iii. Boolean constants: Boolean constants are True or False. In C zero is false and non-zero is True.
5. Special characters: They include characters such as “, ‘, /, &, etc.
6. Operators: Operator is a symbol which is used to perform some specific operation. In C there are many types
of operators. Ex: Arithmetic operators (+, -, *, /, %).
Q: Explain Backslash character constants (or) Escape sequences?
C supports some special backslash character constants that are used in output functions. For example, the
symbol ‘\n’ stands for new line character. Some of the escape characters are shown below.
Page 6
Programming with C
Structures
Arrays Void
Numeric Alpha
numeric Unions
Enumerations Pointers
Integer char
float, double string
1. Primitive Data types (System defined/ built in/primary/fundamental/ scalar data types): The code of
the Primitive Data types is declared and defined by the C compiler and stored in library files. We can
simply use these data types when required. The primitive data types are int, float, double, char.
Page 7
Programming with C
i. Integer data type: Integer data types are used to declare integer variables with the help “int” key
word. These integer variables can occupy 2 bytes in the memory.
Ex: int num; ---→num
ii. Floating point data types: This float data type is used to declare float variables with the help of
“float” key word. Float variables can occupy 4 bytes in the memory. Float variables can have 6 decimal
points.
Ex: float amount=10.95; --→ amount 10.950000
iii. Double data type: It is used to declare real variables same as float with the help of “double” key word.
Double variables can occupy 8 bytes in the memory. Double variables can have 16 to 18 decimal
points.
Ex: double vector=3.44; --→ vector 3.440000
iv. Character data type: It is used to declare character variables with the help of “char” key word.
Character variables can occupy 1 byte in the memory.
Ex: char star=’*’; --→ star *
2. User defined data types: These data types are defined and used by the programmer.
Ex: structures, unions, enumerations.
3. Derived Data types: These data types are derived from primitive data types.
Ex: Arrays and pointers.
Page 8
Programming with C
Empty data type: “void” is empty data type. The void type has no values; this is used to specify the type of
functions. The type of a function is said to be void when it does not return any value.
Q: What is a variable and how to declare a variable?
A variable is a data name in which a constant value is stored. Values of variables can be changed from time
to time. Declaration of variable can be done before they are used in the program.
Declaration of variable: Declaration does two things
i. It tells the compiler what the variable name is
ii. It specifies what type of data the variable will hold.
Documentation section
Link section
Definition section
Global declaration section
main ( )
{
Declaration part;
Executable part;
}
Subprogram section
Function 1
Function 2
…
…
Function n
(User defined functions)
Page 9
Programming with C
i. The documentation section: It consists of comment lines giving name of the program and other details.
Comments are the non-executable statements. These are mainly used for understanding the purpose of the
program.(program name, date and time of creation, author name). All the comments are enclosed in
between /*…..*/ markers.
Ex: /*This program is used for addition of two numbers*/
ii.The link section: It provides instructions to the compiler to link functions from the system library. It
contains preprocessor statements. The statements that are begin with “#” symbol is said to be pre processor
directive statement. These are processed (compiled) first before any programming statements in the
programs are processed. #include statement is used to include a programming file into another file.
Ex: #include<stdio.h>
#include<math.h>
iii. The definition section: It defines all symbolic constants.
iv.The global declaration section: There are some variables that are used in more than one function. Such
variables are called global variables and are declared in this section that is outside of all functions.
v.main( ) function: Every C program must have one main function section. This section contains two parts,
declaration and executable part.
➢ Declaration part declares all the variables used in the executable part.
➢ There should be at least one statement in the executable part which contains instructions to perform
certain task.
➢ The declaration and executable part must appear between the opening and closing braces. All
statements in the declaration and executable parts should end with the semicolon (;).
vi.The subprogram section: It contains all the user defined functions that are called in the main function.
User defined functions are generally placed immediately after the main function.
All sections, except the main function may be absent when they are not required.
Ex: /*program to print a message*/
#include<stdio.h>
void main( )
{ Output:
welcome to c-language
printf(“ welcome to c-language”); This is my first C program
printf(“ This is my first C program”);
}
Page 10
Programming with C
Q: Explain the procedure for creating, compiling, linking and executing a C program.
Creating a C program:
➢ Open any C editor like TurboC.
➢ Now we select NEW option from the File menu.
➢ An edit window will appear with the filename NONAME.C.
➢ Write the program.
➢ Once we complete our typing we should save it to the disk as PROGRAMNAME.C by selecting
save from the file menu, or by pressing the F2.
Compiling the Source Program:
➢ To compile the source file, we select compile menu and will press enter key.
➢ If there is syntax error in the source program, then the resulting window- warning: 0, errors: 0 and
finally success: press any key.
➢ This compilation process creates an object file, which has an extension .OBJ
➢ However if there is error then the compiler displays the appropriate error messages, that tells the
cause of the error and the compilation process terminates. Therefore go back to the source program,
correct it and compile it again. You can also compile the source program by pressing the ALT and
F9 keys simultaneously.
Linking the program:
➢ The program is linked with functions that are needed from ‘C’- library.
➢ To link our object file, select link from the compile menu. After this the OBJ file will be compiled
with the one or more library files.
➢ The result of this linking process produces an executable file with .EXE extension.
Executing (Running) the program:
➢ To execute (run) the .EXE file, select run from RUN menu and press enter key. The result will be
displayed on the screen and controls back to the editing screen.
➢ However you can also execute the .EXE file by pressing CTRL and F9 keys simultaneously. To see
result select User Screen from RUN menu or by pressing ALT and F5 keys simultaneously.
Q: Explain conversion characters (Or) Format specifiers (Or) Conversion Strings?
Format specifiers are used to provide the format of the variables to be printed.
Each format specifier has to be preceded with a “%” sign.
These are used in some of the input and output statements, such as printf and scanf.
The following are the various format specifiers:
Page 11
Programming with C
Conversioncharacter Meaning
%d Integer
%u unsigned integer
%c character
%f floating point
%s string
%o octal value
%x hexa decimal value
%ld long decimal
Ex: /*Example program for format specifier*/
#include<stdio.h>
main( )
{
int n=10;
float salary=1000.00;
Output:
char symbol=’&’; Value of n=10
clrscr(); Value of salary=1000.000000
printf(“\n value of n is=%d”,n); Value of symbol is=&
printf(“\n value of salary=%f”,salary);
printf(“\n value of symbol is=%c”,symbol);
}
Q: What is preprocessor statement? (Or) What are compiler directives (#include, #define and #if
directive).
➢ The preprocessor mechanism allows different directives such as #include and #define.
➢ Before processing the actual program these are processed first.
➢ The preprocessor directives follow special syntax rules. They are begin with # symbol andthey are not
terminated (ended) with semicolon.
➢ They are placed in the program before main ().
➢ Few other directives are: #if, #else, #endif, #undef.
Include directive (File inclusion directive):It includes the processed file that has been mentioned in
angle brackets or quotes.
Syntax: 1)#include<filename> 2) #include“filename”
Ex: #include<stdio.h> #include“abc.c”
Page 12
Programming with C
• Global scope: when variable is defined outside all functions. It is then available to all the
functions of the program and all the blocks program contains.
• Local scope: when variable is defined inside a function or a block, then it is locally accessible
within the block and hence it is a local variable.
• Function scope: when variable is passed as formal arguments, it is said to have function scope.
Let’s understand this with the help of an example:
#include<stdio. h>
int global=100; //global variable declared
void func1();
void main ()
{
int local=10; //local variable declared
printf (“Global variable is %d” ,global);
printf (“Local variable is %d”, local); func1( );
}
void func1()
{
printf(“Global inside func1 is %d”, global); // would print the global successfully.
}
Output:
Global variable is 100
Local variable is 10
Global inside func1 is 100
Q: What are Storage classes? (Or) Explain scope, visibility and lifetime of avariable.
A storage class specifies the scope, life and initial value of a variable.
Scope: Scope of a variable means, the area or place where a variable can be accessed.
Life: Life of a variable means, the period of time the variable exist in memory.
In C, there are four storage classes, they are:
1. auto
2. extern
3. static
4. register
Page 14
Programming with C
Page 15
Programming with C
Page 16
Programming with C
auto (local) Within the function Till the function ends Garbage value
Register Within the function Till the function ends Garbage value
Q. Explain I/O functions in C? (Or) Discuss the elementary functions of Input and Output in C?
The Input functions of C are used to read the data values at execution time into the declared program
variables. In the same way, output functions are used to print the values on the console at execution time.
Input/output statements are categorized into two, they are:
i) Formatted Input/output functions (or) standard Input/Output functions
ii) Unformatted Input/Output functions
i).Formtted I/O functions:The I/O functions that use format specifiers such as %d, %f,..etc. in their Input and
Output operations are known as Formatted I/O functions. These functions allow the input read from the
keyboard and the output displayed on the monitor. Each program that uses a standard Input/Output functions
must contain the statement #include<stdio.h>. “stdio.h” stands for standard input output headerfile. Formatted
I/O functions are: a) scanf( ) b) printf( )
Page 17
Programming with C
ii).Unformatted I/O functions:The I/O functions that does not use format specifiers in their input and output
operations are known as unformatted I/O functions. They are:
Where, control string is the format specifier in which the data is to bo entered and the arg1, arg2,
arg3,….argn are the address of locations where the data is stored. Control string and arguments are separated by
comma’s.
Ex: 1) Inputting Integer Numbers:
Int num;
scanf(“%d”,&num);
2) Inputting Real Numbers:
float fee;
scanf(“%f”, &fee);
3) Inputting characters:
char gender;
scanf(“%c”,&gender);
4) Inputting character Strings:
char name[20];
scanf(“%s”,name);
5) Reading Mixed Datatypes:
int num;
float fee;
char gender;
char name[20];
scanf(“%d%f%c%s”, &num, &fee, &gender, name);
Page 18
Programming with C
printf( ):The standard output function printf( ) is used to print all types of data items on the monitor at
runtime.
Syntax:
printf(“message”);
printf(“control string”, arg1, arg2,….argn);
The first syntax is used to print some message on the screen. Second syntax is used to print arg1, arg2,….argn
values including with format specification.
Ex: 1) Output of Integern umbers:
printf(“%d”, integer_variable);
int num=20;
printf(“%d”, num);
2) Output of Real numbers:
printf(“%f”,float_variable); float
fee=7500.00;
printf(“%f”,fee);
3) Printing a single character:
printf(“%c”,character_variable);
char gender=’m’;
printf(“%c”, gender);
4) Printing of Strings:
printf(“%s”, character_array);
char name[20]=”vdc”;
printf(“%s”, name);
5) Mixed data output:
printf(“%s%c%d%f”, name, gender, num, fee);
Q: How to read a character and write a character in C?
Reading a character:The simplest of all input/output operations is reading a character from the ‘standard
input’ unit (usually the keyboard) and writing it to the ‘standard output’ unit (usually the screen). Reading
a single character can be done by using the function getchar. (This can also be done with the help of the
scanf function). The getchar takes the following form:
Variable-name = getchar( );
Variable-name is a valid C name that has been declared as char type. When this statement is
encountered, the computer waits a key is pressed and then assigns this character as a value to getchar
function. Since getchar is used on the right-hand side of an assignment statement, the character value of
getchar is in turn assigned to the variable name on the left. For example
char name;
name = getchar( );
Page 19
Programming with C
Will assign the character ‘H’ to the variable name when we press the key H on the keyboard.
Example:
# include <stdio.h>
void main()
{
char ch;
printf (“ \n enter a character : “);
ch = getchar( );
printf (“\n ch = %c”, ch);
}
Writing a character:Like getchar, there is an analogous function putchar for writing characters
one at a time on the screen. It takes the form as shown below:
putchar(variable-name);
Where, variable-name is a type char variable containing a character. This statement displays the
character contained in the variable-name on the screen. For example, the statements:
answer = ‘Y’;
putchar(answer);
will display the character Y on the screen. The statement
putchar(‘\n’);
would cause the cursor on the screen to move to the beginning of the next line.
Example program:
#include<stdio.h>
void main()
{
char ch = ‘A’;
putchar(ch);
putchar(‘s’);
putchar(‘z’);
}
Output: ASZ
Page 20
Programming with C
Q: What is Type casting (Type conversion)? (Or)Explain the process of conversion of variables in C.
A: Type casting is the process of converting one data type to another data type. It makes the variables
compatible temporarily. Type casting can be of two types.
1. Implicit Type casting
2. Explicit Type casting
Implicit Type casting: When the constants and variables of different types are mixed in an expression they are
converted to the same type. This conversion is done by the ‘C’ compiler. The compiler converts all the operands
to the type of largest operand. For example, int type gets converted to float type.
Explicit Type casting: If a user forcefully changes the data type into other allowable data type it is said to be
explicit type casting.
Ex: int to float
float x;
x= 5/2; /* x value will be 2.0 */ x=
(float) 5/2; /* x value will be 2.5 */
float to int
int x;
x= 3.2; /* causes error */
x= (int) 3.2; /* x will be 3 */
Page 21
Programming with C
Operator Meaning
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division (quotient)
% Modulo division (remainder)
Ex: #include<stdio.h>
void main()
{
int a, b, c, d, e, f, g;
clrscr( );
printf(“\n Enter two numbers”);
scanf(“%d%d”, &a, &b);
c=a+b;
d=a-b;
Page 22
Programming with C
e=a*b;
f=a/b; Output:
Enter two numbers
g=a%b;
20
printf(“\n Addition=%d”, c); 10
printf(“\n Subtraction=%d”, d); Addition=30
Subtraction=10
printf(“\n Multiplication=%d”, e);
Multiplication=200
printf(“\n Division=%d”, f); Division=2
printf(“\n Remainder=%d”, g); Remainder=0
}
ii) Relational operators: Relational operators are used to make comparisons between operands. These
operators require two operands so these are also called as binary operators.
Operator Meaning
== Equal to
!= not equal to
After comparing the operands, these operators return either true or false.
Ex: int a=10, b=20;
a==b returns false
iii) Logical operators: These operators are used to form compound conditions by combining two or more
relations.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Page 23
Programming with C
Truth table:
iv) Assignment operators: Assignment operators are used to assign values to variables.
Ex: int a=10; here, a is variable and it is assigned with 10.
C supports a set of shorthand assignment operators, which are used in the form:
V Op = Exp;
Following are the some of assignment operators: +=, -=, *=, /=, %=
Statement with shorthand assignment operator Statement with simple assignment operator
a+ =1 a=a+1
a - =1 a=a–1
a* =1 a=a*1
a/ =b a=a/b
a% =b a = a% b
v) Conditional operator: The character pair ?: is the conditional operator. It is also called as ternary operator
because it is used on three operands. The general syntax of the conditional operator is:
Page 24
Programming with C
It first assigns value 10 to x, then assigns 5 to y and finally assigns 15 (i.e. 10+5) to res.
#include<stdio.h>
main( )
{
int a, b;
a= (b=5, b*3);
4) sizeof(3.4); // it returns 8
Page 25
Programming with C
iii) Pre decrement operator: It first decrement the operand and then the result is assigned to the variable on the
left.
Ex: int x=3, y;
y= --x;
In the above statement: x=2, y=2
iv) Post decrement operator: It first assigns the value to the variable on the left and then decrement the operand.
Ex: int x=3, y;
y= x--;
In the above statement: x=2 but y=3.
viii) Bitwise operators: Bitwise operators are used to perform operations on bits(0 and 1). They convert the
numbers into binary system and then apply bitwise operators.
Operator Name
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ complement operator
Page 26
Programming with C
Page 27
Programming with C
4. goto statement
II) Looping control structures (Decision making and Looping (or) Iterative statements)
1. while loop
2. do while loop
3. for loop
III) Jumping control Structures
1. break (Jumping out of loop)
2. continue (Skipping a part of a loop)
3. exit (Jumping out of the program)
Q: Explain Decision making and Branching statements (or) Conditional control structures.
A: Branching: When a program breaks the sequential flow and jumps to another part of code is called as
branching. C language possesses decision-making capabilities by supporting the following statements:
1. if statement
2. switch statement
4. goto statement
Page 28
Programming with C
if (test expression)
The if statement may be implemented in different forms depending on the complexity of conditions to be
i. simple if statement
i) Simple if: The if structure is also called as conditional statement. If the “test expression” is true then
statement-block will be executed. Otherwise the statement-block is skipped and the execution will jump
to the statement-x.
Syntax: Flowchart:
entry
false
Statement-x
Ex: if(x>0)
printf(“x is a positive number”);
ii) if…else: This statement is an extension of simple if statement. In this type of statement if the condition is
true then the “true-block statements” will be executed. Otherwise “false- block” statements will be
executed.
Page 29
Programming with C
if (test expression)
{ True false
test
True-block statements; expression
} ?
else False block
{ True block statements
False-block statements; statements
} Statement-x
statement-x;
Statement-x
Page 30
Programming with C
}
iv) else…if ladder: There is another way of putting ifs together when multipath decisions are involved.
Flow chart:
Entry
True False
Condition1
True False
Statement-1 Condition2
True False
Statement-2 Condition3
Statement-n default-statement
Statement-x
Page 31
Programming with C
This construct is known as else…if ladder. The conditions are evaluated from the top to downwards. As
soon as the true condition is found, the statement associated with it is executed and the control is transferred to
the statement-x. When all the ‘n’ conditions become false, then the final else containing the default-statement
will be executed.
Syntax:
Example:
if(condition1)
if(a>b && a>c)
statement-1;
else if(condition2) printf(“a is big”);
statement-3; else
: printf(“c is big”);
else if(condition n)
statement-n;
else
default-statement;
statement-x;
2. Decision making with switch statement: It is called as multi-way conditional control structure. The switch
statement tests the value of a given variable (or expression) against a list of case values and when a match is
found, a block of statements associated with that case is executed. The general form of switch statement is:
Syntax: switch( expression)
{
case value-1:
block-1;
Page 32
Programming with C
break;
case value-2:
block-2;
break;
:
:
default:
default_block; break;
}
Statement-x;
The “expression” is an expression or characters. Value-1, value-2,….. are the constants and are known
as case labels.
Flow chart:
Entry
expression
expression=value-1
block-1
expression=value-2
block-2
:
:
(no match found) default
default-block
Statement-x
Page 33
Programming with C
Example: program to display the name of the day depending on the number entered from keyboard.
#include<stdio.h>
Void main( )
{
int day;
clrscr( );
printf(“\n Enter a number between (1-7)”); scanf(“%d”,
&day);
switch (day)
{
case 1: printf(“\n Monday”);
break;
case 2: printf(“\n Tuesday”);
break;
case 3: printf(“\n Wednesday”);
break;
case 4: printf(“\n Thursday”);
break;
case 5: printf(“\n Friday”);
break;
Output:
case 6: printf(“\n Saturday”);
break; Enter a number between (1-7)
case 7: printf(“\n Sunday”); 2
break; Tuesday
default: printf(“\ U entered a wrong number”);
break;
}
}
3. Decision making with Conditional operator: The character pair ?: is the conditional operator. It is also
called as ternary operator because it is used on three operands. The general syntax of the conditional operator is:
Page 34
Programming with C
4. Decision making with goto statement: goto is used as a conditional control structure and looping control
structure.
a) Jumping forward: b) Jumping backward:
statement-1; statement-1;
goto label; label:
statement-2; statement-2;
label: goto label;
statement-3; statement-3;
In the Jumping forward after executing statement-1 goto moves the control to the labeled statement i.e.
statement-3. Here statement-2 is not executed.
In the Jumping backward, after statement-1 gets executed statement-2 is executed for infinite times,
because goto moves the control to statement-2 repeatedly.
Example Program for Forward Jump:
# include <stdio.h>
# include <conio.h>
void main( )
{
clrscr ( );
printf(‘\n statement1”);
printf(“\n statement2”);
goto A;
printf (“\n this statement does not execute”); A:
printf (“\n statement4”);
getch ( );
}
Output: statement1
statement2
statement4
Example program for Backward jump:
# include <stdio.h> #
include <conio.h> void
main( )
{
int i=1;
clrscr( );
START:
printf (“\t %d”, i);
i++;
if (i<=10)
Page 35
Programming with C
goto START;
getch( ); Output: 1 2 3 4 5 6 7 8 9 10
}
Test False
Condition Body of the
Loop
True
False
Page 36
Programming with C
In the Entry controlled loop, the conditions are tested before the start of the loop execution. If the
conditions are not satisfied then the body of the loop will not be executed.
In the Exit controlled loop, the test is performed at the end of the body of the loop and therefore the body
of the loop is executed unconditionally for the first time.
A looping process would include following four steps:
The while is an Entry controlled loop statement. The test condition is evaluated and if the condition is
true then the body of the loop is executed. After execution of the body, the condition is once again evaluated
and if it is true, the body is executed once again. This process of repeated execution of body continues until the
condition is false.
Ex: main( )
{
int i=1;
while(i<=10)
{
printf(“\n hello”);
i=i+1;
}
}
Above program prints “hello” for 10 times.
Page 37
Programming with C
ii) do-while loop: It is an Exit controlled loop statement. The basic form of do-while statement is:
Initialization;
do True
{ Condition
Body of the loop
Body of the loop
} while(condition); False
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of
the loop, the condition is evaluated. If the condition is true once again the body of the loop is executed.
Ex: main( )
{
int i=1;
do
{
printf(“\n hello”);
i=i+1;
} while(i<=10);
}
The above program prints “hello” for 10 times.
iii) for loop: The for loop is another entry controlled loop, this provide a more concise loop structure. The basic
form of the loop is:
Page 38
Programming with C
initialization
True
Condition Body of the loop Increment/decrement
False
Page 39
Programming with C
ii) Continue: It may be necessary to skip a part of the body of the loop under certain conditions. This can
be possible by using continue statement. “continue” is used in loops. It omits the statements written after
“continue” and restarts the iterative loop.
iii) exit( ): We can jump out of a program by using the library function exit( ). In case, due to some reason, we
wish to break out of a program and return to the operating system, for this we can use the exit( ) function, as
shown below:
…………
…………
if(test-condition) exit (0);
…………
…………
The exit( ) function takes an integer value as its argument. Normally zero is used to indicate normal
termination and a nonzero value to indicate termination due to some error or abnormal condition. The use of
exit( ) function requires the inclusion of the header file <stdlib.h>.
Page 40
Programming with C
C supports several mathematical functions. These functions are defined in math.h header file. To use any of
these functions in a program we should include the line: #include<math.h>
Page 41
Programming with C
Function Meaning
i) Trigonometric functions:
ii) Hyperbolic:
Page 42
Programming with C
strupr( ) char *strupr(char *s) Converts the given string into uppercase
strlwr( ) char *strlwr(char *s) Converts the given string into lowercase
strcmp( ) int strcmp(char *s1, char *s2) Compares s1 and s2 and Returns 0 if
s1 and s2 are equal Returns positive
if s1>s2
Return negative if s1<s2
6. int islower(int c): This function checks whether the passed character is
Lowercase letter.
7. int isprint(int c): This function checks whether the passed character is printable.
8. int ispunct(int c): This function checks whether the passed character is a punctuation character.
Page 43
Programming with C
9. int isspace(int c): This function checks whether the passed character is white-space.
10. int isupper(int c): This function checks whether the passed character is an uppercase letter
11. int isxdigit(int c): This function checks whether the passed character is a hexadecimal digit
12. int tolower(int c): This function converts uppercase letters to lowercase.
13.int toupper(int c): This function converts lowercase letter to uppercase.
Function Description
setdate( ) This function used to modify the system date
getdate( ) This function is used to get the CPU time
clock( ) This function is used to get current system time
time( ) This function is used to get current system time as structure
difftime( ) This function is used to get the difference between two given times
mktime( ) This function interprets tm structure as calendar time
localtime( ) This function shares the tm structure that contains date and time
informations
ctime( ) This function is to return string that contains date and time informations
Page 44
Programming with C
are called subprograms that are much easier to understand, debug, and test. In C, such subprograms are referred
to as ‘functions’.
This “division” approach clearly results in a number of advantages.
1. It facilitates top-down modular programming as shown in the figure.
2. The length of a source program can be reduced by using functions at appropriate places. This factor is
particularly critical with microcomputers where memory space is limited.
3. A function may be used by many other programs. This means that a C programmer can build on what
others have already done, instead of starting all over again from scratch.
Main Program
B1 B1
Q: Explain the procedure to create a function? (Or) What are the components (elements) of a function?
A: Any function whether it is a system or user defined, should contain three main components.
They are:
1. Function prototype or function declaration
2. Definition of function
3. Function call
Function prototype: Before the function is defined in the program, the function name and its details should be
provided to the compiler. It can be done by declaring the function above the main function is called as
“Prototype of a function” or “forward declaration of function”.
Syntax: return_type function_name ([parameters list] );
Ex: void message( );
Definition of function: It is the actual function that contains programming statements to perform the operation
of function. The programming statements should be written between “{ }”. The header of definition of function
should be similar to the prototype of function but the difference is prototype should end with semicolon(;),
Page 45
Programming with C
whereas definition should not. The definition should be written outside all functions. Definition of function is
also called as “Called function”.
Function call: Defining the function does not do anything without execution. To execute the function, it should
be called. A function can be called by the name of the function and such statement is known as “Function call”.
And it is also called as “calling function”.
Syntax: function_name( [parameters list] );
Ex: message( );
Let us write the complete program by creating the function “message( )”. #include<stdio.h>
void message( ); Function prototype
main( )
{
message( ); Function call ( calling function)
message( ); Function call ( calling function)
}
void message( ) called function
{
Page 46
Programming with C
When a value is returned, it is automatically cast to the function’s type. In functions that do
computations using doubles, yet return ints, the returned value will be truncated to an integer. For instance, the
function
int product (void)
{
return (2.5 * 3.0);
}
will return the value 7, only the integer part of the result.
1. No Argument, No Return: A function, which does not take any arguments and does not return any value.
Ex: #include<stdio.h>
void message( );
main( )
{ Output:
message( );
This is sample function
This is sample function
message( );
}
void message( )
{
printf(“\n This is sample function”);
}
Page 49
Programming with C
2. Argument, No Return: A function, which takes arguments, but do not return any value.
Ex: #include<stdio.h>
void sum( int x, int y);
main( )
{
clrscr( );
sum( 10, 20); Output:
sum( -5, 25);
Sum=30
}
void sum( int x, int y) Sum= 20
{
int z= x+y;
printf(“\n Sum= %d”, z);
}
3. No Argument, Return: A function, which does not take arguments but returns a value.
Ex: #include<stdio.h>
int sum( );
main()
{
int k;
clrscr( ); Output:
k= sum( );
printf(“\n Sum=%d”, k); Sum=30
}
int sum( )
{
int x=10, y=20;
return (x+y);
}
4. Argument, Return: A function, which takes argument and returns a value.
Ex: #include<stdio.h>
int sum( int x, int y);
main( )
{
int k;
clrscr( ); Output:
k= sum( 20, 30); Sum=50
printf(“\n Sum=%d”, k);
}
In the above example, swapping is done in the parameters of called function(x, y) only, whereas these
changes are not made in the arguments of calling function (a, b).
Call by reference: It is also called as pass by reference. In this method, the addresses of arguments are passed
to the parameters of called function (function definition). Since, the parameters should be declared as pointers.
When we make any changes to the parameters of called function, those changes reflects in the arguments of
calling function.
Page 51
Programming with C
Ex: #include<stdio.h>
void swap(int *x, int *y); main( )
{
Output:
int a=10, b=20; a=10, b=20
clrscr( ); after swapping: a=20, b=10
printf(“\n a=%d, b=%d”, a, b);
swap(&a, &b);
printf(“\n after swapping: a=%d, b=%d”, a, b) ;
}
void swap(int *x, int *y)
{
int temp;
temp= *x;
*x= *y;
*y=temp;
}
In the above example, if we make any changes to the parameters of called function, that changes reflects in
the arguments of calling function
Page 52
Programming with C
• Memory wastage will be there.
• To delete an element in the array, you need to traverse (visit) throughout the array.
• To insert an element in the array, you need to traverse (visit) throughout the array.
12 Q: What are the types of arrays? And how do you initialize the arrays.
A: There are mainly three types of arrays.
1. One dimensional arrays (or) Single Dimensional arrays
2. Two dimensional arrays (or) Double dimensional arrays
3. Multi dimensional arrays
One dimensional array: An array with one subscript is called as One dimensional array or single subscripted
variable.
Syntax: datatype arrayname[size];
Ex: int a[10];
In the above example, for the array ‘a’ 20 bytes of memory will be allocated.
Initialization of One dimensional array: giving starting values to a variable is called as initialization. One
dimensional array can be initialized as follows:
In the above example, to access the third element of the array we may use a[2], i.e. the index of third
element is 2.
To print the array, we may write:
Page 53
Programming with C
Two dimensional arrays: Array with two subscript values is called as two dimensional arrays,
i.e, it uses two indexes to refer its elements. It represents the data in the form of rows and columns.
Syntax: datatype arrayname[row-size][col-size];
Ex: int a[3][3];
In the above example, for the array ‘a’ 18 bytes of memory will be allocated and the array can hold 9
integers at a time.
Initialization: Two dimensional arrays can be initialized as follows:
Page 54
Programming with C
A: A string is set of characters enclosed in double quotes. As we know that at the end of the string a null
character (\0) stored in the character array. Any group of characters defined between double quotation marks is
a string constant.
Example: “well done!”
Declaring String variables: C does not support strings as a data type. However, it allows to represent strings as
character arrays.
Page 55
Programming with C
Syntax: char string_name[size];
❖ char city[20] ={‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ’\0’}; (Or)
❖ char city[20] = “NEW YORK”;
(Or)
❖ char city[ ] = “NEW YORK”;
❖ Differences between above declarations are, when we declare string as “city[20]”, 20 bytes of memory
space is allocated for holding the string value.
❖ When we declare string as “city[ ]”, memory space will be allocated as per the requirement during
execution of the program.
Q: How to read and write a string?
Reading Strings: This can be done by using scanf( ) and gets( ) functions.
i) Using scanf( ) function: The input function scanf( ) can be used with %s format specification to read in a
string of characters.
Example: char address[10];
scanf(“%s”, address);
ii) Using gets( ): It is unformatted string input function that reads string from the keyboard.
Syntax: gets (string-variable);
gets( ) reads string from the keyboard and stores into the string-variable given in the ( ).
This function even stores spaces because it stores enter key as null termination (\0).
Writing Strings: This can be done by using printf( ) and puts( ) functions.
i) Using printf( ) function: The output function printf( ) can be used with %s format specification to print
strings on the screen.
Example: printf(“%s”, address);
ii) Using puts( ) function: It is unformatted output function that prints strings on the monitor. The puts( ),
after printing the string, it prints the new line character (\n) so that the cursor moves to next line.
Syntax: puts(string-variable or constant);
puts( ) prints the given string on the monitor. The string may be a variable or constant but not both.
Page 56
Programming with C
Example program:
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[15];
char address[20];
clrscr ( );
printf (“\n Enter your name :”);
gets(name);
printf(“\n Enter your address :”);
scanf(“%s”,address);
printf (“\n Your name is :”);
puts(name);
printf(“\n Your address is :%s”,address);
getch( );
}
Output: Enter your name: Rajkumar
Enter your address: Karimnagar Your
name is: Rajkumar
Your address is: Karimnagar
strupr( ) char *strupr(char *s) Converts the given string into uppercase
strlwr( ) char *strlwr(char *s) Converts the given string into lowercase
strcmp( ) int strcmp(char *s1, char *s2) Compares s1 and s2 and Returns 0 if
s1 and s2 are equal Returns positive
if s1>s2
Return negative if s1<s2
Page 57
Programming with C
The following program explains the usage of string functions.
1) Length of a string:
#include<stdio.h>
#include<string.h>
main( )
{
int L;
char x[10]; Output:
printf(“\n enter a string:”);
Enter a string:
scanf(“%s”, x);
L=strlen(x); Apple
printf(“\n length of given string=%d”,L); Length of given string=5
}
Page 59
Programming with C
Q: What is structure? Explain how to declare structure variables and accessing structure
members.
A: Structure is a derived data type. A structure variable can hold set of dissimilar (different) or similar values.
Creation of a structure is of two step process:
i) Defining the structure template
ii) Declaring structure variables
Defining structure template: structure template can be defined by using following syntax:
struct tag-name Here, “struct” is the keyword which is used to create a
{ structure. “tag-name” is the name of the structure. The list of
Page 61
Programming with C
int acno;
int amount;
};
struct bank b1={“ramesh”, 120,15000}; /* structure initialization */
clrscr( ); Output:
printf(“\n Name=%s”, b1.name); Name= Ramesh
printf(“\n AccountNo=%d”, b1.acno); AccountNo=120
printf(“\n Amount=%d”, b1.amount); Amount=15000
}
Q: Explain Functions and Structures?
A: Structure variables can also be passed from calling function to called function in the same way as the normal
variables are passed. When the structure variable is passed to a function the entire structure is copied into the
receiving formal parameter variable.
The general format of sending a copy of a structure to the called function is:
function_name(structure_variable_name);
struct student
15 25 35
rno rno rno
{
marks 98 marks 85 marks 89
char name[15];
int rno, marks;
};
struct student s[3]={“sri”, 15, 98, “nivas”, 25, 85, “shiva”, 35, 89};
clrscr( );
for(i=0; i<3; i++)
printf(“\n %s \t %d \t %d”, s[i].name, s[i].rno, s[i].marks);
}
Output of above program is:
sri 15 98
nivas 25 85
shiva 35 89
Page 63
Programming with C
Q: What is Enumerated data type? Explain with an example.
A: Enumeration is a way of defining user defined data type. It allows us to declare string constants with
integer equivalent values. The general format of an enumeration declaration is:
enum tag-name
{
member_1, member_2, member_3, ……., member_n
};
The members of the enumerations are automatically assigned with consecutive constant values starting
from 0. Also a variable can be declared to enumeration by following syntax:
Example:
#include<stdio.h>
main( )
{
enum colors{red=10, green=20, blue=30 };
enum colors c1,c2;
clrscr( ); Output:
c1=red; 10 30
c2=blue;
printf(“\n %d \t %d”, c1,c2);
}
Page 64
Programming with C
{
int a;
float b;
};
union alpha a1;
clrscr( ); a1.a=30;
printf("\n a=%d",a1.a); a1.b=20.5;
printf("\n b=%f",a1.b);
}
In the above example, the size of the alpha would be 4 bytes.
Q: Compare Structure and Union. (Or) Write differences between structures and unions.
Structures Unions
6. All the members of the structure are accessed 6. All the members of the union are
accessed with dot (.).
with dot (.).
Page 65
Programming with C
Memory Organization
Page 66
Programming with C
Whenever we declare a variable, the system allocates, somewhere in the memory, an appropriate
location to hold the value of the variable. Since, every byte has a unique address number this location will have
its own address number.
Page 67
Programming with C
#include<stdio.h> 101 102
main( ) 10
n
{ 201 202
int n=10, *p; p 101
p= &n;
printf(“%d”, n); /* prints 10 */
printf(“%d”, *p); /* prints 10 */
printf(“%d”, *(&n)); /* prints 10 */
printf(“%u”, p); /* prints the address*/
}
Page 68
Programming with C
Q. Programming Rules:
i) All lines of C- statements must end with a semicolon.
ii) C is case-sensitive.
iii) A C-program statement can be split into many lines or can be written in one line.
iv) Braces {} must always match upon pairs.
v) All C-programs starts with main() function
vi) Comments cannot be nested.
/*first program ,
welcome to C*/
Q. ALGORITHM:
Definition: An algorithm is a finite sequence of well-defined steps for solving a problem in a systematic
manner. It is written in natural languages like English.
Advantages: i) Easy to write
ii) Human readable techniques to “understand logic”.
Disadvantages: i) Difficult to debug.
ii) Difficult to show branching and looping
Example: Print 1 to 20 numbers
Algorithm:
Step1: Initialize x as 0
Step2: Increment x by 1
Step3: Print x
Step4: If x is less than 20 then go back to step 2.
Q. Flowchart:
A flowchart is a pictorial or graphical representation of a process/Algorithm. Each step in the algorithm is
represented by a different symbol and contains a short description of the algorithm steps.
Advantages: i) Easy to draw
ii) Easy to understand the logic
iii) Easy to identify mistake by the non-computer person.
iv) Easy to show branching and looping
Disadvantages: i) Time consuming ii) Difficult to modify
iii) Very difficult to draw a flowchart for big or complex problems.
Page 69
Programming with C
Example: print 1 to 20
Start
Initialize x=0
Increment x by 1
Print x
x<20
stop
Flowchart Algorithm
1. It is a pictorial representation. 1. Step-by-step process
2. Solution is shown in graphical format. 2. Solution is shown in non-computer
3. Easy to understand language.
4. Easy to show branching and looping 3. Difficult to understand
5. Difficult to debug the errors 4. Difficult to show branching and looping
6. Flowchart for big problem is impractical. 5. Algorithm can be written for any problem
6. It is difficult to write algorithm as
compared to flowchart.
Page 70