All Rights Reserved To Svti 1
All Rights Reserved To Svti 1
C Files I/O: Create, Open, Read, Write and Close a File .................................. 74
Hierarchy of Computer
Hierarchy of computer
Computer Language
A computer language is a set of rules and conventions used to convey the
information to a computer.
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 Learn C
1. Compact, fast and powerful
2. “Mid-level” language
3. Standard for program development (Wide Acceptance)
Flowchart In Programming
A flowchart is a diagrammatic representation of an algorithm. A flowchart can be helpful for
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.
c. Assembler
Assembler is a translator which is used to translate the assembly language code into machine
language code.
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.
#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.
<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
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.
#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.
#include<stdio.h>
void main (void)
{
printf ( “ The letter %c is” , ‘ j ’ ) ;
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?
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
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.
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;
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.
TYPE EXAMPLES
Char ‘A’ ‘b’ ‘$’ ‘9’
Int 1 250 4500
Float 3.5 42.56 345.6789
Double 3.5647290… 486.145875...
Void Valueless
The following table shows the size and range of the type-specifiers on most common
implementations :
#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
#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);
}
#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); }
#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);
}
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);
Output:
My name is Ahmed. My Roll no is 100. My section is A and my GPA is3.25.
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.
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 );
scanf ( )
Examples:
int x,y; float
grade; char
letter;
{
int a, b, mul;
getch();
}
{
int a, b, 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(); }
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.";
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
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();
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'
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); }
V op = exp;
Here,
V= variable
exp = expression and
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
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 ]
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
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:
2. c = b-- - ++a ;
/* What are the values of a, b, c now?*/
(Answers: a = 6, b = 0, c = -5)
Decisions in C
C language needs decisions be taken for desired results which are below
1. simple if
2. if-else
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:
}
return 0;
}
OUTPUT:
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.
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.
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( );
}
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 ’ } ;
String Functions:
Included in String.h are several more String related function that are free for you to
use.
//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
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 ) ;
}
#include<stdio.h>
#include<time.h>
int main()
{
printf("\n\n\t\t***now, the time is to become a programmer*** \n\n\n");
printf("\nThis program has been written at (date and time): %s", ctime(&t));
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
OUTPUT:
1st random number : 83 2nd random number : 86 3rd random number: 16816927
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.
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 " );
}
An argument is the value passed to the function and the parameter is the variable that
received the value.
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.
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");
}
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();
}
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.
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.
int main()
{
greatNum(); // function call
return 0;
#include<stdio.h>
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
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;
}
#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;
}
}
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.
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
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;
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:
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.
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.
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.
Output:
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.
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.
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
(;).
After this, a structure variable sdt is created to store student information and display it on the
computer screen.
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 (;).
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.
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:
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:
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.
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
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.
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");
}
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:
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:
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.
fclose(file_pointer);
return 0;
}
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.
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;
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.
#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.
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 ).