Ravis - Programming in C
Ravis - Programming in C
By
ROM CD’s
ROM stand for Read Only Memory. ROM is used in A CD is a portable secondary storage medium.
personal computers for storing start-up instructions. It Various types of CDs are available: CD-R and
is used for BIOS test or POST. ROMs can be written CD-RW. Once created Data stored on CD-R
only at the time of manufacture. (CDRecordable) disc can’t be changed. A
PROM: CDRewritable (CD-RW) disc can be erased and
A Programmable ROM (PROM), is also non-volatile reused. . CD-RW drives are used to create and read
and can be programmed only once. both CD-R and CD-RW discs.
EPROM: Erasable Programmable Read Only
Memories can be written electrically. Its data can be Tape drive
erased by using ultraviolet light. A tape drive is a data storage device that reads and
EEPROM: Electrically Erasable Programmable writes data on a magnetic tape. Magnetic tapes are
Read Only Memory (EEPROM can be written onto generally used for backup. Magnetic tapes are
by electrical signals. Its data can be erased by cheap but has a long stability.
electrical signals.
USB Flash drive:
It is a small, portable flash memory card. It can be
plugged into a computers USB port. It is easy to
carry and more durable. Because it cannot contain
any internal moving parts. It is also are called pen
drive.
Process(or) management
A process is a program in execution. The operating
system decides which process to run. It also assigns
priority to the processes.
***
3. Problem-oriented languages:
These languages provide pre-programmed
functions. The user need to write those
functions. MATLAB is an example of this
1. Procedural programming languages: category. MATLAB is very popular
In procedural programming, each program can be language among scientists and engineers.
divided into small procedures (subroutines or
functions). This style is easier for programmers. ***
There are mainly three types: Translator, Loader, Linker
Algorithmic languages: In this style, the
programmer must specify the steps, which the A Translator is a program that translates
computer has to follow. It uses top-down the source program into machine
approach. Languages like C, COBOL, understandable form.
PASCAL and FORTRAN fall into this A Linker is a program that combines the
category. machine language program with other
[Top-down approach: It is a technique of programs in the library.
programming that first defines the overall outlines of A Loader is a program that loads the
the program and then fills in the details.] executable program’s from secondary
memory into primary memory and prepares
Object Oriented languages: Object-oriented them for execution and starts the execution.
programming depends on software objects.
Data and associated operations are combined ***
into objects. This approach provides reuse of
code and design. C++, JAVA, SMALLTALK,
etc. are some examples of object-oriented
languages
Differences:
1. A Compiler takes the entire program as its
input. 3. Semantic analysis: The semantic analysis
2. An Interpreter takes Instruction by instruction phase further analyses the parsed
as its input. statements.
3. A Compiler generates Object Code
4. An Interpreter does not generate any object 4. Intermediate code generation and
code. optimization: Many compilers produce an
5. A Compiler requires more memory intermediate form of code for optimization.
6. An Interpreter requires less memory. The intermediate code may be is in
assembly language.
***
Compiling, Linking and Loading a Program 5. Code generation: This is the final phase
that converts the intermediate code into
A Compiler translates a program written in a source target machine code. It also performs
language into target language. The compilation linking and loading step to generate an
process can be divided into the following phases: executable program.
1. Lexical Analysis
2. Syntax Analysis ***
3. Semantic Analysis
4. Intermediate code generation
5. Code Generation
***
5. Testing:
The Testing phase detects errors in the new software
and rectify those errors. The testing phase performs
verification and validation.
Verification is the process of checking the
software based on some specifications.
Validation involves testing the product to
verify whether it meets the user requirements.
6. Deployment:
The newly developed software need to be installed in
its target environment. It hand overs the software
documentation to the users. It also gives training to
the users.
7. Maintenance:
In this phase, developed software becomes
operational. It requires a continuous support.
***
Example:
Write an algorithm for finding the sum of any two
numbers.
Step 1. START
Step 2. PRINT “ENTER TWO NUMBERS”
Step 3. INPUT A, B ***
Step 4. C A + B
Step 5. PRINT C
Step 6. STOP
Developing programs in C
There are mainly three steps in developing a program
in C:
1. Writing the C program
2. Compiling the program
3. Executing the program
***
Header files
A header file is a file that has C declarations and
macro definitions. It provides the required
information for the pre-processor and compiler to Preprocessor directives:
process the program. In C all the lines that begin with # are known as pre-
The ISO C contains the following header files: processor directives. A Pre-Processor is a program
assert.h signal.h errno.h stddef.h that processes the directives before the compilation
complex.h stdarg.h fenv.h stdint.h process.
ctype.h stdbool.h float.h stdio.h Global declarations:
inttypes.h stdlib.h locale.h time.h The global declaration contain the global variables.
iso646.h string.h math.h wchar.h The variables that are available for all the functions
limits.h tgmath.h setjmp.h wctype.h in the program are known as global variables.
There are two ways of including files in C program: Main program section:
1. #include<filename> All the functions in a c program can be divided
This method tells the preprocessor to look for into two sections:
the file in the default location. This method is Local definition
used to include standard headers such as Statements.
stdio.h or stdlib.h. Local definitions:
2. #include “file name” Local definitions are at the beginning of the
This method tells the preprocessor to look for functions. Local definitions are available within
the file in the current directory first, then that function only.
in the predefined locations. This method is Statements:
used to include programmer created files. Statement section consists of the executable
instructions.
***
***
Unit – II getchar(): -
The getchar() is a non-formatted Input function. It
Input-Output can read a single character at a time. It has the
following format:
Input-Output: char_variable = getchar();
Generally, The keyboard and the screen are the Example:
standard input and output devices in programming. int ch;
All input and output is performed with streams. A ch = getchar();
Stream is a sequences of bytes. In input operations, The getchar()function reads a character and places
the bytes flow from keyboard to main memory. In it in the memory location “ch”
output operations, bytes flow from main memory to
screen. putchar():-
The putchar() is a non-formatted output function. It
In C, the input and output are managed through can displays a single character at a time on the
standard streams. Those standard streams are: monitor screen. It has the following format:
1. stdin : Standard Input Stream putchar(char_variable);
2. stdout : Standard Output Stream Example:
int ch = ‘x’;
3. stderr : Standard Error Stream
puchar(ch)’
When a program execution begins, these three
The putchar() function displays the character stored
streams are connected to the program automatically.
in the memory location “ch”.
Normally, the standard input stream is connected to
the keyboard and the standard output stream is
1. Write a C program to display a keyed in
connected to the screen. A third stream, the standard
character.
error stream, is connected to the screen.
Solution
#include<stdio.h>
I/O Functions in C
main()
C has a number of standard functions to perform input
{
and output operations.
int ch;
In C, The input/output (I/O) functions are of two
ch=getchar();
types:
putchar(ch);
1. Non-formatted input/output functions
return 0;
2. Formatted input/output functions. }
Non-formatted input/output functions : I/O
The I/O statements that does not use format codes Input A
are known as Non-Formatted I/O functions. Output A
These functions can handle one character at a
time. There are two important non-formatted I/O
functions in C:
1. getchar()
2. putchar()
Escape sequences
Escape sequences are the control codes that can be
used to control the output as required. C has the
following escape sequence characters:
Code Meaning
Code Meaning
\a Ring bell (a is for alert) Selection Statements
\? Question mark Selection statements are of three types:
\b Backspace One-way Selection Statements These
\r Carriage return statements can do a particular thing or they
\f Form feed do not do anything. In C a simple if
\t Horizontal tab \ statement can do this.
\v Vertical tab Two-way Selection Statements These
\0 ASCII null character statements can do one thing or another
\\ Backslash thing. In C an if..else statement can do this.
\” Double quote Multi-way Selection Statements These
\’ Single quote statements can do one of many different
\n New line
things. In C an else..if ladder/nested if
\o Octal constant
statements can do this.
\x Hexadecimal constant
Write a program to find the largest among three Write a C program to check whether a number
numbers. given by the user is odd or even.
#include <stdio.h> #include <stdio.h>
main() int main()
{ {
int a, b, c, max; int n,r;
printf(“\nEnter 3 numbers”); printf(“\nEnter the number”);
scanf(“%d %d %d”, &a, &b, &c); scanf(“%d”, &n);
max=a; r=n%2;
if(b>max) if(r==0)
max=b; printf(“EVEN”);
if(c>max) else
max=c; printf(“ODD”);
printf(“Largest No is %d”, max); return 0;
getche(); }
return 0;
}
}
getche();
return 0;
}
***
Bounded loops can be used when you know how While loop
many times you need to loop. C provides one while statement is a pre-test loop. First, it verifies
bounded loop: for loop. the test expression before every iteration of the
loop.
Unbounded loops can be used when you does not It has the following syntax:
know how many times to loop. C provides two types
of unbounded loops: while loop and do...while loop. Initialization;
while (TestExpr)
A loop can be either a {
pre-test loop or stmT
post-test loop. ...
In a pre-test loop, first, the condition is checked. If ...
the test condition is true, then only it executes the Updating
statements of that loop. }
This process is repeated till the test expression
becomes false. In a pre-test loop, the statements may stmT will be executed repeatedly till the value of
not be executed even once. TestExpr becomes 0 (FALSE).
The following figure shows the execution of
In the post-test loop, first the code is always “while” loop:
executed once. The test condition is tested at the end
of the loop. If the test condition is true, the loop
repeats. if it is false the loop terminates.
if(isspace(ch))
words++;
chars++;
}
printf("\nNumber of Lines : %d", lines+1);
printf("\nNumber of Words: %d", words+1);
printf("\nTotal Number of Characters: %d", chars);
getch( );
return 0; Statements
} Block
I/O
Enter the required no. of lines:
This is a Test
This is a Test
This is a Test ^Z
Number of Lines : 3
Number of Words : 12
Number of Characters: 44
I/O:
Enter the number of terms: 5
Sum is 15
Example:
Write a C program to print the numbers from 1 to 3.Write a C program to calculate the factorial of
10. the given number.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> main()
main() {
{ int n, i, f=1;
int i; printf(“\n Enter the number: ”);
clrscr(); scanf(“%d”,&n);
for(i = 1; i <= 10; i++) for(i=1;i<=n;++i)
printf(“%d”,i); f*=i;
return 0’ printf(“\n Factorial is %ld”,f);
} getche();
return 0;
I/O }
1
2 I/O:
3 Enter the number: 5
4 Factorial is 120
5
6
7
8
9
10
2. return statement:
The return type is used in a function definition to set
its returne value.
The return statement has two forms.
(1) return;
This format can be used for the functions
which return a blank control without value.
(2) return expression;
This format can be used for the functions which
return a particular value.
Write a C program to search for an element in the Write a C program to sort the array elements
array. using bubble sort.
#include <stdio.h>
#include <stdio.h> #include<conio.h>
#include<conio.h> #include <stdlib.h>
#include <stdlib.h> main()
main() {
{ int a[30],n,i,j,temp;
int a[30],n,i,key, FOUND=0; clrscr();
clrscr(); printf(“\n How many numbers”);
printf(“\n How many numbers”); scanf(“%d”,&n);
scanf(“%d”, &n); if(n>30)
} Example:
} arr [0][0] = 1;
printf(“\n The numbers in sorted order \n”); arr [0][1] = 2;
for(i=0 ; i<n; ++i) arr [0][2] = 3;
printf(“\n %d”, a[i]); arr [1][0] =4;
getche(); arr [1][1] = 5;
return 0; arr[1][2] = 6;
} arr [2][0] = 7;
arr [2][1] = 8;
Multidimensional Arrays arr[2][2] = 9;
Strings
printf("\n Matrix a is:\n");
One-dimensional Character Arrays
for(i = 0; i < row1; i++)
A String is an arrays of characters.
{
In C, a String can be terminated by a null
for(j = 0; j < col1; j++)
character(\0).
printf("%3d", a[i][j]);
printf("\n");
Declaraing a String
}
Strings can be declared like one-dimensional
arrays. For example:
printf("\n Matrix b is: \n");
char name[30];
for(i = 0; i < row2; i++)
char address[80];
{
for(j = 0; j < col2; j++)
String Initialization
printf("%3d", b[i][j]);
Strings allow a shorthand initialization, for
printf("\n");
example,
}
char str[9] = “I like C”;
char msg[] = “Hello”;
if(col1 == row2)
{ Printing Strings
printf("\n Multiplication is possible and the Result is The format code ‘%s’ can be used to print strings
as follows \n"); by using printf(). For For example,
for(i=0; i<row1; i++) printf(“%s”,name);
for(j=0; j<col2; j++)
{ Reading a String
m[i][j] = 0; The format code %s can be used to read a string
for(k = 0; k < col1; k++) with scanf().
m[i][j] += a[i][k] * b[k][j]; For example:
} scanf("%s', &name);
Write a C Program to illustrate Strings:
for(i = 0; i < row1; i++) #include<stdio.h>
{ main()
for(j = 0; j < col2; j++) {
printf("%3d", m[i][j]); char str[50];
printf("\n"); printf(“Enter a string”);
} scanf(“%s”,str);
} printf(“The string was :%s\n”,str);
return 0;
else }
printf("\n Multiplication is not possible");
getche(); I/O:
return 0; (a) Enter a string: Ritchie
} The string was :Ritchie
***
USING FUNCTIONS
You can use a function by calling it. A function
which calls another function is known as a Calling
Function. A function which responds to a function
call is known as a Called function.
/* Declaring a Pointer:
output The syntax for declaring a pointer variable is
=========== datatype * pointer_variable;
Enter a Number : 4
Factorial of 4 is = 24 Example:
*/ char *ptr;
Example:
#include <stdio.h>
int swap(int*, int*);
int main()
{
int x=5,y=10; For example:
void swap(int *,int *); #include<stdio.h>
printf(“%d %d\n”,x,y); main()
swap(&x, &y); {
printf(“%d %d\n”,x,y); int a[]={1,2,3,4,5};
return 0; int b[]={10,20,30,40,50};
} int c[]={100,200,300,400,500};
int *p[3];
int i,j;
p[0]=a;
p[1]=b;
p[2]=c;
***
Structures S2.sno=201;
A structure is a collection of variables under a single S2.sname=”Bobbage”;
name. These variables can be of different types S2.marks=654;
printf("\n sno \t name \t s1 \t s2 \t s3 \t total \t avg The members of a union can be accessed by using
:\n"); the ‘.’ the ‘dot operator’. It has the following form:
for(i=0;i<10;i++) < union_variable >.< member_name > ;
{
printf("\n%d \t %s \t %d \t %d \t %d \t %d \t%f Example:
\n", student1[i].sno, student1[i].sname, student1[i]. e1.eno=101;
s1, student1[i].s2, student1[i].s3, student1[i].total, e1.ename=”Ritchie”;
student1[i].avg); e1.salary=25000;
A union can be declared by using the keyword printf("\n\t Employee Number = %d", e1.eno);
"union". printf("Enter Employee Name:");
scanf("%s",e1.ename);
Declaring a Union and its Members: printf("\n\t Employee Name = %s", e1.ename);
The general format for declaring a union is :
union tag_name printf("Enter Employee Salary:");
{ scanf("%f",e1.salary);
data type member1;
data typemember2; printf("\n\t Employee Salary = %f", e1.salary);
.
. getche();
data type memberN; return 0;
}variable1,variable2,variable3,…,variableX; }
Example:
union emp
{
int eno;
char ename[10];
float salary;
} e1;
Write a Program to illustrate working with text The functions fread() and fscanf() can be
files used to read a file sequentially.
#include<stdio.h> These functions can move the file position
#include<process.h> indicator to the first byte of the next record.
void main() { fwrite() function can be used to write to a
FILE *fp1, *fp2; file.
char a; The feof() function can be useful to indicate
clrscr(); the end of the fie.
fp1 = fopen("test.txt", "r");
if (fp1 == NULL) { The following program illustrates Files of Records:
printf("cannot open this file"); #include<stdio.h>
exit(1); #include <stdlib.h>
} #include <string.h>
fp2 = fopen("test1.txt", "w");
if (fp2 == NULL) { struct person {
printf(" Cannot open this file"); char *name;
fclose(fp1); int code;
exit(1); int number;
} };
do { main()
a = fgetc(fp1); {
if(a >= 'a' && a <= 'z') FILE *fp, *fp1;
{ struct person p1,p2;
a = toupper(a);
}
Renaming a File
The rename() function changes the name of an
existing file. It has the following format:
int rename(const char *oldname, const char
*newname);
.#include <stdio.h>
int main(void)
{
char oldname[80], newname[80];
printf(“File to rename:”);
gets(oldname);
printf(“New name:”);
gets(newname);
if(rename(oldname, newname) == 0)
printf(“Renamed %s to %s.\n”, oldname, newname);
else
perror(“rename”);
return 0;
}
*****
[END]
PROGRAMMING IN C Unit-2
Question Bank
1. Write about the I/O functions in C.
Unit-1 2. Discuss about the escape sequence
11 characters.
1. Discuss about the classification of Computers. 3. Write about the selection statements in C.
2. Write about the anatomy of a Computer. 4. Explain about the conditional operator
3. Write about the Memory Hierarchy. 5. Write about the switch statement
4. What is O.S? Explain its functions. 6. Differentiate between while and do
5. Discuss the generations of programming 7. Explain about for loop. Write a C program
languages. to find whether the given number is
6. Differentiate between Compiler and palindrome.
Interpreter 8. What is goto statement
7. Explain the steps in developing a Program? 9. Differentiate between break and continue.
8. Write about the Software Development Life 10. What is an array? Expain how to declare
Cycle. and initialize a 1D array.
9. What is Algorithm? Explain different ways of 11. Explain the Multi-dimensional arrays in C.
stating an algorithm. 12. Explain the functions available with
10. What do you mean by Structured <ctype.h>
Programming? 13. What is a String? Explain about the string
11. What is C? Explain how to develop a C manipulation functions
Program
12. Explain the parts of a simple C program. Unit-3
13. Write about the comments in C
14. Write about the program statements
15. Explain about C Tokens? 1. What is a Function? Explain the elements of
16. What are the keywords in C? functions.
17. Explain the rules of identifiers? 2. What are the types of functions? Explain.
18. Explain about the data types in C 3. Differentiate Call-by-Value Vs Call-by-
19. What are the types of constants? reference.
20. Write about different operators in C. 4. Write about the storage classes
21. Explain the rules of evaluating an arithmetic 5. What is an inline function?
expression. 6. What is Recursion? Explain about the
22. What is type conversion? recursive functions.
7. What is a Pointer? Explain
8. What is an array of pointers
9. What is dynamic memory allocation
Unit-4
C Programs