C Program
C Program
C is a powerful language.
Why Name 'C' was given to this language
Many of the ideas of C language were derived and taken from 'B‘
language.
BCPL and CPL are previous versions of 'B' language.
As many features came from B it was named as 'C'.
Why Name 'C' was given to this language
C programming
Language-Structured
and Disciplined C programs built from
approach to Variable and type
programming language declarations
Functions
Statements
Expressions
Structure Of “C” Programs
#include<conio.h>
void main()
{ Entry Point of program
-- other statements
}
Indicates starting of
program
Header files
do long
The Identifiers
Real Constants
The floating point constants such as 0.0083, -0.78, +67.89
etc.
Constants
Constants and variables must be declared before they can be used.
A constant declaration specifies the type, the name and the value
of the constant any attempt to alter the value of a variable defined
as constant results in an error message by the compiler
A variable declaration specifies the type, the name and possibly the
initial value of the variable.
When you declare a constant or a variable, the compiler: Reserves
a memory location in which to store the value of the constant or
variable.
Associates the name of the constant or variable with the memory
location.
Constants
Single Character Constants
String Constants
A string constant is a sequence of characters enclosed in
double quotes [ “ ” ];
• For example, “0211”, “Stack Overflow” etc.
Variables
A Variable is a data name that is used to store any data
value.
Variables are used to store values that can be changed
during the program execution.
Variables in C have the same meaning as
variables in algebra. That is, they represent some unknown,
or variable, value.
x=a+b
z + 2 = 3(y - 5)
Remember that variables in algebra are represented by a
single alphabetic character
Variables
Variables in C may be given representations containing multiple
characters. But there are rules for these representations.
Variable names in C :
1. A variable name can have letters (both uppercase and lowercase
letters), digits and underscore only.
2. The first letter of a variable should be either a letter or an
underscore. However, it is discouraged to start variable name with
an underscore. It is because variable name that starts with an
underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the
first 31 characters of a variable are checked by the compiler. So,
the first 31 letters of two variables in a program should be different.
Declaring Variables
Before using a variable, you must give the compiler some information
about the variable; i.e., you must declare it.
The declaration statement includes the data type of the variable.
Examples of variable declarations:
int length ;
float area ;
Variables are not automatically initialized. For example, after
declaration
int sum;
the value of the variable sum can be anything (garbage).
Thus, it is good practice to initialize variables when they are declared.
Once a value has been placed in a variable it stays there until the
program alters it.
Datatypes
Data Type is used to define the type of value to be used in a Program.
Based on the type of value specified in the program specified amount
of required Bytes will be allocated to the variables used in the
program
Datatypes
There are three classes of data types here::
Primitive data types
– int, float, double, char
Aggregate OR derived data types
– Arrays come under this category
– Arrays can contain collection of int or float or char or double data
User defined data types
– Structures and enum fall under this category.
Datatypes
Type Size Representation Minimum range Maximum range
char, signed char 8 bits ASCII -128 127
unsigned char bool 8 bits ASCII 0 255
short, signed short 16 bits 2's complement -32768 32767
printf(“id=%d”,a);
printf(“id=%lf”,b);
printf(“id=%d”,c);
printf("\n%lf",d);
return 0: }
OPERATORS
Operators
Operator is a Symbol that tells or instructs the Compiler to perform
certain Mathematical or Logical manipulations (Calculations).
Operators are used in a program to work on data and variables.
Operators in general form a part of Mathematical or Logical
expression.
Operators are generally classified into different types. They are
described one below another as follows.
C Logical Operators. An expression containing logical operator
returns either 0 or 1 depending upon whether expression results
true or false.
Logical operators are commonly used in decision making in C
programming.
Operators
1.Arithmetic Operators • Arithmetic (+,-,*,/,%)
• Relational (<,>,<=,>=,==,!=)
2.Relational Operators
• Logical (&&,||,!)
3.Logical Operators • Bitwise (&,|)
• Assignment (=)
4.Assignment Operators • Compound assignment(+=,*=,-=,/=,
%=,&=,|=)
5.Conditional Operators • Shift (right shift >>, left shift <<)
6.Unary operators
Arithmetic operators
Arithmetic operators are used
Operator Meaning Details
to perform Arithmetic
operations. They form a part + Addition Performs addition on integer numbers, floating point
of program. Programs can be numbers. The variable name which is used is the
Example Example
Example Example
Operator Meaning Simp. Assign Shorthand
~= Assignone’s complement
The result of the Logical AND operator will be TRUE If both value is
TRUE. If any one of the value is false then the result will be always
False. The result is similar to basic Binary multiplication.
If any of the expression is true the result is true else false otherwise.
The result is similar to basic Binary addition.
It acts upon single value. If the value is true result will be false and if
the condition is false the result will be true. The logical not operator
takes single
11
Eg(!a)
Logical Operators
#include <stdio.h> result = (a != b) || (c < b);
int main() printf("(a != b) || (c < b) is %d \n",
result);
{
int a = 5, b = 5, c = 10, result; result = !(a != b);
printf("!(a != b) is %d \n", result);
result = (a == b) && (c > b);
result = !(a == b);
printf("(a == b) && (c > b) is %d \n", printf("!(a == b) is %d \n", result);
result);
result = (a == b) && (c < b); return 0;
}
printf("(a == b) && (c < b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
Unary Operator-
#include <stdio.h>
Unary Operator-it performs single int main()
{
operator int a = 10, b = 100;
Ex:++,-- float c = 10.5, d = 100.5;
is (exp1)?(exp2):(exp3);
z=((x>y)?x:y);
}
DECISION MAKING
&
LOOPING
Declaring Variables
It is used to perform operation based on the condition given. There are 5
conditional control structures. They are:
1.If
2.If.else if
3.Nested if
4.switch.
Declaring Variables
If structure:
Syntax:
if(condition)
{
statement;
}
Declaring Variables
#include <stdio.h>
int main()
{
int age;
printf("Enter age : ");
scanf("%d", &age);
if (age >=60)
printf("You can have the pension");
return 0;
}
Declaring Variables
if..else structure:
In this structure if the condition satisfies the statement under it will be
executed. Else the statements under the else part will be executed.
Syntax:
if(condition)
{
statement;
}
else
{
statement;
}
Declaring Variables
#include <stdio.h>
int main()
{
int age;
printf("Enter age : ");
scanf("%d", &age);
if (age >= 18)
printf("You can Vote!");
else
printf("You cant Vote!");
return 0;
}
if..elseif structure:
if(condition)
In this structure if the condition {
satisfies the statement under if will be statement 1;
executed. Else the condition }
else if(condition)
becomes true in elseif part the {
statements under it will be executed. statement 2;
Else if both the condition becomes }
…..
false the default else part will be …..
executed. else if(condition)
{
statement n;
}
else
{
Stmt;
}
Declaring Variables
#include<stdio.h> if(score>=90 && score<=100)
int main() grade = 'A';
else if(score>=80)
{ grade = 'B';
int score; else if(score>=70)
grade = 'C';
char grade; else if(score>=60)
printf("Enter score(0-100): "); grade = 'D';
else if(score>=50)
scanf("%d",&score); grade = 'E';
if(score<0 || score>100) { else
grade = 'F';
printf("Invalid Score"); printf("Grade: %c\n", grade);
return 0;
return 0; }
}
Switch:
Alternative extension of if else switch (expression)
statement which allows a variable to {
case 1: statement 1;
be tested for equality against list of break;
values. Each value is called a “case” case 2: statement 2;
and the variable is being switched is break;
….
checked for switch case. ….
case n: statement n;
break;
default: statement;
break;
}
Declaring Variables
#include <stdio.h> switch (choice){
void main() case 1:
{ printf("%d + %d = %d\n", a, b, a + b);
int choice; break;
case 2:
printf("Select an option from the list
printf("%d - %d = %d\n", a, b, a - b);
below:\n");
break;
printf("1. Addition\n"); case 3:
printf("2. Subtraction\n"); printf("%d * %d = %d\n", a, b, a * b);
printf("3. Multiplication\n"); break;
printf("4. Division\n"); case 4:
printf("5. Modulus\n"); printf("%d / %d = %d\n", a, b, a / b);
break;
printf("6. Exit\n");
case 5:
printf("Enter your choice: "); printf("%d %% %d = %d\n", a, b, a % b);
scanf("%d", &choice); break;
int a, b; case 6:
// read two numbers printf("Exiting...\n");
printf("Enter two numbers: "); break;
default:
scanf("%d %d", &a, &b); printf("Invalid choice\n");
}}
Nested if:
If an if structure comes inside another if structure, then it is called as nested
if.
Syntax:
if(condition)
{
if(condition)
{
statement;
}
statement;
}
Nested if:
#include<stdio.h>
void main()
{
int x=45;
if(x<90){
if(x>30){
printf(“The student is brilliant\n”);
}
printf(“The student is not brilliant\n”);
}
Printf(“The value of x=%d\n”,x);
}
Nested if:
Loops are used to perform a specific task many times till the condition gets
satisfied. Using loop structure we can make a statement ‘n’ no of times, till
our condition gets satisfied.
1.While
2.Do while
3.For
Nested if:
while:
While is the entry control statement. If the test condition is true the body of
the loop will be executed.
Syntax:
while(test condition)
{
body of the loop;
}
Nested if:
#include<stdio.h>
int main(){
int i=1,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
while(i<=n)
{
printf("\n%d",i);
i++;
}
return 0;
}
Nested if:
do-while:
do-while is the exit control statement. Body of the loop will be executed at
least once.
Syntax:
do
{
body of the loop;
}
while(test condition);
Nested if:
#include<stdio.h>
int main(){
int i=0,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
do
{
printf("\n%d",i);
i+=2; //i=i+2
}while(i<=n);
return 0;
}
Nested if:
For loop:
Execute a statement or group of statement repeatedly for a noun number of
times.
Syntax:
for (i=initial condition;testcondition;inc/dec)
{
body of the loop;
}
Nested if:
Eg prog:
#include<stdio.h>
int main(){
int i,n;
printf("\nEnter The Limit : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n%d",i);
}
return 0;}
Nested if:
Nested for loop:
In this loop structure more than one form can be nested. In this one loop
stands for row and another stands for column.
Syntax:
for(initialization; condition; inc/dec){
for(initialization; condition; inc/dec){
statement 1;
statement 2;
statement n;
}
}
Nested if:
void main()
{
int i,j; int n;
printf("Enter the value of N:\n");
scanf("%d",&n);
printf("\n");
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
printf("%d\t",j);
}
printf("\n");
}}
Nested if:
#include <stdio.h>
int main() {
int i = 0;
int i;
while (i < 10) {
for (i = 0; i < 10; i++) { if (i == 4) {
if (i == 4) { break;
}
break; printf("%d\n", i);
} i++;
}
printf("%d\n", i);
}
return 0;
}
Nested if:
#include <stdio.h>
int main() {
int i = 0;
int i;
while (i < 10) {
for (i = 0; i < 10; i++) { if (i == 4) {
if (i == 4) { continue;
}
continue; printf("%d\n", i);
} i++;
}
printf("%d\n", i);
}
return 0;
}
STRING
Declaring Variables
Strings are actually one-dimensional array of characters terminated by a null
character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.
The following declaration and initialization create a string consisting of the
word "Hello". To hold the null character at the end of the array, the size of
the character array containing the string is one more than the number of
characters in the word "Hello.“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above
statement as follows −
char greeting[] = "Hello";
.
Declaring Variables
strlen(str) – To find length of string str
strrev(str) – Reverses the string str as rts
strcat(str1,str2) – Appends str2 to str1 and returns str1
strcpy(st1,st2) – copies the content of st2 to st1
strcmp(s1,s2) – Compares the two string s1 and s2
strcmpi(s1,s2) – Case insensitive comparison of strings
.
Declaring Variables
// C program to illustrate strings
#include<stdio.h>
#include<string.h>
int main()
{
// declare and initialize string
char str[] = “gtec";
// print string
printf("%s",str);
return 0;
}
.
Declaring Variables
/#include<stdio.h>
#include<string.h>
int main(){
char c[20],a[20];
char x[10]={'G','T','E','C','\0'};
char y[10]={'E','D','U','A','T','\0'};
printf("x : %s",x);
printf("\nEnter The String : ");
gets(c);
printf("c : %s",c);
return 0;
}
Declaring Variables
/#include<stdio.h>
#include<string.h>
int main(){
printf("\nCompare : %d ",strcmp(x,c));//String Compare
printf("\nLength : %d ",strlen(c));//String Length
printf("\nReverse : %s ",strrev(c));//String Reverse
printf("\nUppercase : %s ",strupr(c));//String Upper
printf("\nLowercase : %s ",strlwr(c));//String Lower
printf("\nCopy : %s ",strcpy(a,c));//String Copy
strcat(x,y);
printf("\nConcatenation : %s ",x);//String Concatenation
return 0;}
Declaring Variables
• pow(n,x) – evaluates n^x
• ceil(1.3) – Returns 2
• floor(1.3) – Returns 1
• abs(num) – Returns absolute value
• log(x) - Logarithmic value
• sin(x)
• cos(x)
• tan(x)
.
Declaring Variables
Functions:
A Function is a group of statement that together perform a task.
Every C program has atleast one function which is called main() function.
• Functions will have return types int, char, double, float or even structs and
arrays
• Return type is the data type of the value that is returned to the calling point
after the called function execution completes
Declaring Variables
#include<stdio.h>
void fun(int a); //declaration
int main()
{
fun(10); //Call
}
void fun(int x) //definition
{
printf(“%d”,x);
}
Declaring Variables
Actual parameters are those that are used during a function call
Formal parameters are those that are used in function definition and function
declaration
Declaring Variables
Types of function calling
float marks[100];
The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:
– One-dimensional arrays
– Multidimensional arrays (will be discussed in next chapter)
Declaring Variables
Syntax:
Now, let us see the example to declare the array. int marks[5];
Declaring Variables
Few key notes:
• Arrays have 0 as the first index not 1. In this example, mark[0]
• If the size of an array is n, to access the last element, (n-1) index is used. In
this example, mark[4]
• Suppose the starting address of mark[0] is 2120d. Then, the next address,
a[1], will be 2124d, address of a[2] will be 2128d and so on. It's because the
size of a float is 4 bytes.
Declaring Variables
Initialization of C Arraay
The simplest way to initialize an array
is by using the index of eaach
element. We can initialize each
eleement of the array by using the
index. Consider the following
example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Declaring Variables
Single Dimensional Array:
};
int main(){
struct student o,o2;
o.name="GTEC COMPUTER EDUCATION";
o.age=24.;
o.per=85.5;
Declaring Variables
/Local and Global Scope Structure in C s.m1=50; s.m2=50; s.m3=50;
Programming printf("\nMark-1: %d",s.m1);
#include<stdio.h> printf("\nMark-2 : %d",s.m2);
struct student{ printf("\nMark-3 : %d",s.m3);}
int main(){
char *name;
struct student o;
int age; o.name="Naveen";
float per;}; o.age=30;
void total(){ o.per=85.5;
struct mark printf("\nName :
{ %s",o.name);
printf("\nAge : %d",o.age);
int m1,m2,m3;
printf("\nPercent : %f",o.per);
}s; total();
return 0;}
Declaring Variables
/Access members of structure using pointer.
#include<stdio.h>
struct student{
char *name;
int age;
float per;};
int main(){
struct student o={"RAM",25,75.5};
struct student *ptr=&o;
printf("\nName : %s",(*ptr).name);
printf("\nAge : %d",ptr->age);
printf("\nPercent : %f",ptr->per);
return 0;}
Declaring Variables
struct detail{ scanf("%d",&det.age);
int age; printf("Enter the address:\n");
char name[50]; scanf("%s",det.address);
printf("Enter the pincode:\n");
char address[250];
scanf("%ld",&det.pincode);
long int contno; printf("Enter the contact number:\n");
long double pincode; }; scanf("%ld",&det.contno);
void main() printf("\nthe name: %s",det.name);
{ printf("\nthe age: %d",det.age);
struct detail det; printf("\nthe address:%s",det.address);
printf("\nthe pincode: %ld",det.pincode);
printf("Enter the name:\n");
printf("\nthe contact number: %ld",det.contno);
scanf("%s",det.name); }
printf("Enter the age:\n");
Declaring Variables
/#include <stdio.h>
#include <string.h>
struct student
{
int id; strcpy(record.name, "Raju");
record.percentage = 86.5;
char name[20]; printf(" Id is: %d \n",
float percentage; record.id);
printf(" Name is: %s \n",
}; record.name);
printf(" Percentage is: %f \n",
int main() record.percentage);
{ getch( );
return 0;
struct student record ; }
record.id=1;
Declaring Variables
/Structure as function arguments in C Programming
#include<stdio.h>
struct student{
char *name;
int age;
float per;};void display(struct student o){
printf("\nName : %s",o.name);
printf("\nAge : %d",o.age);
printf("\nPercent : %f",o.per);}int main(){
struct student o={"RAM",25,75.5};
display(o);
return 0;}
//Array of Structure Objects
#include<stdio.h>
struct student{ printf("\n------------------------------");
printf("\nName : %s",o[0].name);
char *name; printf("\nAge : %d",o[0].age);
int age; printf("\nPercent : %f",o[0].per);
printf("\n------------------------------");
float per;};int main(){ printf("\nName : %s",o[1].name);
struct student o[2]; printf("\nAge : %d",o[1].age);
printf("\nPercent : %f",o[1].per);
o[0].name="Ram Kumar"; printf("\n------------------------------\n\n");
o[0].age=25;
return 0;}
o[0].per=65.25;
o[1].name="Sam Kumar";
o[1].age=12;
o[1].per=80;
Declaring Variables
A union is a special data type available in C that allows to store different data
types in the same memory location.
You can define a union with many members, but only one member can
contain a value at any given time.
Unions provide an efficient way of using the same memory location for
multiple-purpose.
Declaring Variables
DEFINING A UNION
To define a union, you must use the union statement in the same way as you
did while defining a structure.
The union statement defines a new data type with more than one member for
your program. The format of the union statement is as follows −
Syntax:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Declaring Variables
#include<stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
Declaring Variables
struct demo{
int a;//4
char b;};
union udemo{
int a;//4
char b;}o;
int main(){
o.a=65;
printf("\nUnion A : %d",o.a);
printf("\nUnion B : %c",o.b);
return 0;}
Declaring Variables
The typedef operator is used for creating alias of a data type
For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
Declaring Variables
#include <stdio.h>
#include <string.h>
strcpy(record.name, "Raju");
typedef struct student record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
{ printf(" Name is: %s \n", record.name);
int id; printf(" Percentage is: %f \n",
record.percentage);
char name[20]; return 0;
float percentage; }
} status;
int main()
{
status record;
record.id=1;
Declaring Variables
Pointer is a special variable that stores address of another variable
Addresses are integers. Hence pointer stores integer data
Size of pointer = size of int
Pointer that stores address of integer variable is called as integer pointer and is
declared as int *ip;
Declaring Variables
• Pointers that store address of a double, char and float are called as double
pointer, character pointer and float pointer respectively.
• char *cp
• float *fp
• double *dp;
• Assigning value to a pointer
int *ip = &a; //a is an int already declared
Declaring Variables
int a;
a=10; //a stores 10
int *ip;
ip = &a; //ip stores address of a (say 1000)
ip : fetches 1000
*ip : fetches 10
* Is called as dereferencing operator
Declaring Variables
• Calling a function with parameters passed as values
5 #ifndef
Returns true if this macro is not
defined.
6 #if
Tests if a compile time condition is
true.
Declaring Variables
Program for #define Program for #define
Ex: Ex:
#include <stdio.h>
#include<stdio.h> #define MIN(a,b) ((a)<(b)?(a):(b))
#define PI 3.14 void main()
{
void main() clrscr( );
{ printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
printf("%f",PI);
}
Declaring Variables
Program for #undef variable. But before being undefined, it was used by square
Ex: variable.
Ex:
#include <stdio.h> #include <stdio.h>
#include<conio.h> #include<conio.h>
#define number 15
#define PI 3.14 int square=number*number;
#undef PI #undef number
void main()
void main() {
{ clrscr( );
printf("%d",square);
clrscr( ); getch( );
}
printf("%f",PI);
getch( );
}
Program for #ifdef using NOINPUT
#include <stdio.h> #include <stdio.h>
#define NOINPUT void main()
{
void main() int a=0;
{ clrscr( );
#ifdef NOINPUT
int a=0; a=2;
#ifdef NOINPUT #else
printf("Enter a:");
a=2; scanf("%d", &a);
#else #endif
printf("Value of a: %d\n", a);
printf("Enter a:"); }
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
}
Declaring Variables
• A file is a collection of related data that a computers treats as a single unit.
• Computers store files to secondary storage so that the contents of files
remain intact when a computer shuts down.
• When a computer reads a file, it copies the file from the storage device to
memory; when it writes to a file, it transfers data from memory to the storage
device.
• C uses a structure called FILE (defined in stdio.h) to store the attributes of
a file.
Declaring Variables
1. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file name.
3. Read or write the data.
4. Close the file.
Declaring Variables
• fopen - open a file- specify how its opened (read/write) and type (binary/text)
• fclose - close an opened file
• fread - read from a file
• fwrite - write to a file
• fseek/fsetpos - move a file pointer to somewhere in a file.
• ftell/fgetpos - tell you where the file pointer is located.
Declaring Variables
• r+ - open for reading and writing, start at beginning
• w+ - open for reading and writing (overwrite file)
• a+ - open for reading and writing (append if file exists)
Declaring Variables
Declaring Variables
Declaring Variables
• The file open function (fopen) serves two purposes:
– It makes the connection between the physical file and the stream.
– It creates “a program file structure to store the information” C needs to
process the file.
• Syntax:
filepointer=fopen(“filename”, “mode”);
Declaring Variables
• The file mode tells C how the
program will use the file.
• The filename indicates the system
name and location for the file.
• We assign the return value of
fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”,
“w”);
spData = fopen(“A:\\MYFILE.TXT”,
“w”);
Declaring Variables
• When we finish with a mode, we need to close the file before ending the
program or beginning another mode with that same file.
• To close a file, we use fclose and the pointer variable:
fclose(spData);
Declaring Variables
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
Declaring Variables
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
Declaring Variables
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
Declaring Variables
write a single character to the output file, pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
Declaring Variables
• There are a number of ways to test for the end-of-file condition. Another way
is to use the value returned by the fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
Declaring Variables
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
}
Declaring Variables
#include <stdio.h>
#include<conio.h>
void main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("\n%c",ch);
}
getch();
}
Declaring Variables
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.
Remarks:
fwrite appends a specified number of equal-sized data items to an output file.
"ftell" returns the current position for input or output on the file
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
Read a File in C Programming//r w a
#include<stdio.h>
int main(){
FILE *fp; }
char c; return 0;}
sample.txt
fp=fopen("sample.txt","r"); GTec Education
if(fp==NULL) Ambattur
Chennai-53.
{ 904123489
printf("\nFile Cant Open or File Not Found..");
}
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
printf("%c",c);
Read a File in C Programming//r w a
/Write a File#include<stdio.h>
int main(){
FILE *fp;
//fp=fopen("sample.txt","w");
fp=fopen("sample.txt","a");
fprintf(fp,"Gtec Computer Education\n");
fclose(fp);
return 0;}
Declaring Variables
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program.
Four types of storage class:
auto
register
static
extern
Declaring Variables
The auto Storage Class
The auto storage class is the default storage class for all local variables.
Syntax:
{
int mount;
auto int month;
}
The register Storage Class
The register storage class is used to define local variables that should be
stored in a register instead of RAM.
Syntax:
{
register int miles;
}
Declaring Variables
The static Storage Class
The static storage class instructs the compiler to keep a local variable in
existence during the life-time of the program instead of creating and
destroying it each time it comes into and goes out of scope.
Declaring Variables
Example 1
1.#include<stdio.h>
2.static char c;
3.static int i;
4.static float f;
5.static char s[100];
6.void main ()
7.{
8.printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printe
d.
9.}
Declaring Variables
1.#include<stdio.h>
2.void sum()
3.{
4.static int a = 10;
5.static int b = 24;
6.printf("%d %d \n",a,b);
7.a++;
8.b++;
9.}
10.void main()
11.{
12.int i;
13.for(i = 0; i< 3; i++)
14.{
15.sum();}}
Declaring Variables
1.#include <stdio.h>
1.#include <stdio.h>
2.int main() 2.int a;
3.{ 3.int main()
4.extern int a; 4.{
5.printf("%d",a); 5.extern int a = 0;
6.printf("%d",a);
6.} 7.}
1.#include <stdio.h>
2.int a; 1.#include <stdio.h>
2.int main()
3.int main() 3.{
4.{ 4.extern int a;
5.extern int a; o a 5.printf("%d",a);
6.}
6.printf("%d",a);
int a = 20;
7.}