C Project Work 3rd-Page
C Project Work 3rd-Page
PROJECT WORK ON C
1.1 INTRODUCTION TO C
C programming is a general-purpose, procedural computer
programming language developed in 1972 by Dennis M. Ritchie at
the Bell Telephone Laboratories to develop the UNIX operating
system. C is the most widely used computer language.
Why to Learn C Programming?
C programming language is a must for students and working
professionals to become a great Software Engineer specially when
they are working in Software Development Domain. I will list down
some of the key advantages of learning C Programming:
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Applications of C Programming
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a
system development language because it produces code that runs
nearly as fast as the code written in assembly language. Some
examples of the use of C are -
⏯ Operating Systems
⏯ Language Compilers
⏯ Assemblers
⏯ Language Interpreters
⏯ Modern Programs
⏯ Databases
⏯ Utilities
1
C Basic Commands
Following are the basic commands in C programming language:
printf(“Hello_World!
This command prints the output on the screen.
“);
2
1.2 Algorithm and Flowchart
Definition of algorithm and flowchart as below:
Algorithm
It is well known that the programs are used to solve the various kinds
of problems by computerized technique. The algorithm is a step-by-
step procedure that guarantees a solution if followed correctly.
Flowchart
The pictorial representation of a sequence of events that describe
activities required in the program to solve the particular problem is
called a flowchart. Therefore, a flowchart is a pictorial representation
of an algorithm.
3
1.3 Structures of C Program
Structure is a group of variables of different data types represented
by a single name. Let’s take an example to understand the need of a
structure in C programming.
4
C Structure example
Let's see a simple example of structure in C language.
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Santosh Aryal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 Id : 101
employee 1 Name : Santosh Aryal
5
1.4 Data Type in C
Data type is an instruction that is used to declare the category or
type of variable being used in the program. Any variable used in
the program must be declared before using it.It determines the way
a computer organizes data in memory. It determines how much
space it occupies in storage.
Void : Void data type has no values. It is used as return type for
function that does not return a value.
Example of Data types in c
#include <stdio.h>
int main()
{
int a = 1;
char b = 'G';
double c = 3.14;
printf("Santosh Aryal!\n");
// printing the variables defined
// above along with their sizes
printf("Hello! I am Santosh Aryal. My value is %c and "
"my size is %lu byte.\n",
b, sizeof(char));
// can use sizeof(b) above as well
printf("Hello! I am Santosh Aryal. My value is %d and "
6
"my size is %lu bytes.\n",
a, sizeof(int));
// can use sizeof(a) above as well
printf("Hello! I am Santosh Aryal."
" My value is %lf and my size is %lu bytes.\n",
c, sizeof(double));
// can use sizeof(c) above as well
printf("See you! Have a good day. :)\n");
return 0; }
Output:
Hello Santosh Aryal!
Hello! Santosh Aryal. My value is G and my size is 1 byte.
Hello! Santosh Aryal. My value is 1 and my size is 4 bytes.
Hello! Santosh Aryal floating point variable My value is 3.140000
and my size is 8 bytes.
See you! Have a good day. :)
7
1.5 Arithmetic and Logical Operator in C
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical
operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic
operators are of two types:
a) Unary Operators: Operators that operate or work with a single
operand are unary operators. For example: Increment(++) and
Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two
operands are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For
example, checking if one operand is equal to the other operand or
not, whether an operand is greater than the other operand or not, etc.
Some of the relational operators are (==, >= , <= )(See this article for
more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combine two or more
conditions/constraints or to complement the evaluation of the
8
original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C
or C++ returns true when both the conditions under consideration
are satisfied. Otherwise, it returns false. Therefore, a && b returns
true when both a and b are true (i.e. non-zero)(See this article for
more reference).
(4 != 5) && (4 < 5); // true
4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then the
calculation is performed on the operands. Mathematical operations
such as addition, subtraction, multiplication, etc. can be performed at
the bit-level for faster processing. For example, the bitwise
AND represented as & operator in C or C++ takes two numbers as
operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1. (See this article for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
9
Arithmetic Operators in C
Example
Try the following example to understand all the arithmetic operators
available in C −
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
10
Logical Operators in C
Example
Try the following example to understand all the logical operators
available in C −
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}
}
Output:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
11
1.6 Control Structures in Programming Languages
# include<stdio.h>
# include<conio.h>
void main( )
{
int a,b;
clrscr( );
printf(“Enter Two numbers:”);
scanf(“%d%d”, &a,&b);
if( a>b )
printf(“\n %d is largest number”,a);
else
printf(“\n %d is largest number”,b);
getch( );
}
Output:
Enter Two numbers: 13 30
30 is largest number
# include<stdio.h>
# include<conio.h>
main( )
{
int n;
clrscr( );
printf(“Enter a number :”);
12
scanf(“%d”, &n);
if( (n%2)==0 )
printf(“\n The given number is EVEN ”);
else
printf(“\n The given number is ODD ”);
getch( );
}
Output :
Run 1 :
Enter a number : 24
The given number is EVEN
Run 2: /* that means one more time we run the program */
Enter a number : 17
The given number is ODD
13
1.7 Array of Structures in C
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
15
1.8 Array and Structure
String and Character Array
String is a sequence of characters that are treated as a single data item
and terminated by a null character '\0'. Remember that the C
language does not support strings as a data type. A string is actually a
one-dimensional array of characters in C language. These are often
used to create meaningful and readable programs.
If you don't know what an array in C means, you can check the C
Array tutorial to know about Array in the C language. Before
proceeding further, check the following articles:
C Function Calls
C Variables
C Datatypes
C Syntax Rules
For example: The string "home" contains 5 characters including the '\
0' character which is automatically added by the compiler at the end
of the string.
// valid
// Illegal
char str[4];
str = "hello";
16
String Input and Output:
But scanf() function, terminates its input on the first white space
it encounters.
edit set conversion code %[..] that can be used to read a line
containing a variety of characters, including white spaces.
The gets() function can also be used to read character string with
white spaces.
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str);
printf("%s", str);
char text[20];
gets(text);
printf("%s", text);
The following are the most commonly used string handling functions.
Method Description
17
strcat() It is used to concatenate(combine) two strings
strcat() function in C:
Syntax:
strcat("hello", "world");
strcat() will add the string "world" to "hello" i.e ouput = helloworld.
int j = strlen("studytonight");
printf("%d %d",j,i);
18
12 -1
strcpy() function:
#include<stdio.h>
#include<string.h>
int main()
strcpy(s1, "StudyTonight");
strcpy(s2, s1);
printf("%s\n", s2);
return(0);
Study Tonight
strrev() function:
19
Code snippet for strrev():
#include <stdio.h>
int main()
char s1[50];
gets(s1);
return(0);
20
1.9 C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks
are performed more easily with pointers, and other tasks, such as
dynamic memory allocation, cannot be performed without using
pointers. So it becomes necessary to learn pointers to become a
perfect C programmer. Let's start learning them in simple and easy
steps.
As you know, every variable is a memory location and every memory
location has its address defined which can be accessed using
ampersand (&) operator, which denotes an address in memory.
Consider the following example, which prints the address of the
variables defined −
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
C - Strings
Strings are actually one-dimensional array of characters terminated by
a null character '\0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting
of the word "Hello". To hold the null character at the end of the array,
the size of the character array containing the string is one more than
the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the
above statement as follows −
21
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in
C:
C - Structures
Arrays allow to define type of variables that can hold several data
items of the same kind. Similarly structure is another user defined
data type available in C that allows to combine data items of different
kinds.
Structures are used to represent a record. Suppose you want to keep
track of your books in a library. You might want to track the
following attributes about each book −
Title
Author
Subject
23
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member. The
format of the struct statement is as follows −
struct [structure tag] {
member definition;
member definition;
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal
variable definition, such as int i; or float f; or any other valid variable
definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is
optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access
operator (.). The member access operator is coded as a period
between the structure variable name and the structure member that we
wish to access. You would use the keyword struct to define variables
of structure type. The following example shows how to use a structure
in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
24
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Madhav Prasad Regmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Aashish Neupane");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Book 1 title : C Programming
Book 1 author : Madhav Prasad Regmi
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Aashish Neupane
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
25
1.10 C - Functions
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and all
the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide
up your code among different functions is up to you, but logically the
division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the actual
body of the function.
The C standard library provides numerous built-in functions that your
program can call. For example, strcat() to concatenate two
strings, memcpy() to copy one memory location to another location,
and many more functions.
A function can also be referred as a method or a sub-routine or a
procedure, etc.
Defining a Function
The general form of a function definition in C programming language
is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function
header and a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform
the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of
statements that define what the function does.
26
Example
Given below is the source code for a function called max(). This
function takes two parameters num1 and num2 and returns the
maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
27
Function Declarations
A function declaration tells the compiler about a function name and
how to call the function. The actual body of the function can be
defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as
follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their
type is required, so the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one
source file and you call that function in another file. In such case, you
should declare the function at the top of the file calling the function.
Calling a Function
For example –
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
28
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code.
While running the final executable, it would produce the following
result −
Max value is : 200
Function Arguments
29
to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it
means the code within a function cannot alter the arguments used to
call the function.
30
1.11 File Handling in C
There are many functions in the C library to open, read, write, search
and close the file. A list of file functions are given below:
Mode Description
32
w opens a text file in write mode
#include<stdio.h>
void main( )
{
FILE *fp ;
33
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Output
The content of the file will be printed.
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed
after performing all the operations on it. The syntax of fclose()
function is given below:
34
Writing File : fprintf() function
Syntax:
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf() function
Syntax:
Example:
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
36
Now open file from current directory. For windows operating system,
go to TC\bin directory, you will see emp.txt file. It will have
following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000
37
CHAPTER TWO:
RESULTS AND DISCUSSION
It was identified early on that testing and evaluation of the source
code would determine a successful program. Each group member
was responsible for checking their code construction so that final
compilation could run smoothly.
38
CHAPTER THREE:
SUMMARY AND
CONCLUSION
Summary
Conclusion
Though the common trend among us (students) is to take these
academic activities as a formal job (which is correct for a different
point of view), I really enjoyed doing this project. I started the work
the first day I got my copy of assignment and completed 90%
excluding printing and binding jobs within a week and spent some
days on its moderation. Now, I am satisfied with my project and the
report.
Time management was crucial for this project. With the desire to
create a working program and with the limitations of time, it was
decided to create a simpler version that would work but still prove
the principle and solve the problem.
39
Bibliography
JAAVAPoints . (2079, 04 26). Retrieved 04 26, 2079,
from JAAVAPoints :
https://www.javatpoint.com/array-of-structures-in-c
40