[go: up one dir, main page]

0% found this document useful (0 votes)
24 views86 pages

All Rights Reserved To Svti 1

Uploaded by

bachaparty346
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views86 pages

All Rights Reserved To Svti 1

Uploaded by

bachaparty346
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Table of Contents

Introduction to Computer Language .................................................................... 1

C Building Blocks .............................................................................................. 12

C Input Output and Operations .......................................................................... 20

OPERATORS USED IN C ............................................................................... 26

CONTROL STRUCTURE ............................................................................... 34

ARRYS IN C PROGRAMING ........................................................................ 42

SRTING & I/O MANIPULATION FUNCTION ............................................. 48

USER DEFINE FUNCTIONS ........................................................................... 55

POINTTER IN C PROGRAMMING ................................................................ 64

STRUCTURE IN C PROGRAMMING ............................................................ 70

C Files I/O: Create, Open, Read, Write and Close a File .................................. 74

Date and Time Function in C Programming ..................................................... 83

ALL RIGHTS RESERVED TO SVTI 1


Chapter 1
Introduction to Computer Language
Introduction
In basic term, a computer is an electronic device that processes data,converting
it into information that is useful to people.

Hierarchy of Computer

Hierarchy of computer

Program & Software


Program: It is the set of instructions to be given to computer for processingand
desired results.
Software: Set of program(s).

What is a programming language?


A programming language is a set of rules that provides a way of telling a computer what
operations to perform.
A programming language is a set of rules for communicating an algorithm
It provides a linguistic frameworkfor describing com-putations

A programming language is a notational system for describing computation in a


machine-readable and human-readable form.
A programming language is a tool for developing executable models for a class of
problem domains.

• English is a natural language. It has words, symbols and grammatical rules.


• A programming language also has words, symbols and rules of grammar.
• The grammatical rules are called syntax.
• Each programming language has a different set of syntax rules.

Computer Language
A computer language is a set of rules and conventions used to convey the
information to a computer.

ALL RIGHTS RESERVED TO SVTI 2


An artificial language in which computer programmer writes instructions for
computer to execute, these instructions translated into machine language and then
executed by a computer.

Levels of Computer Languages


a. Machine Language
The native tongue of a computer is the Machine Language. Each MachineLanguage
instruction is a binary string of 0’s and 1’s that specifies an operation and identifies
the memory cells involved in that operation.

b. Low Level Language


In the Low-Level Language, Machine Language is still used by the computer as it
processes data, but Low-Level Language software first translate the specified
operation symbol onto its Machine Language equivalent.
Example is Assembly Language.

c. High Level Language


High Level Language is a programming language where an instruction resembles
everyday language. Instructions are given to a computer by usinga convenient letters,
symbols or English text rather than by using 1’s and 0’s code that the computer
understands.
Example is C, BASIC and Pascal etc.

Types of Programming Language

1. First Generation Languages


Machine language
a. Operation code – such as addition or subtraction.
b. Operands – that identify the data to be processed.
c. Machine language is machine dependent as it is the only language the computer can
understand.
d. Very efficient code but very difficult to write.

2. Second Generation Languages


Assembly languages
a. Symbolic operation codes replaced binary operation codes.
b. Assembly language programs needed to be “assembled” for execution by the computer.
Each assembly language instruction is translated into one machine language instruction.
c. Very efficient code and easier to write.

3. Third Generation Languages


Closer to English but included simple mathematical notation.
a. Programs written in source code which must be translated into machine language
programs called object code.
b. The translation of source code to object code is accomplished by a machine language
system program called a compiler.

4. Fourth Generation Languages

ALL RIGHTS RESERVED TO SVTI 3


a. Alternative to compilation is interpretation which is accomplished by a system
program called an interpreter.
b. Common third generation languages
• FORTRAN
• COBOL
• C and C++ ◦
• Visual Basic
5. Fifth Generation Languages
a. A high level language (4GL) that requires fewer instructions to accomplish a
task than a third generation language.
b. Used with databases
• Query languages
• Report generators
• Forms designers
• Application generators
c. Declarative languages
d. Functional(?): Lisp, Scheme, SML
• Also called applicative
• Everything is a function
e. Logic: Prolog
• Based on mathematical logic
• Rule- or Constraint-based

Introduction to C Language
C is a general-purpose, imperative computer programming language, supporting
structured programming, lexical variable scope and recursion, while a static type system
prevents many unintended operations.
C programming language was developed in early 1970s by Dennis Ritchie at Bell
Laboratories. C Language in between the Low-Level Language and High- Level
Language. That’s why it is also called a Middle Level Language, since it was designed
to have both: a relatively good programming efficiency and relatively good machine
efficiency.

Why C is middle level language?


C is called middle-level language because it actually binds the gap between amachine
level language and high-level languages. A user can use c language to do System
Programming (for writing operating system) as well as Application Programming (for
generating menu driven customer billing system). That's why it is called the middle-
level language.

High level - Ada, Modula-2, Pascal, COBOL, FORTRAN, BASIC


Middle level - Java, C++, C, FORTH, Macro-assemble
Low level – Assembler

Why Learn C
1. Compact, fast and powerful
2. “Mid-level” language
3. Standard for program development (Wide Acceptance)

ALL RIGHTS RESERVED TO SVTI 4


4. It is everywhere (portable)
5. Supports modular programming style
6. Useful for all applications
7. C is native language of Unix
8. Easy to interface with System devices/assemble routines

Why use C Language?


Mainly because it produces code that runs nearly as fast as code written in assembly
language. Some examples of the use of C might be:
1. Operating Systems
2. Language Compilers
3. Assemblers
4. Text Editors
5. Print Spoolers
6. Network Drivers
7. Modern Programs
8. Data Bases
9. Language Interpreters
10. Utilities

Flowchart In Programming
A flowchart is a diagrammatic representation of an algorithm. A flowchart can be helpful for

ALL RIGHTS RESERVED TO SVTI 5


both writing programs and explaining the program to others.

Examples of flowcharts in programming


1.Add two numbers entered by the user.

What is Translators? Different type of translators


a. A program written in high-level language is called as source code. To convert the source
code into machine code, translators are needed.

b. A translator takes a program written in source language as input and converts it into a
program in target language as output.
It also detects and reports the error during translatio0n.
1. Roles of translator are:
• Translating the high-level language program input into an equivalent machine language
program.
• Providing diagnostic messages wherever the programmer violates specification of the
high-level language program.

Different type of translators


The different types of translator are as follows:
a. Compiler
Compiler is a translator which is used to convert programs in high-level language to low-level
language. It translates the entire program and also reports the errors in source program
encountered during the translation.

ALL RIGHTS RESERVED TO SVTI 6


b. Interpreter
Interpreter is a translator which is used to convert programs in high-level language to low-
level language. Interpreter translates line by line and reports the error once it encountered
during the translation process.
It directly executes the operations specified in the source program when the input is given by
the user.
It gives better error diagnostics than a compiler.

Differences between compiler and interpreter

c. Assembler

Assembler is a translator which is used to translate the assembly language code into machine
language code.

ALL RIGHTS RESERVED TO SVTI 7


Integrated Development Environment (IDE)
1. IDE referred to as Programmer’s Platform.
2. Users of Turbo Pascal or Turbo basic will already be familiar with major
features of IDE.
3. It is a screen display with windows and pull-down menus.
4. The program listing, its output, error messages and other information are
displayed in separate windows.
5. You use menu selections (or key combinations) to invoke all operations
necessary to develop program, including editing, compiling, linking and
program execution.
6. You use menu selections (or key combinations) to invoke all.
7. You can even debug your program within IDE.

Files used in C Program Development


1. Library and Runtime Files
a. Various files are combined with your programs during linking. These files
contain routines for a wide variety of purposes.
b. They are stored in LIB subdirectory.

2. Library Files
a. Library files are group of precompiled routines for performing specifictasks. For
example, if a programmer uses a function such as printf ( )to displayed text on the
screen, the code to create the display is contained in a library file.
b. A library file has a unique characteristic: only those parts of it that arenecessary
will be linked to a program, not the whole file.

3. Header Files
a. The subdirectory called INCLUDE contains header files.
b. Header files can be combined with your program before it is complied,in the same
way that a typist can insert a standard heading in a business letter.
c. Each header file has a “. h” file extension

4. Programmer-Generated Files.
a. You can place the programs that you write in any subdirectory youchoose; for
instance, a subdirectory bin.

ALL RIGHTS RESERVED TO SVTI 8


Writing a Program in C Language:
/* First Program in C to display text on screen */

#include <stdio.h>
void main (void)
{
printf ( “ This is my first program in C Language.” ) ;
}

Comments in C
Line begin with /* and end with */ indicating that these two lines are comment.
Comments are used to document programs and improve readability.
Comments helps other people to understand your program.
Comments do not cause the computer to perform any action and are ignored by
compiler when C program is run.

a. Single line comment


// (double slash)
Termination of comment is by pressing enter key
b. Multi line comment
/*……….…….*/ This can span over to multiple lines
# include
a. Line begins with # is called “pre process directives”.
b. Not part of our program, it is instruction to compiler.
c. Tells the compiler to “include” the contents of a file.

<stdio.h>
a. Name of standard library file, stands for STanDard Input Output.
b. .h is extension called header file. Header file contains the information used by
compiler when compiling library function.
c. Stdio.h contains the functions that we want to use (e.g. in our program printf( ) function).

Header files
The files that are specified in the include section is called as header file
a. These are precompiled files that has some functions defined in them
b. We can call those functions in our program by supplying parameters
c. Header file is given an extension .h
d. C Source file is given an extension .c

Main Function main( )


a. main( ) is part of every C program.
b. ( ) parenthesis after main indicates that main is a “function”.
c. All C programs must have at least one function i-e main.
d. Main is the point from where the program execution begins.
e. This is the entry point of a program
f. When a file is executed, the start point is the main function
g. From main function the flow goes as per the programmer’s choice.
h. There may or may not be other functions written by user in a program

ALL RIGHTS RESERVED TO SVTI 9


i. Main function is compulsory for any c program
Printf Function printf()
a. Instructs the compiler to perform an action i-e to print on the screen the stringof
characters marked by quotation marks (“ ”).
b. Entire line including pritnf( ), its argument within parenthesis and semicolon is
called “statement”.

Saving the Program in C Language


a. After you have typed in the source file for the program, you should save it on
your disk or hard disk. To do this, select the Save option from the File menu.
You can also accomplish
b. In C language a new file is created by a temporary name untitled.c.
c. You can save your source file as first.c or first.cpp.
d. Saving the source file is not necessary before compiling and running your
program, but it is a good idea and programming practice.

The Basic Structure of C Program


1. Function Definition
a. All C Language programs are divided into units called "Functions".
b. A function in C will always a ( ) at its end. Main() is always be the first function to
be executed and is the one to which control is passed when theprogram is executed.
c. The word "void" preceding the "main" specifies that the function main( )will not
return a value. The second "void", in the parenthesis, specifies that the function
takes no arguments.

2. Delimiter
a. Following the function definition are the braces, which signals the
beginning and ending of the body of the function.
b. The opening brace " { " indicates that a block of code that forms a distinctunit is
about to begin.
c. The closing brace " } " terminates the block code.

3. Statement Terminator
a. The line in our program that begins with the word " printf " is an exampleof a
statement.
b. A statement in C Language is terminated with a semicolon " ; ".
c. The C Language pays no attention to any of the "White Space Character ":the carriage
return (newline), the Spacebar and the Tab key.
d. You can put as many or as few white spaces characters in your programas you like;
since they are invisible to the compiler.

4. The printf ( ) function


a. The program line printf ( " This is my first program in C Language. " );
causes the phrase in quotes to be printed on the screen.
b. The word printf is actually a function, just as " main " is a function name.Since "
printf " is a function, therefore it is followed by parenthesis.
c. C Language distinguishes between uppercase and lowercase letters, i.e C Language

ALL RIGHTS RESERVED TO SVTI 10


is case sensitive.
d. Thus the function PRINTF( ) and Printf( ) are not the same as the functionprintf( ).

Exploring the printf ( ) Function


The printf( ) function uses a unique format for printing constants and variables.
For example

#include<stdio.h>
void main (void)
{
printf ( “ I am %d years old.”, 20 ) ;
}

Output:
I am 20 years old
NOTE:
 The function printf( ) can be given more than one argument. For example in the
above program we have taken 2 arguments in the printf( ) function.
 The two arguments are separated by a comma.
 The printf( ) function takes the vales on the right of the comma and plugs it intothe
string on the left.
Format Specifier
The format specifier tells the printf( ) where to put a value in a string and what format
to use in printing the values.
In the previous program, the %d tells the printf( ) to print the value 20 as a decimal
integer.Then what will be the method of writing a character or floating point number?
Why not simply put the decimal integer into the original string as compared to the
format specifier?
List of Format Specifier for printf ( )
%c single character
%s string
%d signed decimal integer
%f floating point (decimal notation)
%e floating point (exponential notation)
%u unsigned decimal integer
%x unsigned hexadecimal integer
%o unsigned octal integer
l prefix used with %d, %u, %x, %o to specify long integer.
For example, %ld.
Using Format Specifier in printf
( )Program 1
#include<stdio
.h> void main
(void)
{
printf ( “ My name is %s and I am %d years old.”, “Ahmed”, 20 );
}
Output:
My name is Ahmed and I am 20 years old.

ALL RIGHTS RESERVED TO SVTI 11


Program 2

#include<stdio.h>
void main (void)
{
printf ( “ The letter %c is” , ‘ j ’ ) ;

printf ( “ pronounced as %s” , “ jay ” ) ;


}

Output: The letter j is pronounced as jay.

NOTE: In the above program, there are two different new things to note.
 First we have used %c for the printing of a character which is surrounded by single
quotes whereas %s is used for printing a string which is surrounded by double quotes.
This is how C Language recognizes the difference between a character and a string.
 Second thing to note is that even though the output statement is printed by two
separate program lines, it does not consists of two line of text on the output screen.
That is because printf( ) does not automatically prints a new line character at the end
of a line. So what to do for inserting a new line in a printf( ) statement?

ALL RIGHTS RESERVED TO SVTI 12


Chapter 2

C Building Blocks
Escape sequences
combinations consisting of a backslash (\) followed by a letter are called "escape
sequences."
To represent a newline, single quotation mark, or certain other characters, you mustuse
escape sequences. Escape sequences are non-printing characters.
\n new line
\t tab
\r carriage return
\a alert
\\ backslash
\” double quote

Variables and Constant


1. Variables may be the most fundamental aspect of any computer language.
2. A variable is a space in the computer’s memory set aside for a certain kind ofdata
and given a name for easy reference.
3. Therefore, variables are used so that the same space in memory can holddifferent
values at different times. (But one value at a time).
4. Variable names correspond to locations in computer memory.
5. Every variable has a name, type and value.
6. Data values processed in the program are stored in memory locations and
referenced through variables.

Variable is a reserved location


1. Same idea used in algebra: y = 3x +5x and y are the ‘variables’;
3,5 are the ‘constants’
2. Inside the computer:
a variable is a reserved location in memory, and holds data that areallowed
to change.

Variable Declaration
ALWAYS declare a variable before use!
Forgot? error messages … ALWAYS set
a variable’s value before use!
Forgot? starting value will be unpredictable…What
does ‘declaring’ a variable do?
Reserve a memory location that will store the value of the variable.Assign the
variable name to that location.

How to ‘declare’ Variables?


Any variable must be declared (defined) before it can be used in the program. The same
variable cannot be defined more than once within the same block. The generalform of a
variable declaration:
data_type variable_name ;

ALL RIGHTS RESERVED TO SVTI 13


Example: int counter;

Where? Declare variables at the start of a function, right after the opening brace {
Variables of the same type can be defined in one declaration:
data_type var_name1 , var_name2 , … ,
var_namen;

Assigning value to variable


A programmer can assign a unique value to the variable.
The general form of an assignment statement is
type var-name = value;
OR
var-name = value;

float hours; float


payrate; float
grosspay;int j;
hours = 40.0;
payrate = 20.00;
grosspay = hours * payratej = 5;
j = j + 1; }

NOTE: referencing a variable only "reads" it (non-destructive). Assigning to a


variable overwrites whatever was there (destructive).

Rules for Naming Variables in C


In C, variable names are built from:
a. the letters of the alphabet (A-Z, or a-z)
b. the digits 0 through 9
c. the underscore. (no other special characters!)

 A variable name must start with a letter or an underscore.


 Spaces are not allowed in variable name.
 Only the 32 characters of a variable name are significant.
 Identifiers are case sensitive: sum≠SUM≠Sum≠sUM
 A variable name must not be the same as a reserved word.

Reserved words / Key Words in C and C++


Certain words have a special meaning to the C or C++ compiler.They are
called reserved words or keywords.We should not try to use these words
as names of variables or functionnames in a program.The keyword list
for C contains 32 words.
Some Keywords in C and C++

ALL RIGHTS RESERVED TO SVTI 14


asm auto Double new switch
break case else operator template
catch char enum private this throw
class const extern protected try typedef
continue float for public union
default friend register unsigned
delete do goto return short virtual void
if signed volatile
inline sizeof static while
int struct
long
Variable Names

Valid variable Invalid variable Legal, badly-chosen variable names


names names
 totalArea  $product  l11 (is it L11, L1L, LL1, or LLL?)
 _main  int  x (what does it mean?)
 counter1  main  maximum_number_of_students_in_my_class
 isEmpty  not-this  a23456789_123456789_123456789_123456
 Count_trees  total%
 pNuts  19
 temp_in_F  3rd
 m_size  Student
score

Data Types or Types of Variables


Programming languages store and process data in various ways depending on thetype
of the data; consequently, all data read, processed, or written by a program must
have a type.
A data type is a set of values, and a set of operations on those values.

A data type is used to:


a. Determines how much storage space is allocated to variables.
b. Identify the type of a variable when the variable is declared.
c. Identify the type of the return value of a function
d. Identify the type of a parameter expected by a function.

Classifications of Data Types Fundamental or Built-in datatypes


1. void – used to denote the type with no values.
2. int – used to denote an integer type
3. char – used to denote a character type
4. float, double – used to denote a floating point type.

Derived data types


array, string, structure, Union, Enumeration.

ALL RIGHTS RESERVED TO SVTI 15


Data Type ranges
Type Memory use Ranges
Char 1 BYTE 0 to 255 (ASCII) - 128
a single byte(8 bits) and can store one character type data to 127
Int 2BYTE -32768 to 32767
an integer type is used to represent whole numbers within a
specified range of values.
Float 4BYTE 3.4E-32 to 3.4 E+38
single-precision floating point

Double 8BYTE 1.7E-308 to 1.7 E+308


double-precision floating point
Void 0 valueless

Character Types :
A single character can be defined as a character type data. Characters are usually stored in 8
bits of internal storage. The qualifier signed or unsigned may be explicitly applied to char.
While unsigned chars have values between 0 and 255, signed chars have values from -128 to
127.

Integer Types :
C has three classes of integer storage, namely short int, int, and long int, in both signed and
unsigned forms. The keywords signed and unsigned are the two sign qualifiers which specify
whether a variable can store positive or negative or both numbers. The keyword signed uses
one bit for a sign and 15 bits for the magnitude of the number in a 16-bit machine. The keyword
unsigned uses to store all the bits for the magnitude of the number and always positive.

Floating Point Types :


Floating point numbers are stored in 32 bits with 6 digits of precision. Floating point numbers
are defined in C by the keyword float. When the accuracy provided by a float number is not
sufficient, the type double can be used to define the number.

Double Point Types :


A double data type number uses 64 bits giving a precision of 14 digits. These are known as
double precision numbers. Remember that double type represents the same data type that float
represents but with a greater precision. To extend the precision further, we may use long double
which uses 80 bits.

Data Type example

TYPE EXAMPLES
Char ‘A’ ‘b’ ‘$’ ‘9’
Int 1 250 4500
Float 3.5 42.56 345.6789
Double 3.5647290… 486.145875...
Void Valueless

ALL RIGHTS RESERVED TO SVTI 16


 Characters are stored internally as integers.
 Characters are interpreted according to the character set.
 The most commonly used character set is ASCII.
 In the ASCII character set, A is represented by the number 65.

The following table shows the size and range of the type-specifiers on most common
implementations :

Working with variable


Program in c to initialized the variable

#include<stdio.h>
#include<conio.h>
void main(void)
{
int first,second,third;
first=10; second=10;
third=10;
printf(“%d, %d and %d ”,first,second,third);
}
Output:
10,10and10

ALL RIGHTS RESERVED TO SVTI 17


1. Write a program in C for three variables and display its addition.
#include<stdio.h>
#include<conio.h>
void main(void)
{
float a,b,c;
a=10.5;
b=20.3;
c=a + b;
printf("%f + %f = %f ", a, b, c);
}

2. Write a program in C for two variable and display its multiplication.

#include<stdio.h>
#include<conio.h>
void main(void)
{
float a,b,c;
a=10.5;
b=20.3;
c=a * b;
printf("%f * %f = %f ",a, b, c);
}

3. Write a program in C for two variables and display its division.

#include<stdio.h>
#include<conio.h>
void main(void)
{
float a,b,c;
a=10.5;
b=20.3;
c=a / b;
printf("%f / %f = %f ",a, b, c); }

4. Write a program in C for two variables and display its subtraction.

#include<stdio.h>
#include<conio.h>
void main(void)
{
float a,b,c;
a=10.5;
b=20.3;
c=a - b;
printf("%f - %f = %f ",a, b, c);
}

ALL RIGHTS RESERVED TO SVTI 18


5. Write a program in C for subject marks and find its percentage.
#include<stdio.h>
#include<conio.h>
void main(void)
{
int obt, total;
obt =250;
total =300;
float per =obt *100 / total;
printf("obt %d * 100 / total %d = per%% %.3f " ,obt, total, per);
}
6. Write a program in C for radius and pi for area of circle.
#include<stdio.h>
#include<conio.h>
void main(void)
{
float radius = 2.3;
float pi =3.14;//area of circle = pi (r*r)
float area = pi * (radius) *(radius);
printf(" the area of circle %f ", area);
}

7. Write a program in C for side of Square and find its Area.


#include <stdio.h>
void main(void)
{
Int side = 4;
int area = side * side ; //area of square A=s*s
printf("area of square %d ", area);

8. Write a program in C for length and width of rectangle and find its Area

#include <stdio.h>
void main(void)
{
int L = 2;
int w = 4;
int area = L * w;
printf("area of square %d ", area);

ALL RIGHTS RESERVED TO SVTI 19


9. Write a program in C using format specifier and variables

// program using variables


void main (void)
{
int rollno; char
section;
float gpa = 3.25;
rollno = 100;
section = ‘A’;
printf (“ My name is %s. My Roll no is %d.”, “Ahmed”, rollno );printf (“
My section is %c and my GPA is %f.”, section, gpa);
}

Output:
My name is Ahmed. My Roll no is 100. My section is A and my GPA is3.25.

ALL RIGHTS RESERVED TO SVTI 20


Chapter 3
C Input Output and Operations
 Input means to provide the program with some data to be used in the
program.
 Output means to display data on screen or write the data to a printer or a
file.

C programming language provides many built-in functions to read any given input
and to display data on screen when there is a need to output the result.

scanf() and printf() functions


The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to takeinput
from user respectively.
#include<stdio.h>

void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}

scanf( ) FUNCTION
scanf function allows the programmer to accept the input from a keyboard.
scanf( ) allows us to enter data (at run time) from keyboard that will be formatted in
a certain way.
Syntax:
scanf (“format control string”, &variable list);
For example:
scanf ( “ %s %d %f”, &name, &age, &per );

ALL RIGHTS RESERVED TO SVTI 21


Here is a new symbol:
& ( Address Operator )
The format control string indicates the type of data that should be input by the
user.
Format control string Data Type
%c character
%d integer
%f float
%lf double

The ampersand (&) is called the address operator in C.


This is placed before the variable name in a scanf( ).
The address operator tells scanf( ) the location in memory in which the variable will
be stored. The computer then stores the value of the variable at that location.

scanf ( )
Examples:
int x,y; float
grade; char
letter;

scanf (“%d”, &x);


scanf (“%f”, &grade);
scanf (“%c”, &letter);
scanf (“%d %d”, &x, &y);

Working with scanf function


1. Write a program in C to take two numbers and display its addition.

#include < stdio.h >


#include <conio.h>
main( )
{
int integer1, integer2, sum;

printf ( “Enter first integer : ” );


scanf ( “%d”, &integer1 );
printf ( “Enter second integer: ” );
scanf ( “%d”, &integer2 );
sum = integer1 + integer2;
printf ( “Sum is %d ”, sum );
getch();
}

ALL RIGHTS RESERVED TO SVTI 22


2. Write a program in C to take two numbers and display its multiplication.
#include <stdio.h> #include
<conio.h>main( )

{
int a, b, mul;

printf ( "Enter first integer : " );scanf ( "%d", &a );


printf ( "\nEnter second integer: " );scanf ( "%d", &b );
mul = a * b;
printf ( "\nMultipilation is %d ", mul );

getch();
}

3. Write a program in C to take two numbers and display its division.


#include <stdio.h> #include
<conio.h>main( )

{
int a, b, div;

printf ( "Enter first integer : " );scanf ( "%d",


&a );
printf ( "\nEnter second integer: " );scanf ( "%d",
&b );
div = a / b;
printf ( "\nDivision is %d ", div );

getch();
}
4. Write a program in C to take two numbers and display its subtraction.

#include <stdio.h>
#include <conio.h>
main( )
{ int a, b, sub;
printf ( "Enter first integer : " );
scanf ( "%d", &a );
printf ( "\nEnter second integer: " );scanf ( "%d", &b );
sub = a - b;
printf ( "\nSubtraction is %d ", sub );
getch(); }

ALL RIGHTS RESERVED TO SVTI 23


5. Write a program in C to take subject marks and find its percentage.
#include <stdio.h>
#include <conio.h>
main( )
{ int obt, total;
printf ( "Enter obtain number: " );
scanf ( "%d", &obt );
printf ( "\nEnter total number: " );
scanf ( "%d", &total );
float per;
per = (obt*100) /total;
printf ( "\npersentage is %% %.2f ", per );getch(); }

gotoxy() Function
gotoxy(int x, int y) a function available in Turbo C/C++. It is not standard C. This function is
used to move the cursor on the screen to the desire location. The top left corner of the monitor
is 0,0 and the bottom right corner might be any number based on the size of the screen. But
today's standard C++ compiler such as Visual Studio, GCC and clang to not provide gotoxy
function. However, if you are developing console applications without a third party graphic
library then gotoxy function is useful to manage text alignment on the screen.

If you need similar implementation on a windows machine with GCC compiler then here is an
example source code.(this program is written in C++ programming language )
#include <windows.h> // header file for gotoxy
#include <iostream> //header file for standard input output
COORD coord= {0,0}; // this is global variable
void gotoxy(int x,int y)
{
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
int main()
{
//calling these function
int x;
gotoxy(15,5);
std::cout<<"1. This is item number one.";
gotoxy(15,7);
std::cout<<"2. This is item number two.";
gotoxy(15,9);
std::cout<<"3. This is item number three.";
gotoxy(15,11);
std::cout<<"4. This is item number four.";
gotoxy(15,13);
std::cout<<"5. This is item number five.";

ALL RIGHTS RESERVED TO SVTI 24


std::cin>>x;
return 0;
}

Character Data Entry Functions


1. getch()
2. getche()
3. getchar()
4. gets()
Difference between getc(), getchar(), getch() and getche()
All of these functions read a character from input and return an integer value. The integer is
returned to accommodate a special value used to indicate failure. The value EOF is generally
used for this purpose.

getc():
It reads a single character from a given input stream and returns the corresponding integer value
(typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream);
// Example for getc() in C Input: g (press enter key)
#include <stdio.h>
Output: g
int main()
{
printf("%c", getc(stdin));
return(0);
}

getchar():
The difference between getc() and getchar() is getc() can read from any input stream, but
getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void);
// Example for getchar() in C

#include <stdio.h> Input: g(press enter key)


int main()
Output: g
{ printf("%c", getchar()); return 0; }

getch():
getch() is a nonstandard function and is present in conio.h header file which is mostly used by
MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C
Like above functions, it reads also a single character from keyboard. But it does not use any
buffer, so the entered character is immediately returned without waiting for the enter key.

Syntax:
int getch();

ALL RIGHTS RESERVED TO SVTI 25


// Example for getch() in C Input: g (Without enter key)
#include <stdio.h>
Output: Program terminates immediately.
#include <conio.h>
int main() But when you use DOS shell in Turbo C,
{
it shows a single g, i.e., 'g'
printf("%c", getch());
return 0;
}

getche()
Like getch(), this is also a non-standard function present in conio.h. It reads a single character
from the keyboard and displays immediately on output screen without waiting for enter key.

Syntax:
int getche(void);
#include <stdio.h> Input: g(without enter key as it is not
#include <conio.h> buffered)
// Example for getche() in C
Output: Program terminates
int main()
immediately.
{
printf("%c", getche()); But when you use DOS shell in Turbo
return 0; C,
}
double g, i.e., 'gg'

getch( ) & getche() function


So far for input we have used the scanf( ).
However, for some situations the scanf( ) has one weakness... You need to hit the
Enter key before the function can digest what you have typed.
However, we often want a function that will read a single character the instant it is
typed without waiting for the Enter key to be hit.
getch( ) and getche( ) are two functions which serve this purpose.
These functions return the character that has been recently typed.

• You do not have to press the [ Return ] Key.


• Unformatted input function.
• It only takes a character.
• If you typed any wrong character, you cannot move backward to correct it.

get get from outside


ch character
e echo ( display )

ALL RIGHTS RESERVED TO SVTI 26


Chapter 4
OPERATORS USED IN C

Introduction
C supports a wide variety of operators, such as +, -, *, /, &, <, > etc.
An Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
C operators can be classified into a number of categories. They are :

1. Arithmetic operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increment and Decrement Operators.

1. Arithmetic Operators
Arithmetic operators include +, -, *, /, %, which performs all mathematical manipulations.
These operators can operate on any built-in data type allowed in C
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
Remainder Operator ( % ) is also called Modulo Operator.
For Example: = 13 % 5
Answer = 3
//Fahrenheit to Celsius Temperature conversion#include<stdio.h>
void main(void)
{
int ftemp,ctemp;
pritnf((“Type temperature in degree fahrenheit”);scanf((“%d”,&ftemp);
ctemp=(ftemp-32)*5/9;
printf(“Temperature in degree Celsius is %d”,ctemp); }

//Celsius to Fahrenheit Temperature conversion


#include<stdio.h>
void main(void)
{
int ftemp,ctemp;
pritnf((“Type temperature in degree Celsius”);scanf((“%d”,&ctemp);
ftemp = (ctemp +32)*9/5;
printf(“Temperature in degree Celsius is %d”,ftemp); }

ALL RIGHTS RESERVED TO SVTI 27


Operator Precedence- Order of Evaluation

How the operations works

Arithmetic Operators – Order of Evaluation


Another example:
1. x = 6 / 2 + 1 - 3 + 8 * 4;
output x = 33;
2. x = 6 / (2 + 1) - (3 + 8) * 4;
output x = -42;

2. Arithmetic Assignment Operator


Assignment operators are used to assign the result of an expression to a variable. Usually, ‘=’
operator is used. There is an additional ‘shorthand’ assignment operators of the form

V op = exp;
Here,
V= variable
exp = expression and

ALL RIGHTS RESERVED TO SVTI 28


op = a binary arithmetic operator.
The Operator op= is known as the shorthand assignment operator.
Syntax:
Arithmetic op=
+= (Addition Arithmetic Assignment Operator)
-= (Subtraction Arithmetic Assignment Operator)
*= (Multiplication Arithmetic Assignment Operator)
/= (Division Arithmetic Assignment Operator)
%= (Remainder Arithmetic Assignment Operator)

Representation
 a+=1 is same as=> a=a+1
 a-=1 is same as=> a=a-1
 a*=1 is same as=> a=a*1
 a/=1 is same as=> a=a/1
 a%=1 is same as a=a%1

Example of arithmetic assignment operators:


1. int a = 4, b = 2, c = 36 ;
a += b ; /* This adds b to a,
a=? */ [ Answer: a = a
+ b, so a = 4 + 2 or a = 6 ]

2. c /= a + b ; /* What is value
of c now?*/
[ Answer: c = c / (a + b), and a = 6 now, so
c = 36 / (6 +2), so c = 36 / 8 or c = 4 ]

#include <stdio.h> void main(void)


{
int num=2;
printf("Number plus four is %d",num+4); }

Output : Number plus four is 6

3. Relational Operators
Relational operators are used to compare two operands, and depending on their relation,
certain decisions are taken. For example, it can be used to compare the age of two persons,
price of two items and so on.
There are 6 types of relational operators. They are:

Operator: Meaning:
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
== Exactly Equal To
!= Not Equal To

ALL RIGHTS RESERVED TO SVTI 29


Used for asking questions like:
Is x bigger than 10?
In C, the value of 1 stands for true and 0 stands for false. But C will recognizeany non
zero value as true.
NOTE: "==" is NOT same as "="
Program Using Relational Operator.
void main (void)
{
int age ; age
= 15;
printf ( “ Is age less than 20 ? %d \n “, age < 20 ); age = 30;
printf ( “ Is age less than 20 ? %d \n “, age < 20 ); getch (
);
}
Output:
Is age less than 20 ? 1
Is age less than 20 ? 0

4. Logical Operator
C supports three Logical Operators. They are:
&& Logical AND or short circuit AND
|| Logical OR or short circuit OR
! Logical NOT

5. Increment/Decrement Operators
C supports two unique operators that are not found in other languages. They are: ++ and –
(increment and decrement operators respectively).
The operator ++ adds 1 to the operand, while -- subtracts 1. Both are unary operators and
take the following form:

Operator: Meaning: When?


count++ ; count = count + 1 ; After use
++count ; count = count + 1 ; Before use
count-- ; count = count - 1 ; After use
--count ; count = count - 1 ; Before use

Examples of increment and decrement operators:


1. int a = 4, b = 2, c;
c = ++a + b-- ; /* What are the values of a, b, c
now */(Answers: a = 5, b = 1, c = 7)

2. c = b-- - ++a ;
/* What are the values of a, b, c now?*/
(Answers: a = 6, b = 0, c = -5)

ALL RIGHTS RESERVED TO SVTI 30


Postfix increment and Postfix decrement Operator
Op++ It is postfix increment operator
Op-- It is postfix decrement operator
Prefix increment and Prefix decrement Operator
++Op It is prefix increment operator
--Op It is prefix decrement operator
variable++ as postfix increment operator
#include<stdio.h>
void main(void)
{
int num=0;
printf(“Number=%d\n”,num);
printf(“Number=%d\n”,num++);
printf(“Number=%d\n”,num);
}
OUTPUT
0,0,1

++variable as prefix increment operator

#include<stdio.h> void main(void)


{
int num=0; printf(“Number=%d\n”,num); printf(“Number=%d\n”,++num);
printf(“Number=%d\n”,num);
}
o/p is 0,1,1

variable-- as Postfix decrement operator


#include<stdio.h> void main(void)
{
int num=0; printf(“Number=%d\n”,num); printf(“Number=%d\n”,num--);
printf(“Number=%d\n”,num);
}
o/p is 0,0,-1

--variable as Prefix decrement operator


#include<stdio.h> void main(void)
{
int num=0; printf(“Number=%d\n”,num); printf(“Number=%d\n”,--num);
printf(“Number=%d\n”,num);
}
o/p is 0,-1,-1

Decisions in C
C language needs decisions be taken for desired results which are below
1. simple if
2. if-else

ALL RIGHTS RESERVED TO SVTI 31


3. else if
4. switch
1. Simple if 2. if-else Syntax 3. else if Syntax
if(condition)Statement if(condition)statement
Syntax if(condition) Else else if(condition)
statement
Statement statement
else if(condition)statement
else if(condition)
Statement
else
Statement

If else program
#include<stdio.h> void main (void)
{
int percentage = 70; if( percentage >= 60 )
printf (“You are passed”); else // no condition after else printf (“You are Fail”);
printf (“\n End of Program”); getch();
}

4. Switch statement
Switch statement can be used instead of simple if, if else and else if
Syntax
int x;
x=value;
switch( x)
{
case 1:
case 2:
case 3:
default:
}

ALL RIGHTS RESERVED TO SVTI 32


Calculator using switch case
// Performs addition, subtraction, multiplication or division depending the input fromuser
# include <stdio.h>int
main() {
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *,): ");
scanf("%c", &operator); printf("Enter
two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber, firstNumber +
secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber -
secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber, firstNumber *
secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber /
secondNumber);
break;
// operator doesn't match any case constant (+, -, *, /)default:
printf("Error! operator is not correct");
}

return 0;
}

OUTPUT:

Enter an operator (+, -,


*,): *Enter two
operands: 1.5
4.5
1.5 * 4.5 = 6.8

ALL RIGHTS RESERVED TO SVTI 33


Nested if and Nested switch statement
• If can be nested
• If condition inside if
• Switch can be nested, which means switch inside switch
Syntax
If(condition)
{
If(conditi
on)
printf(“O
k”);
}

ALL RIGHTS RESERVED TO SVTI 34


CHAPTER 5
CONTROL STRUCTURE

Repetitive Control Structure (LOOP’s)


In Programming; we frequently need to perform an action more than once (repetitively).The
mechanism that meets this need is the “Loop”.

Repeating some portion of the program either specified number of times or until a
particular condition is being satisfied.
Three methods (loops) by which we can repeat the portion of program:
1. Using a for statement
2. Using a while statement
3. Using a do-while statement
For Loop
Specifies counter-controlled repetition details in a single line of code.
Syntax
for (initialization expression; test expr; increment expr)
Body of for loop ;
Example:
for ( count = 1; count < 10; count + + )
for loop allows us to specify three things:
1. setting a loop counter to an initial value.
2. testing the loop counter to determine whether its value has reached number of
repetitions desired.
3. increasing the value of loop counter each time the program segment (body of
for loop) has been executed.

Flow chart – for loop

ALL RIGHTS RESERVED TO SVTI 35


// programming example using for loop Output of program:
void main (void) Count = 1
{ Count = 2
int count; Count = 3
Count = 4
for ( count = 1; count <= 10; count + + ) Count = 5
printf ( “ Count = %d \n”, count ); //body of for loop Count = 6
Count = 7
getch( ); Count = 8
} Count = 9
Count = 10
The following diagram illustrates the operation of a for loop

initialize Test exp increment

Body of for loop

Write a C program to find the sum of first 10 natural numbers.


#include <stdio.h> Output
void main() The first 10 natural number is :
{ 1 2 3 4 5 6 7 8 9 10
int j, sum = 0; The Sum is : 55

printf("The first 10 natural number is :\n");

for (j = 1; j <= 10; j++)


{
sum = sum + j;
printf("%d ",j);
}
printf("\nThe Sum is : %d\n", sum);
}

Nested for loop


A for loop within the body of for loop is called “Nested for loop”.
Syntax:
for (initialization expression; test expr; increment expr) //outer loop
{
for (initialization expression; test expr; increment expr) //inner loop
{
Body of inner for loop ;
}
}

ALL RIGHTS RESERVED TO SVTI 36


/* Demonstration of nested loops */ Output of program:
main( ) r = 1 c = 1 sum = 2
{ r = 1 c = 2 sum = 3
int r, c, sum ; r = 2 c = 1 sum = 3
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */ r = 2 c = 2 sum = 4
{ r = 3 c = 1 sum = 4
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */ r = 3 c = 2 sum = 5
{
sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
} } }

Write a program in C to display the pattern like right angle triangle using an asterisk.
#include <stdio.h> Input number of rows : 10
void main() *
{ **
int i,j,rows; ***
printf("Input number of rows : "); ****
scanf("%d",&rows); *****
for(i=1;i<=rows;i++) ******
{ *******
for(j=1;j<=i;j++) ********
printf("*"); *********
printf("\n"); **********
}}

Fibonacci Series
The Fibonacci series is a set of numbers that starts with a 1 or a 0, followed by a 1, and proceeds
based on the rule that each number is equal to the sum of the preceding two numbers.
How to Generate?
The first two numbers in the series are one and one. To obtain each number of the series, you
simply add the two numbers that came before it. In other words, each number of the series is
the sum of the two numbers preceding it.

// Program to generate Fibonacci series Output of Program:


void main (void) 1 1 2 3 5 8 13 21 34
{ 55 89
int next = 0, last = 1, sum ;
for (int i=1; i <=10 ; i++)
{
printf (“ %d \t ”, last );
sum = next + last;
next = last;
last = sum;
}
getch();
}

ALL RIGHTS RESERVED TO SVTI 37


While loop
The while loop provides a mechanism for repeating C statements until a condition is true.
Syntax:
While (control expression)
program statement ;
The while statement works as follows:
1) Control expression is evaluated.
2) If it is FALSE, skip over the loop.
3) If it is TRUE, loop body is executed.
4) Go back to step 1
// Programmer is responsible for initialization and Output of program:
incrementation. 1
#include <stdio.h> 2
void main (void) 3
{ 4
int count = 1; 5
while (count < = 10) 6
{ 7
printf(“ %d \n”,count); 8
count ++ ; 9
} 10
getch( ); }

Why While Loop?


In situations, where the number of repetitions in a loop are known in advance, as they are in
the while loop example, while loop is less appropriate. In this case the for loop is a more natural
choice.
So, when is the while loop becomes the appropriate choice?
The while loop shines, in situations where a loop may be terminated unexpectedly by
conditions developing with in the loop.
OR
When we don’t know in advance how many times the loop is executed.
#include<stdio.h> Output of program:
void main (void) Type in a phrase:
{ This is while loop
int count ; Character count is = 18
char ch ;
printf ( "Type in a phrase:\n " );
ch = getche ( );
while ( ch != '\r' ) // check for Return key
{
count ++ ;
ch = getche ( );
}
printf ( " \n Character Count is = %d ", count ); }

ALL RIGHTS RESERVED TO SVTI 38


Counter program
//Program to generate numbers 1 to 100 /*Program to generate Hello SVTI message
#include<stdio.h> 100 times*/
void main(void) #include<stdio.h>
{ void main(void)
int counter=1; {
while(counter<=100) int counter=1;
{ while(counter<=100)
pritnf(“%d=”,counter); {
counter++; pritnf(“Hello SVTI”);
}} counter++;
}}

do – while Loop
The do while statement is a variant of the while loop in which the condition test is
performed at the “bottom” of the loop.
This guarantees that the loop is executed at least once whether the condition is TRUE or
FALSE.
The syntax of the do while statement is
Syntax:
initialization
do {
// body of for loop
increment
} while(checking);
-
and it works as follows
1) The body of the loop is executed.
2) The control expression is evaluated (“exit condition”).
3) If it is TRUE, go back to step 1.
4) If it is FALSE, exit loop.
do – while flow chart

#include <stdio.h>
#include <conio.h>
Void main (void)
{ int num;
do
{
printf (" Enter any number");
scanf ("%d", &num);
} while ( num < 25 );
getch( );
}

ALL RIGHTS RESERVED TO SVTI 39


//Program to generate numbers 1 to 100 /*Program to generate Hello SVTI message
#include<stdio.h> 100 times*/
void main(void) #include<stdio.h>
{ void main(void)
int counter=1; {
do int counter=1;
{ do
pritnf(“%d=”,counter); {
counter++; pritnf(“Hello SVTI”);
}while(counter<=100); counter++;
} }while(counter<=100);
}

Summary of Loops in C Language


• The for Loop is frequently used, usually where the loop will be traversed a fixed number
of times. It is very flexible.
• The while Loop keeps repeating an action until an associated test returns false. This is
useful where the programmer does not know in advance how many times the loop will be
traversed.
• The do While Loop is similar to the While Loop, but the test occurs after the loop body is
executed. This ensures that the loop body is run at least once.

BREAK AND CONTINUE STATEMENT IN C LANGUAGE


C break
The break statement ends the loop immediately when it is encountered. Its syntax is:
break;
The break statement is almost always used with if...else statement inside the loop

How break statement works?

ALL RIGHTS RESERVED TO SVTI 40


Example 1: break statement

// Program to calculate the sum of a maximum of 10 numbers


// If a negative number is entered, the loop terminates

# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 10; ++i)


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If the user enters a negative number, the loop ends


if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);

return 0;
}
Output
Enter a n1: 2.4
Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

This program calculates the sum of a maximum of 10 numbers. Why a maximum of 10


numbers? It's because if the user enters a negative number, the break statement is executed.
This will end the for loop, and the sum is displayed.

C continue
The continue statement skips the current iteration of the loop and continues with the next
iteration. Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.

ALL RIGHTS RESERVED TO SVTI 41


How continue statement works?

Example 2: continue statement


// Program to calculate the sum of a maximum of 10 Output
numbers
// Negative numbers are skipped from the calculation Enter a n1: 1.1
# include <stdio.h> Enter a n2: 2.2
int main() Enter a n3: 5.5
{ Enter a n4: 4.4
int i; Enter a n5: -3.4
double number, sum = 0.0; Enter a n6: -45.5
for(i=1; i <= 10; ++i) Enter a n7: 34.5
{ Enter a n8: -4.2
printf("Enter a n%d: ",i); Enter a n9: -1000
scanf("%lf",&number); Enter a n10: 12
if(number < 0.0) Sum = 59.70
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);

return 0;
}

In this program, when the user enters a positive number, the sum is calculated using sum +=
number; statement.When the user enters a negative number, the continue statement is executed
and it skips the negative number from the calculation.

ALL RIGHTS RESERVED TO SVTI 42


Chapter 6
ARRYS IN C PROGRAMING

What are Arrays?


Definition:
An array is a collection of variables of same data type that has given the same name and stores
in consecutive memory locations.
OR
Array is collection of homogeneous elements in C.Array is needed to be declared and
initialized

Why we need arrays?


For understanding the arrays properly, let us consider the following program:
main( )
{ int x ;
x=5;x
= 10 ;
printf ( "\nx = %d", x ) ;
}

This program will print the value of x as 10. Why so? Because when a value 10 is assigned to
variable x, the earlier value of x, i.e. 5, is lost. Thus, simple variables (the ones which we have
used so far) are capable of holding only one value at a time (as in the above example).
However, there are situations in which we would want to store more than one value at a time
in a single variable.

For example, suppose we wish to arrange the marks obtained by 100 students in ascending
order. In such a case we have two options to store these marks in memory: i- Construct 100
variables to store marks obtained by 100 different students, i.e.
each variable containing one student’s marks.

ii- Construct one variable (called array) capable of storing or holding all the hundred values.
Obviously, the second alternative is better. A simple reason for this is, it would be much easier
to handle one variable than handling 100 different variables.

A Simple Program Using Array


Consider a program to find average marks obtained by a class of 30 students in a
test.
#include<stdio.h>
main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i < 30; i++ )
{

ALL RIGHTS RESERVED TO SVTI 43


printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[ i ] ) ; /* store data in array */
}
for ( i = 0 ; i < 30 ; i++ )
sum = sum + marks[ i ] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}

The first for loop gets the marks from the user and places them in the array, while the second
loop reads them from the array and computes the sum.

Array Declaration:
Syntax:
type array_name [ size ];
Like other variables an array needs to be declared so that the compiler will know array type
and name. But it includes another feature: a size. The size specifies how many data items the
array will contain or how large an array we want. It immediately follows the name, and is
surrounded by square brackets. In our program we have done this with the statement:
int marks[30] ;
Here, int specifies the type of the array, just as it does with ordinary variables and the word
marks specifies the name of the array. The [30] however is new. The number 30 tells how
many elements of the type int will be in our array. The square bracket [ ] tells the compiler
that we are dealing with an array.

Accessing Elements of an Array:


The items in an array are called elements. Once an array is declared, let us see how individual
elements in the array can be referred or accessed.
In above example we access each array element twice. The first time, we insert a value into
the array, with the line scanf ( "%d", &marks[ i ] ) ;
The second time, we read it out with the line sum
= sum + marks[ i ] ;
In both cases, the expression for the array element is marks[i]

This consists of the name of the array, followed by brackets delimiting a variable i.
mark[0] refers to the first element, mark[1] to the second, mark[2] to the third, mark[4] to the
fourth and son on. The variable (or constant) in the square brackets [ ] is called the array index
or subscript. This number specifies the element’s position in the array. Since i is the loop
variable in both for loops, it starts at 0 and is incremented until it reaches 30, thereby accessing
each of the array elements in turn.

To fix our ideas, let us revise whatever we have learnt about arrays:
i- An array is a collection of similar elements.
ii- The first element in the array is numbered 0, so the last element is 1 less than the size
of the array.
iii- An array is also known as a subscripted variable.
iv- Before using an array its type and dimension must be declared.
v- However big an array its elements are always stored in contiguous memory locations.

ALL RIGHTS RESERVED TO SVTI 44


Array Initialization:

You can give values to each array element when the array is declared.
int num[6] = { 2, 4, 12, 5, 45, 5 }
; int num[6] = { 1, 2, 3, 4, 5 } ;
int num[ ] ={2, 4, 12, 5, 45, 5, 3, 10 }
;
1. In first initialization six elements are initialized to six locations of array.
2. In second initialization there are not enough elements initialized, last (rightmost) elements
become 0.
3. In last initialization size of array in not mentioned, compiler will count number of elements in
array initialization, which will be the size of array. In above case size of array would be 8.
NOTE: Refer all programs related to arrays we discussed in class.
Initialization
Single dimensional
array array[0]=20;
array[1]=30;
array[2]=40;
array[3]=50;
array[4]=60;
array[5]=70;
array[6]=80;
array[7]=90;
array[8]=90;
array[9]=100;
• First element can be accessed array[0]
• Last element can be accessed array[9] or array[size-1]
Average of week’s temperature
#include<stdio.h>
void main(void)
{
int temper[7]; int
day,sum;
for(day=0;day<7;day++)
{
printf(“Enter temperature for day %d”,day); scanf(“%d”,&temper[day]);
}
sum=0; for(day=0;day<7;day++)
sum+=temper[day];
printf(“The average is %d”,sum/7);
}

There are seven numbers stored in an array. The following program prints all the numbers of
that array as well as prints the numbers in backward.

ALL RIGHTS RESERVED TO SVTI 45


#include<stdio.h>
int main()
{
int M[10];
int j;
/* store seven numbers in array M */
M[0] = 2;
M[1] = 4;
M[2] = 6;
M[3] = 8;
M[4] = 10;
M[5] = 12;
M[6] = 14;
/* print numbers in M */
printf("Print all the Numbers : \n");
for (j = 0; j < 7; ++j)
printf("M[%d] = %d\n",j,M[j]);
/* print numbers in M backwards */
printf("\nFrom End to Beginning : \n");
for (j = 6; j >= 0; --j)
{
printf("M[%d] = %d\n",j,M[j]);
}
}

Multidimensional Arrays:
So far we have explored arrays with only one dimension. It is also possible for arrays to have
two or more dimensions. The two-dimensional array is also called a matrix.

Declaring a 2-D array:


Syntax: type array_name[size][size]; // 1st dimension indicate row and 2nd
column int a[10]; /* declare 1D array */
int b[3][5]; /* declare 2D array */

ALL RIGHTS RESERVED TO SVTI 46


First index value specifies the row and second index value specifies the column. Consider
a 2-D array b[3][5], memory map of 2-D arrays is as follows:

Here is a sample program that stores roll number and marks obtained by a student side by side
in a matrix.

#include<stdio.h>
main( )
{
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i < 4 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i < 4 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

In stud[i][0] and stud[i][1] the first subscript of the array stud, is row number which changes
for every student whenever loop executes. The second subscript tells which of the two columns
are we talking about—the zeroth column which contains the roll no. and the first column which
contains the marks. Remember the counting of rows and columns begin with zero. The
complete array arrangement is shown below.

ALL RIGHTS RESERVED TO SVTI 47


Initializing a 2-Dimensional Array:
int stud[4][2] = { {1234, 56},{1212, 33},{1434, 80},{1312, 78}
}; or even this would work... int stud[4][2] = { 1234, 56, 1212,
33, 1434, 80, 1312, 78 } ;

It is important to remember that while initializing a 2-D array it is necessary to mention


the second (column) dimension, whereas the first dimension (row) is optional.

Thus the declarations,


int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas,
int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
would never work.

ALL RIGHTS RESERVED TO SVTI 48


Chapter 7
SRTING & I/O MANIPULATION FUNCTION

Introduction
Strings are the form of data used in programming languages for sorting and manipulating text,
such as words, names and sentences. In C Language, a string is not a formal data type as it is
in some languages (e.g. Pascal and BASIC). Instead, String is an array of type char that is
called “C String”. Declaring String:
Syntax:
type name of string [ size ] ; // In case of string, type must be char.

Example:
char name[30];
Strings must be terminated by the null character '\0' which is called the end-
ofstring
character. Don’t forget to remember to count the end-of-string character
when you calculate the size of a string. Figure shows string stored in the
memory.
The terminating null character (‘\0’) is important, because it is the only way
the functions that work with a string can know where the string ends.

Programming Example:
#include<stdio.h>
void main ( void )
{
char name [ 30 ] ; printf ( “ Enter your name : “ ); scanf ( “ %s “, name ) ;
printf ( “ Greetings, %s. “, name ) ;
}
Output:
Enter your name: Ahmed Greetings, Ahmed.

You may have noticed something odd about the scanf ( ) statement in the above program.
There is no address operator ( & ) preceding the name of the string when we are going to
take input.
scanf ( “ %s ”, name ) ; This is because name is an array and array’s name represent starting
address of array.
We need to preface numerical and character variables with the & (address operator) to change
values into address, but name is already the name of the array, and therefore it is an address
and does not need the & (address operator).

Note: Since a string is an address, no address operator ( & ) need precede it in a scanf ( )
function.

String & I / O Manipulation Functions:


1. gets ( )
2. puts ( )

ALL RIGHTS RESERVED TO SVTI 49


There are many C functions whose purpose is to manipulate strings. One of the most common
is used to input a string from the keyboard. Why is it needed?
Because our old friend, the scanf ( ) function has some limitations when it comes to handling
strings.
For example consider the following program:
void main ( void )
{
char name [ 80 ] ;
printf ( “ Enter your name : “ );
scanf ( “%s”, name ) ;
printf ( “ Greetings, %s. “, name ) ;
}
Output:
Enter your name: Adnan Ahmed Arain
Greetings, Adnan

Where did the second and third words of our name go? Remember that scanf ( ) uses any white
spaces characters (space, tab or return key) to terminate entry of a variable. The result is that
there is no way to enter a multi-word string into a single array using scanf( ).
The solution to this problem is to use another C library function: gets ( ). The purpose of gets(
) is, to get a string from the keyboard. It is not as versatile an input function as scanf ( ). gets
( ) is specialize in doing one thing: reading strings. It is terminated only when the [Return]
key is pressed; therefore spaces and tabs are perfectly acceptable.
void main ( void )
{
char name [ 80 ] ;
puts ( “ Enter your name : “ );
gets ( name ) ;
puts ( “ Greetings, “ ) ;
puts ( name );
}
Output of program:
Enter your name: Adnan Ahmed Arain
Greetings, Adnan Ahmed Arain

The puts ( ) function is a special purpose output function specializing in strings. Unlike printf
( ), it can only output one string at a time and, like gets( ), it has no ability to format a string
before printing it. The syntax of puts ( ) is simpler than printf ( ), however, so it is the function
to use when you want to output a single string.

Initializing Strings:
Initializing (or assigning a value to) a string can be done in three ways:
1) at declaration,
2) by reading in a value for the string, and 3) by using the strcpy
function.

ALL RIGHTS RESERVED TO SVTI 50


Direct initialization using the = operator is invalid. The following code would
produce an error:
char name[34];
name = "ADNAN"; /* ILLEGAL */
• To read in a value for a string use the %s format specifier or use gets ( ) function:
scanf("%s",name); or
gets( name );

Initialization:
Just as arrays can be initialized, so can strings. Since a string is an array of characters, we
can initialize one in exactly that way, as the following example demonstrate:
char abc[ ] = {‘ A ’ , ’ d ’ , ’ n ’ , ’ a ’ , ’ n ’ , ’ \0 ’ } ;

In this type of initialization each character is enclosed in single quote,


separated by comma, programmer has to include null character ‘\0’ at the end
of string and delimit the string in curly brackets { }.
However, C Language provides an easier and shortcut method of initializing strings, as the
following example demonstrate:
char abc [ ] = “ Adnan “ ;
Second string initialization, marked with double quotes automatically includes the endof-
string character. The curly braces are not required for string initialization at declaration.

String Functions:
Included in String.h are several more String related function that are free for you to
use.

ALL RIGHTS RESERVED TO SVTI 51


1- strlen( ):
This function counts and returns the number of characters present in a string.
Syntax:
int var = strlen ( string );
as the functions returns an integer value, therefore we need an integer variable on left side of
function call to store the length of sting.
Programming Examples that demonstrate strlen( ) function:

//Program #1 #include<stdio.h>
void main(void)
{
char str[ ] = "I Love Pakistan" ;
int len;
len = strlen ( str ); printf ("Length of string =
%d\n ",len) ;
getch();
}
Output
Length of string = 15

2- strnlen
Syntax:
size_t strnlen(const char *str, size_t maxlen)
size_t represents unsigned short
It returns length of the string if it is less than the value specified for maxlen (maximum length)
otherwise it returns maxlen value.

Example of strnlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30));
printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10));
return 0;
}
Output:
Length of string str1 when maxlen is 30: 13
Length of string str1 when maxlen is 10: 10

Have you noticed the output of second printf statement, even though the string length was 13
it returned only 10 because the maxlen was 10.

3- strcpy ( ):
The function simply copies one string to another. Copies string from source to destination.
Syntax:
strcpy ( Destination string, Source string ) ; Programming

ALL RIGHTS RESERVED TO SVTI 52


Example:
void main(void)
{
char str1 [ ] = “QUEST”; char
str2 [ ] = "Nawabshah";
strcpy ( str1 , str2 ) ; //copies str2 into str1, contents of str1 are replaced
puts(str1); puts(str2);
}
Output of program:
Nawabshah
Nawabshah

4- Strcmp ( ):
This is a function which compares two strings to find out whether they are same or different.
The two strings are compared character by character using the ASCII numerical values until
there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two
strings are identical, strcmp ( ) returns a value zero. If they’re not, it returns the numeric
difference between the ASCII values of the first non-matching pairs of characters.
Syntax:
int var = strcmp ( s1, s2 ) ; strcmp function
returns following values:
0 If both s1 and s2 are equal
> 0 If s1 is greater than s2
< 0 If s2 is less than s1
#include<stdio.h>
main( )
{
char string1[ ] = "JJJ" ;
char string2[ ] = "DDD" ;
int i, j, k ;
i = strcmp ( string1, "JJJ" ) ;
j = strcmp ( string1, string2 );
k = strcmp ( string1, "MMM" ) ;
printf("\n%d %d %d", i, j, k ) ;
}

C Program to Display the current Date and Time


The C library function char *ctime(const time_t *timer) returns a string representing the
localtime based on the argument timer. The returned string has the following format: Www
Mmm dd hh:mm:ss yyyy. Here Www is the weekday, Mmm the month in letters, dd the day
of the month, hh:mm:ss the time and yyyy the year.

Below is the program to display current date and time.

ALL RIGHTS RESERVED TO SVTI 53


// #include<time.h> is used for time and ctime function and time_t datatype.

#include<stdio.h>
#include<time.h>

int main()
{
printf("\n\n\t\t***now, the time is to become a programmer*** \n\n\n");

time_t t; // not a primitive datatype time(&t);

printf("\nThis program has been written at (date and time): %s", ctime(&t));

printf("\n\n\t\t\tCoding is Fun !\n\n\n");


return 0;
}

C– Miscellaneous functions
Descriptions and example programs for C environment functions such as getenv(), setenv(),
putenv() and other functions perror(), random() and delay() are given below.
Miscellaneous functions Description

Returns random integer number range from 0 to


rand() at least 32767

Suspends the execution of the program for


delay() particular time

EXAMPLE PROGRAM FOR RAND() FUNCTION IN C:


This function returns the random integer numbers range from 0 upto 32767.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main ()
{ printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0; }

OUTPUT:
1st random number : 83 2nd random number : 86 3rd random number: 16816927

EXAMPLE PROGRAM FOR DELAY() FUNCTION IN C:


This function suspends the execution of the program for particular time.

ALL RIGHTS RESERVED TO SVTI 54


#include<stdio.h>
#include<stdlib.h>
int main ()
{
printf("Suspends the execution of the program " \
"for particular time");
delay(5000); // 5000 mille seconds
return 0;
}
OUTPUT:
Suspends the execution of the program for particular time

ALL RIGHTS RESERVED TO SVTI 55


Chapter 8
USER DEFINE FUNCTIONS
Functions
• Predefined functions are such as printf(), scanf() and getch().
Concept of user defined functions
• These functions are used to avoid unnecessary repetition of code.
• The function is created by user for specific task.
• The user defined function can be modified at any time by programmer.
• The name of function can be given by programmer by the legal identifier rules.
• The user defined functions are useful for software development.
• The user define functions make the programmer expert and smart.

A function groups a number of program statements into a unit and gives it a name. This
unit can then be invoked (called) from other parts of the program.
The most important reason to use functions is to reduce program size.
Any sequence of instructions that appears in a program more than once is a candidate
for being made into a function. Instead of having to write a section of code over and over,
you can just make a function, and call the function. The function’s code is stored in only
one place in memory, even though the function is executed many times in the course of the
program.

Ideally, your main( ) function should be very short and should consist primarily of
function calls.
Each function has its own name. When that name is encountered in a main program, the
execution of the program branches (jumps) to the body of that function. When the
function is finished, execution returns to the main program code from which it was
called, and the program continues on to the next line of code.

ALL RIGHTS RESERVED TO SVTI 56


Components of Function:
1- Function Declaration 2- Function Call 3- Function Definition

Sample Program 1:
#include <stdio.h>
#include <conio.h>
void star(); // user define function declaration
void main()
{
star();
printf (" 10 ELECTRONICS ");
star(); // Function Call
printf (" \n SVTI ") ;
star(); // Function Call
getch();
}
// star()function definition
void star() // function declarator
{
int j ;
for( j=0; j<=30; j++)
printf (" * ");
printf (" \n " );
}

1. Declaring the function:


The function declaration, also called the function prototype, tells the compiler the
name, return type, and arguments of the function (see diagram below). This
statement is placed after header file and before void main (void).
Just as you can’t use a variable without first telling the compiler what it is, you also can’t
use a function without telling the compiler about it. In the above program, the function
star ( ) is declared in the line:
void star();
The declaration tells the compiler that at some later point we plan to present a function
called star. The keyword void specifies that the function has no return value, and the

ALL RIGHTS RESERVED TO SVTI 57


empty parentheses indicate that it takes no arguments. Notice that the function
declaration is terminated with a semicolon. It is a complete statement in itself.

An argument is the value passed to the function and the parameter is the variable that
received the value.

2. Calling the Function:


The function is called (or invoked, or executed) three times from main( ) in above program.
Each of the three calls looks like this:
star();
This is all we need to call the function: the function name, followed by parentheses. The
syntax of the call is very similar to that of the declaration, except that the return type is
not used. The call is terminated by a semicolon. Executing the call statement causes the
function to execute; that is, control is transferred to the function, the statements in the
function definition are executed, and then control returns to the statement following the
function call.

3. Define the function:


Finally, we come to the function itself, which is referred to as the function definition.
Function definition contains the actual code for the function. The definition consists of a
line called the declarator, followed by the function body. Here’s the definition for
star ( )
void star() //declarator
{
for(int j=0; j<=30; j++) //function
body
printf (“ * “);
printf (“ \n “ ); }

The function definition tells the compiler what task the function will be performing. The
function declaration and the function definition must agree EXACTLY on the return
type, the name, and the parameters. The only difference between the function
declaration and the function definition is a semicolon (see diagram below). The function
definition is placed AFTER the end of the void main(void) function.
The function definition consists of the declarator and its body. The declarator is
EXACTLY like the function declaration, EXCEPT that it contains NO terminating
semicolon.

ALL RIGHTS RESERVED TO SVTI 58


Example program 2
//Declaration of function
// using special character \xDB for courser box
#include <stdio.h>
void line(void);
void main()
{
line();
printf("\t\t\t \xDB SVT Nawabshah\xDB\n");
line();
}
void line(void)
{
int j;
for(j=1;j<=20;j++)
printf(" \xDB ");
printf("\n");
}

Example program 3
//program to print the hello svti 10 times
#include<stdio.h>
void message(void);
void main(void)
{
message();
printf(" user define function use for the reduction of code \n");
message();
}
void message(void)
{
printf("***HELLO SVTI STUDENTS*** \n");
printf("***HELLO SVTI STUDENTS*** \n");
printf("***HELLO SVTI STUDENTS*** \n");
printf("***HELLO SVTI STUDENTS*** \n");
}

ALL RIGHTS RESERVED TO SVTI 59


Example program 4
//A sound example
//Special character ‘\x7’ called Bell
#include<stdio.h>
void twobeep(void);
void main(void)
{
twobeep();
printf("type any character");
getch();
twobeep();
}
void twobeep(void)
{
long j;
printf("\x7");
for(j=1;j<100000;j++)
;
printf("\x7");
}

Passing Arguments to Functions


An argument is a piece of data (for example an int, char or float value) passed from a program
to the function. Arguments allow a function to operate with different values, or even to do
different things, depending on the requirements of the program calling it.

Passing Constants
The star( ) function in the last example is too rigid. Instead of a function that always prints 30
asterisks, we want a function that will print any character any number of times. Here’s a
modified program, that incorporates just such a function. We use arguments to pass the
character to be printed and the number of times to print it.

Example Program 5:
void star(int , char);
void main()
{

Arguments

star(5, ‘-');
printf (“ 10 ELECTRONICS “);
star(15, ‘*‘); // Function Call
printf (“ \n QUEST “) ;
star(25,’#’); // Function Call
getch();
}

ALL RIGHTS RESERVED TO SVTI 60


Parameters

void star(int n, char c)


{
for(int j=0; j<=n; j++)
printf (“ %c “, c);
printf (“ \n “ );
}

Now function declaration looks like this:


void star(int , char); // declaration specifies data types
The items in the parentheses are the data types of the arguments that will be sent to star( ):
int and char. In a function call, specific values—constants in this case—are inserted in the
appropriate place in the parentheses:

star(5 , ‘-’); // function call specifies actual values

This statement instructs star( ) function to print a line of 5 dashes. The values supplied in
the call must be of the types specified in the declaration: the first argument, the number 5,
must be of time int, and the second argument the ‘-’ character, must be of type char. The
types in the declaration and the definition must also agree.

The next call to star( ),


star(15 , ‘#’);

tells it to print a line of 15 asterisk. The third call again prints 25 hashes.
The variables used within the function to hold the argument values are called parameters;
in star( ) they are c and n. The declarator in the function definition specifies both the data
types and the names of the parameters:

void star(int n , char c) //declarator specifies parameter names and data types

These parameter names, c and n, are used in the function as if they were normal variables.
When the function is called, its parameters are automatically initialized to the values
passed by the calling program.

Passing Variables
In the above sample program 5, the arguments were constants: ‘-’, 43, and so on. Let’s
look at an example where variables, instead of constants, are passed as arguments. This
program, incorporates the same star( ) function as did, but lets the user specify the
character and the number of times it should be repeated.

ALL RIGHTS RESERVED TO SVTI 61


Example Program 6:
void star(int , char);
void main()
{
int num;
char ch;
printf(“ Enter character “);
scanf(“ %c “, &ch);
printf(“\n Enter number of times to repeat the character “);
scanf(“ %d “, &num);
star(num, ch);
getch();
}
void star(int n, char c)
{
for(int j=0; j<=n; j++)
printf (“ %c “, c);
printf (“ \n “ );
}
OUTPUT OF PROGRAM:
Enter a character: +
Enter number of times to repeat it: 20
++++++++++++++++++++
Here ch and num in main() are used as arguments to star( ):
star(num, ch); // function call

Type of User-defined Functions in C


There can be 4 different types of user-defined functions, they are:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
Below, we will discuss about all these types, along with program examples.
1. Function with no arguments and no return value
Such functions can either be used to display information or they are completely dependent on
user inputs.
Below is an example of a function, which takes 2 numbers as input from user, and display
which is the greater number.
#include<stdio.h>

void greatNum(); // function declaration

int main()
{
greatNum(); // function call
return 0;

ALL RIGHTS RESERVED TO SVTI 62


}

void greatNum() // function definition


{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}

2. Function with no arguments and a return value


We have modified the above example to make the function greatNum() return the number
which is greater amongst the 2 input numbers.

#include<stdio.h>

int greatNum(); // function declaration

int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum() // function definition


{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j) {
greaterNum = i;
}
else {
greaterNum = j;
}
// returning the result
return greaterNum;
}

ALL RIGHTS RESERVED TO SVTI 63


3. Function with arguments and no return value
We are using the same function as example again and again, to demonstrate that to solve a
problem there can be many different ways.
This time, we have modified the above example to make the function greatNum() take two int
values as arguments, but it will not be returning anything.
#include<stdio.h>

void greatNum(int a, int b); // function declaration

int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}

void greatNum(int x, int y) // function definition


{
if(x > y) {
printf("The greater number is: %d", x);
}
else {
printf("The greater number is: %d", y);
}
}

4. Function with arguments and a return value


This is the best type, as this makes the function completely independent of inputs and outputs,
and only the logic is defined inside the function body.

#include<stdio.h>
int greatNum(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}
int greatNum(int x, int y) // function definition
{
if(x > y) {
return x;
}
else {
return y;
}
}

ALL RIGHTS RESERVED TO SVTI 64


Chapter 9
POINTTER IN C PROGRAMMING

What is Pointer in C?
The Pointer in C, is a variable that stores address of another variable. A pointer can also be
used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to
point to the next/ previous memory location. The purpose of pointer is to save memory space
and achieve faster execution time.

Pointers are addresses


A pointer is really the address of something in memory.
Pointers are needed if it is required that a function change the value of an object(through global
variables could be used).
For example, the scanf function takes pointers as arguments.

Pointers are not Integers


It is possible to treat pointers as though they are integers since they hold actual addresses in
memory i-e 7232.
printf, scanf, assignment and some of the arithmetic operators work with pointers.

How to Use Pointers in C


If we declare a variable v of type int, v will actually store a value.

v is equal to zero now.

However, each variable, apart from value, also has its address (or, simply put, where it is
located in the memory). The address can be retrieved by putting an ampersand (&) before the
variable name.

If you print the address of a variable on the screen, it will look like a totally random number
(moreover, it can be different from run to run).
Let's try this in practice with pointer in C example

The output of this program is -480613588.

ALL RIGHTS RESERVED TO SVTI 65


Now, what is a pointer? Instead of storing a value, a pointer will y store the address of a
variable.

Pointer Variable
Int *y = &v;

VARIABLE
A value stored in a named storage/memory address

POINTER
A variable that points to the storage/memory address of another variable

Declaring a Pointer
Like variables, pointers in C programming have to be declared before they can be used in your
program. Pointers can be named anything you want as long as they obey C's naming rules. A
pointer declaration has the following form.
Syntax:
data_type * pointer_variable_name;
Here,
 data_type is the pointer's base type of C's variable types and indicates the type of the
variable that the pointer points to.
 The asterisk (*: the same asterisk used for multiplication) which is indirection operator,
declares a pointer.
Let's see some valid pointer declarations in this C pointers tutorial:
int *ptr_thing; /* pointer to an integer */
int *ptr1,thing;/* ptr1 is a pointer to type integer and thing is an integer variable */
double *ptr2; /* pointer to a double */
float *ptr3; /* pointer to a float */
char *ch1 ; /* pointer to a character */
float *ptr, variable;/*ptr is a pointer to type float and variable is an ordinary float variable
*/

Initialize a pointer
After declaring a pointer, we initialize it like standard variables with a variable address. If
pointers in C programming are not uninitialized and used in the program, the results are
unpredictable and potentially disastrous.
To get the address of a variable, we use the ampersand (&)operator, placed before the name of
a variable whose address we need. Pointer initialization is done with the following syntax.
Pointer Syntax
pointer = &variable;

A simple program for pointer illustration is given below:


#include <stdio.h>
int main()
{
int a=10; //variable declaration

ALL RIGHTS RESERVED TO SVTI 66


int *p; //pointer variable declaration
p=&a; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the address
printf("Value stored in a variable p is:%d\n",*p); //accessing the value
return 0;
}
Output:

Address stored in a variable p is:60ff08


Value stored in a variable p is:10

Operator Meaning
* Serves 2 purpose
i. Declaration of a pointer
ii. Returns the value of the referenced variable
& Serves only 1 purpose
Returns the address of a variable

Types of Pointers in C
Following are the different Types of Pointers in C:

Null Pointer
We can create a null pointer by assigning null value during the pointer declaration. This method
is useful when you do not have any address assigned to the pointer. A null pointer always
contains value 0.
Following program illustrates the use of a null pointer:
#include <stdio.h>
int main()
{
int *p = NULL; //null pointer
printf(“The value inside variable p is:\n%x”,p);
return 0;
}
Output:

The value inside variable p is:


0

Void Pointer
In C programming, a void pointer is also called as a generic pointer. It does not have any
standard data type. A void pointer is created by using the keyword void. It can be used to store
an address of any variable.

ALL RIGHTS RESERVED TO SVTI 67


Following program illustrates the use of a void pointer:
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d\n",sizeof(p));
return 0;
}
Output:

The size of pointer is:4

Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything. These types of C
pointers are not efficient because they may point to some unknown memory location which
may cause problems in our program and it may lead to crashing of the program. One should
always be careful while working with wild pointers.

Following program illustrates the use of wild pointer:


#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("\n%d",*p);
return 0;
}
Output

timeout: the monitored command dumped core


sh: line 1: 95298 Segmentation fault timeout 10s main

Other types of pointers in 'c' are as follows:


 Dangling pointer
 Complex pointer
 Near pointer
 Far pointer
 Huge pointer

C Pointers & Arrays with Examples


Traditionally, we access the array elements using its index, but this method can be
eliminated by using pointers. Pointers make it easy to access each array element.
#include <stdio.h>
int main()
{
int a[5]={1,2,3,4,5}; //array initialization
int *p; //pointer declaration
/*the ptr points to the first element of the array*/

ALL RIGHTS RESERVED TO SVTI 68


p=a; /*We can also type simply ptr==&a[0] */

printf("Printing the array elements using pointer\n");


for(int i=0;i<5;i++) //loop for traversing array elements
{
printf("\n%x",*p); //printing array elements
p++; //incrementing to the next element, you can also write p=p+1
}
return 0;
}
Output
1
2
3
4
5
Adding a particular number to a pointer will move the pointer location to the value obtained
by an addition operation. Suppose p is a pointer that currently points to the memory location
0 if we perform following addition operation, p+1 then it will execute in this manner:

Since p currently points to the location 0 after adding 1, the value will become 1, and hence
the pointer will point to the memory location 1.

C Pointers and Strings with Examples


A string is an array of char objects, ending with a null character '\ 0'. We can manipulate
strings using pointers. This pointer in C example explains this section
#include <stdio.h> Output
#include <string.h> First character is:H
int main() Next character is:e
{ Printing all the characters in a
char str[]="Hello Guru99!"; string
char *p; H
p=str; e
printf("First character is:%c\n",*p); l
p =p+1; l
printf("Next character is:%c\n",*p); o
printf("Printing all the characters in a
string\n"); G
p=str; //reset the pointer u
for(int i=0;i<strlen(str);i++) r
{ printf("%c\n",*p); u
p++; } 9
return 0; 9
} !

ALL RIGHTS RESERVED TO SVTI 69


Another way to deal strings is with an array of pointers like in the following program:
#include <stdio.h>
int main(){
char *materials[ ] = { "iron", "copper", "gold"};
printf("Please remember these materials :\n");
int i ;
for (i = 0; i < 3; i++) {
printf("%s\n", materials[ i ]);}
return 0;}

Output:

Please remember these materials:


iron
copper
gold

Advantages of Pointers in C
 Pointers are useful for accessing memory locations.
 Pointers provide an efficient way for accessing the elements of an array structure.
 Pointers are used for dynamic memory allocation as well as deallocation.
 Pointers are used to form complex data structures such as linked list, graph, tree,
etc.

Disadvantages of Pointers in C
 Pointers are a little complex to understand.
 Pointers can lead to various errors such as segmentation faults or can access a
memory location which is not required at all.
 If an incorrect value is provided to a pointer, it may cause memory corruption.
 Pointers are also responsible for memory leakage.
 Pointers are comparatively slower than that of the variables.
 Programmers find it very difficult to work with the pointers; therefore it is
programmer's responsibility to manipulate a pointer carefully.

Summary
A pointer is nothing but a memory location where data is stored.
A pointer is used to access the memory location.
There are various types of pointers such as a null pointer, wild pointer, void pointer and
other types of pointers.
Pointers can be used with array and string to access elements more efficiently.
We can create function pointers to invoke a function dynamically.
Arithmetic operations can be done on a pointer which is known as pointer arithmetic.
Pointers can also point to function which make it easy to call different functions in the case
of defining an array of pointers.
When you want to deal different variable data type, you can use a typecast void pointer.

ALL RIGHTS RESERVED TO SVTI 70


Chapter 10
STRUCTURE IN C PROGRAMMING

What is Structure?
Structure is a user-defined data type in C programming language that combines logically
related data items of different data types together.

All the structure elements are stored at contiguous memory locations. Structure type variable
can store more than one data item of varying data types under one name.

What is Union
Union is a user-defined data type, just like a structure. Union combines objects of different
types and sizes together. The union variable allocates the memory space equal to the space to
hold the largest variable of union. It allows varying types of objects to share the same location.

Syntax of Declaring Structure


struct [name of the structure]
{
type member1;
type member2;
type member3; };

Structure is declared using the "struct" keyword and name of structure. Number 1, number 2,
number 3 are individual members of structure. The body part is terminated with a semicolon
(;).

Example of Structure in C Programming


#include <stdio.h> Output:
struct student {
char name[60]; Enter the following information:
int roll_no;
float marks; Enter student name: James
} sdt;
int main() { Enter student roll number: 21
printf("Enter the following information:\n");
printf("Enter student name: "); Enter student marks: 67
fgets(sdt.name, sizeof(sdt.name), stdin);
printf("Enter student roll number: "); The information you have entered
scanf("%d", & sdt. roll_no); is:
printf("Enter students marks: ");
scanf("%f", & sdt.marks); Student name: John
printf("The information you have entered is: \n");
printf("Student name: "); Student roll number: 21
printf("%s", sdt.name);
printf("Student roll number: %d\n", sdt. roll_no); Student marks: 67.0
printf("Student marks: %.1f\n", sdt.marks);
return 0; }

ALL RIGHTS RESERVED TO SVTI 71


In the above program, a structure called student is created. This structure has three data
members: 1) name (string), 2) roll_no (integer), and 3) marks (float).

After this, a structure variable sdt is created to store student information and display it on the
computer screen.

Syntax of Declaring Union


union [name of union]
{
type member1;
type member2;
type member3;
};

Union is declared using the "union" keyword and name of union. Number 1, number 2, number
3 are individual members of union. The body part is terminated with a semicolon (;).

Example of Union in C Programming


#include <stdio.h> Output:
union item
{ 1101109601
int x;
float y; 20.199892
char ch;
}; a
int main( )
{
union item it;
it.x = 12;
it.y = 20.2;
it.ch = 'a';
printf("%d\n", it.x);
printf("%f\n", it.y);
printf("%c\n", it.ch);
return 0;
}

In the above program, you can see that the values of x and y gets corrupted. Only variable ch
prints the expected result. It is because, in union, the memory location is shared among all
member data types.

Therefore, the only data member whose value is currently stored, will occupy memory space.
The value of the variable ch was stored at last, so the value of the rest of the variables is lost.

ALL RIGHTS RESERVED TO SVTI 72


Structure Vs. Union

Here is the important difference between structure and union:

Structure Union
You can use a struct keyword to define a You can use a union keyword to define a
structure. union.
Every member within structure is assigned In union, a memory location is shared by all
a unique memory location. the data members.
Changing the value of one data member Changing the value of one data member will
will not affect other data members in change the value of other data members in
structure. union.
It enables you to initialize several members It enables you to initialize only the first
at once. member of union.
The total size of the structure is the sum of The total size of the union is the size of the
the size of every data member. largest data member.
It is mainly used for storing various data It is mainly used for storing one of the many
types. data types that are available.
It occupies space for each and every It occupies space for a member having the
member written in inner parameters. highest size written in inner parameters.
You can retrieve any member at a time. You can access one member at a time in the
union.
It supports flexible array. It does not support a flexible array.

Advantages of structure
Here are pros/benefits for using structure:

 Structures gather more than one piece of data about the same subject together in the
same place.
 It is helpful when you want to gather the data of similar data types and parameters like
first name, last name, etc.
 It is very easy to maintain as we can represent the whole record by using a single name.
 In structure, we can pass complete set of records to any function using a single
parameter.
 You can use an array of structure to store more records with similar types.

Advantages of union
Here, are pros/benefits for using union:

 It occupies less memory compared to structure.


 When you use union, only the last variable can be directly accessed.

ALL RIGHTS RESERVED TO SVTI 73


 Union is used when you have to use the same memory location for two or more data
members.
 It enables you to hold data of only one data member.
 Its allocated space is equal to maximum size of the data member.

Disadvantages of structure
Here are cons/drawbacks for using structure:

 If the complexity of IT project goes beyond the limit, it becomes hard to manage.
 Change of one data structure in a code necessitates changes at many other places.
Therefore, the changes become hard to track.
 Structure is slower because it requires storage space for all the data.
 You can retrieve any member at a time in structure whereas you can access one member
at a time in the union.
 Structure occupies space for each and every member written in inner parameters while
union occupies space for a member having the highest size written in inner parameters.
 Structure supports flexible array. Union does not support a flexible array.

Disadvantages of union
Here, are cons/drawbacks for using union:

 You can use only one union member at a time.


 All the union variables cannot be initialized or used with varying values at a time.
 Union assigns one common storage space for all its members.

KEY DIFFERENCES:
 Every member within structure is assigned a unique memory location while in union a
memory location is shared by all the data members.
 Changing the value of one data member will not affect other data members in structure
whereas changing the value of one data member will change the value of other data
members in union.
 Structure is mainly used for storing various data types while union is mainly used for
storing one of the many data types.
 In structure, you can retrieve any member at a time on the other hand in union, you can
access one member at a time.
 Structure supports flexible array while union does not support a flexible array.

ALL RIGHTS RESERVED TO SVTI 74


Chapter 11
C Files I/O: Create, Open, Read, Write and Close a File

C File management
A File can be used to store a large volume of persistent data. Like many other languages 'C'
provides following file management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
Following are the most important file management functions available in 'C,'
Function Purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

How to Create a File


Whenever you want to work with a file, the first step is to create a file. A file is nothing but
space in a memory where data is stored.

To create a file in a 'C' program following syntax is used,


FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
fopen is a standard function which is used to open a file.
 If the file is not present on the system, then it is created and then opened.
 If a file is already present on the system, then it is directly opened using this function.
fp is a file pointer which points to the type file.

Whenever you open or create a file, you have to specify what you are going to do with the file.
A file in 'C' programming can be created or opened for reading/writing purposes. A mode is
used to specify whether you want to open a file for any of the below-given purposes. Following
are the different types of modes in 'C' programming which can be used while working with a
file.

ALL RIGHTS RESERVED TO SVTI 75


File Mode Description
r Open a file for reading. If a file is in reading mode, then no data is deleted
if a file is already present on a system.
w Open a file for writing. If a file is in writing mode, then a new file is
created if a file doesn't exist at all. If a file is already present on a system,
then all the data inside the file is truncated, and it is opened for writing
purposes.
a Open a file in append mode. If a file is in append mode, then the file is
opened. The content within the file doesn't change.
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting a file
a+ open for reading and writing, appending to file

In the given syntax, the filename and the mode are specified as strings hence they must always
be enclosed within double quotes.
Example:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}

Output:
File is created in the same folder where you have saved your code.

You can specify the path where you want to create your file
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("D://data.txt", "w");
}

ALL RIGHTS RESERVED TO SVTI 76


How to Close a file
One should always close a file whenever the operations on file are over. It means the contents
and links to the file are terminated. This prevents accidental damage to the file.
'C' provides the fclose function to perform file closing operation. The syntax of fclose is as
follows,
fclose (file_pointer);
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);

The fclose function takes a file pointer as an argument. The file associated with the file pointer
is then closed with the help of fclose function. It returns 0 if close was successful and EOF (end
of file) if there is an error has occurred while file closing.

After closing the file, the same file pointer can also be used with other files. In 'C' programming,
files are automatically close when the program is terminated. Closing a file manually by writing
fclose function is a good programming practice.

Writing to a File
In C, when you write to a file, newline characters '\n' must be explicitly added.
The stdio library offers the necessary functions to write to a file:
 fputc(char, file_pointer): It writes a character to the file pointed to by file_pointer.
 fputs(str, file_pointer): It writes a string to the file pointed to by file_pointer.
 fprintf(file_pointer, str, variable_lists): It prints a string to the file pointed to by
file_pointer. The string can optionally include format specifiers and a list of variables
variable_lists.
The program below shows how to perform writing to a file:
fputc() Function:
#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[50];
char str[] = "Guru99 Rocks\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++) {
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}
Output:

ALL RIGHTS RESERVED TO SVTI 77


The above program writes a single character into the fputc_test.txt file until it reaches the next
line symbol "\n" which indicates that the sentence was successfully written. The process is to
take each character of the array and write it into the file.

1. In the above program, we have created and opened a file called fputc_test.txt in a write
mode and declare our string which will be written into the file.
2. We do a character by character write operation using for loop and put each character in
our file until the "\n" character is encountered then the file is closed using the fclose
function.

fputs () Function:
#include <stdio.h>
int main() {
FILE * fp;
fp = fopen("fputs_test.txt", "w+");
fputs("This is Guru99 Tutorial on fputs,", fp);
fputs("We don't need to use for loop\n", fp);
fputs("Easier than fputc function\n", fp);
fclose(fp);
return (0);
}
OUTPUT:

ALL RIGHTS RESERVED TO SVTI 78


1. In the above program, we have created and opened a file called fputs_test.txt in a write
mode.
2. After we do a write operation using fputs() function by writing three different strings
3. Then the file is closed using the fclose function.

fprintf()Function:
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("fprintf_test.txt", "w"); // "w" defines "writing mode"
/* write to file */
fprintf(fptr, "Learning C with Guru99\n");
fclose(fptr);
return 0;
}

OUTPUT:

1. In the above program we have created and opened a file called fprintf_test.txt in a write
mode.
2. After a write operation is performed using fprintf() function by writing a string, then
the file is closed using the fclose function.

ALL RIGHTS RESERVED TO SVTI 79


Reading data from a File
There are three different functions dedicated to reading data from a file
fgetc(file_pointer): It returns the next character from the file pointed to by the file pointer.
When the end of the file has been reached, the EOF is sent back.
fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string in a
buffer in which the NULL character '\0' is appended as the last character.
fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and
analyze data. It reads characters from the file and assigns the input to a list of variable pointers
variable_adresses using conversion specifiers. Keep in mind that as with scanf, fscanf stops
reading a string when space or newline is encountered.
The following program demonstrates reading from fputs_test.txt file using fgets(),fscanf() and
fgetc () functions respectively :
#include <stdio.h> Result:
int main() {
FILE * file_pointer; ----read a line----
char buffer[30], c; Learning C with Guru99

file_pointer = fopen("fprintf_test.txt", "r"); ----read and parse data---


printf("----read a line----\n"); -
fgets(buffer, 50, file_pointer); Read String1 |Learning|
printf("%s\n", buffer); Read String2 |C|
Read String3 |with|
printf("----read and parse data----\n"); Read String4 |Guru99|
file_pointer = fopen("fprintf_test.txt", "r"); //reset the ----read the entire file----
pointer Learning C with Guru99
char str1[10], str2[2], str3[20], str4[2];
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
printf("Read String1 |%s|\n", str1);
printf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read String4 |%s|\n", str4);

printf("----read the entire file----\n");

file_pointer = fopen("fprintf_test.txt", "r"); //reset the


pointer
while ((c = getc(file_pointer)) != EOF) printf("%c", c);

fclose(file_pointer);
return 0;
}

ALL RIGHTS RESERVED TO SVTI 80


1. In the above program, we have opened the file called "fprintf_test.txt" which was
previously written using fprintf() function, and it contains "Learning C with Guru99"
string. We read it using the fgets() function which reads line by line where the buffer
size must be enough to handle the entire line.
2. We reopen the file to reset the pointer file to point at the beginning of the file. Create
various strings variables to handle each word separately. Print the variables to see their
contents. The fscanf() is mainly used to extract and parse data from a file.
3. Reopen the file to reset the pointer file to point at the beginning of the file. Read data
and print it from the file character by character using getc() function until the EOF
statement is encountered
4. After performing a reading operation file using different variants, we again closed the
file using the fclose function.

Interactive File Read and Write with getc and putc


These are the simplest file operations. Getc stands for get character, and putc stands for put
character. These two functions are used to handle only a single character at a time.
Following program demonstrates the file handling functions in 'C' programming:
#include <stdio.h>
int main() {
FILE * fp;
char c;
printf("File Handling\n");
//open a file
fp = fopen("demo.txt", "w");
//writing operation
while ((c = getchar()) != EOF) {
putc(c, fp);

ALL RIGHTS RESERVED TO SVTI 81


}
//close file
fclose(fp);
printf("Data Entered:\n");
//reading
fp = fopen("demo.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);
return 0;
}
Output:

1. In the above program we have created and opened a file called demo in a write mode.
2. After a write operation is performed, then the file is closed using the fclose function.
3. We have again opened a file which now contains data in a reading mode. A while loop
will execute until the eof is found. Once the end of file is found the operation will be
terminated and data will be displayed using printf function.
4. After performing a reading operation file is again closed using the fclose function.

ALL RIGHTS RESERVED TO SVTI 82


Summary
 file is a space in a memory where data is stored.
 'C' programming provides various functions to deal with a file.
 A mechanism of manipulating with the files is called as file management.
 A file must be opened before performing operations on it.
 A file can be opened in a read, write or an append mode.
 Getc and putc functions are used to read and write a single character.
 The function fscanf() permits to read and parse data from a file
 We can read (using the getc function) an entire file by looping to cover all the file until
the EOF is encountered
 We can write to a file after creating its name, by using the function fprintf() and it must
have the newline character at the end of the string text.

ALL RIGHTS RESERVED TO SVTI 83


Chapter 12
Date and Time Function in C Programming

time() function in C
The time() function is defined in time.h (ctime in C++) header file. This function returns
the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is
not a null pointer, the returned value is also stored in the object pointed to by second.

Syntax:
time_t time( time_t *second )

Parameter: This function accepts single parameter second. This parameter is used to set
the time_t object which store the time.

Return Value: This function returns current calender time as a object of type time_t.

Program 1:
// C program to demonstrate Output:
// example of time() function. Seconds since January 1, 1970 =
#include <stdio.h> 1538123990
#include <time.h>

int main ()
{
time_t seconds;

seconds = time(NULL);
printf("Seconds since January 1, 1970 = %ld\n",
seconds);

return(0);
}

Example 2:
// C program to demonstrate Output:
// example of time() function. Seconds since January 1, 1970 =
1538123990
#include <stdio.h>
#include <time.h>
int main()
{ time_t seconds;

// Stores time seconds


time(&seconds);
printf("Seconds since January 1, 1970 = %ld\n",
seconds);
return 0; }

ALL RIGHTS RESERVED TO SVTI 84


getdate() and setdate() function in C with Examples

getdate()
getdate() function is defined in dos.h header file. This function fills the date structure *dt
with the system’s current date.
Syntax
struct date dt;
getdate(&dt);

Parameter: This function accepts a single parameter dt which is the object of structure
date.

Return Value: This method do not returns anything. It just gets the system date and sets it
in the specified structure.

Program 1: Implementation of getdate() function


// C program to demonstrate getdate() method

#include <dos.h>
#include <stdio.h>
int main()
{
struct date dt;
// This function is used to get
// system's current date
getdate(&dt);
printf("System's current date\n");
printf("%d/%d/%d",
dt.da_day,
dt.da_mon,
dt.da_year);
return 0;
}
Output:

setdate()
setdate() function is defined in dos.h header file. This function sets the system date to the
date in *dt.
Syntax
struct date dt;
setdate(&dt)

Parameter: This function accepts a single parameter dt which is the object of structure
date that has to be set as the system date.

ALL RIGHTS RESERVED TO SVTI 85


Return Value: This method do not returns anything. It just sets the system date as
specified.
Program 1: Implementation of setdate() function
// C program to demonstrate setdate() method
#include <dos.h>
#include <stdio.h>
int main()
{
struct date dt;
// This function is used to get
// system's current date
getdate(&dt);
printf("System's current date\n");
printf("%d/%d/%d",
dt.da_day,
dt.da_mon,
dt.da_year);
printf("Enter date in the format (date month year)\n");
scanf("%d%d%d", &dt.da_day, &dt.da_mon, &dt.da_year);
// This function is used to change
// system's current date
setdate(&dt);
printf("System's new date (dd/mm/yyyy)\n")
printf("%d%d%d", dt.da_day, dt.da_mon, dt.da_year);
return 0;
}

Output:

gettime c
gettime in c: gettime function is used to find current system time. We pass address of a
structure varibale of type ( struct time ).

C programming code for gettime


#include<stdio.h>
#include<dos.h>
main()
{
struct time t;
gettime(&t);
printf("Current system time is %d : %d : %d\n",t.ti_hour,t.ti_min,t.ti_sec);
return 0; }

ALL RIGHTS RESERVED TO SVTI 86

You might also like