C Programming (2) - Min
C Programming (2) - Min
Control Statements Iteration Statements Arrays gets() and puts() printf("Name: ");
a) If statement iteration statements are used to set up loops A loop It Collection of homogenous data items Arrays a kind of data structure that can store a fixed-size sequential #include<stdio.h> puts(name);// display string
It is used to a logical test and then take one of two is a statement whose job is to repeatedly execute collection of elements of the same type. An array is used to store a collection of data, but it is often more useful int main() return0;
possible action some other statement to think of an array as a collection of variables of the same type { }
if ( expression) i. The while Statement 1) One dimensional arrays char name[30]; Output
statement1; It will executed repeatedly as long as the expression Conceptually you can think of a one-dimensional array as a row, where elements are stored one after another printf("Enter name: "); Enter name: Tom Hanks
else is true gets(name);// read string Name: Tom Hanks
statement2; syntax: String function
Eg: while ( expression )statement;
String function
#include <stdio.h> Consider the following while statement: Syntax: data type array name[size];
strcpy() Copies a string to another string
int main () Main() datatype: It denotes the type of the elements in the array.
strcmp() Compares two string
{ { array_name: it is the name given to an array. It must be any valid identifier.
int a = 10; Is lower () Determine whether argument is a lower case letter
int n=0 size: It is the number of elements an array can hold.
if( a < 20 ) while (n < =10) Is upper() Determine whether argument is a upper case letter
here are some example of array declarations:
printf("a is less than 20\n" ); { To lower() To convert upper case to lower case letter
else printf(“%d”,n); To upper To convert lower case to upper case letter
printf("value of a is : %d\n", a); 1. Int num[100]; num is an array of type int, which can only store 100 elements of type int.
n++; 2. float temp[20]; temp is an array of type float, which can only store 20 elements of type float. Structures
return 0;
} 3. char ch[50]; ch is an array of type char, which can only store 50 elements of type char. Keyword struct is used for creating a structure. It is heterogeneous data type
}
b) Switch statement ii. The do Statement 2) Multidimensional array Structure declarations are somewhat more complicated than array declarations, since a structure must
It is multiple branch selection statement in which It is used to carry out looping operation in which a Syntax: data type array name[exp1][exp2]…[expn] be defined in terms of its individual members. In general terms, the composition of a structure may be defined
one group of statement is selected from several group of statement is executed repeatedly as long as Eg: int foo[1][2][3]; as
available the given condition is true
char vowels[1][5] = { struct tag char name[80];
Case expression: do statement while ( expression );
{'a', 'e', 'i', 'o', 'u'} { member 1; float balance; };
Statement1; iii. The for Statement
}; member 2; Create structure variable
Statement2; It is carry out looping operation in which group
3) Two-dimensional Arrays ..... struct Person
………………… statement is executed repeatedly for specific time
The simplest form of multidimensional array is the two-dimensional array. member m; {
Statementn; syntax:
Syntax: data type array name[exp1][exp2] }; char name[50];
for( expression1;expression2;expression3)statement
What are jumping statements? Eg; int table [10][5] int city No;
in looping operation sometime it may be desirable to skip or exit of the loop as soon as certain condition occurs Eg: struct account { float salary;
4) Three-dimensional Arrays
Break statement goto label; int acct-no; } person1, person2, p[20];
Syntax: data type array name[exp1][exp2][exp3]
It is used to terminate or exit from a switch Nested if char acct-type;
Eg: int table [10][5][3]
break; An if statement with in another if statement is called Union
nested if. string
Continue statement
When compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null Unions, like structures, contain members whose individual data types may differ from one another.
The loop does not terminate when a continue if (exp1)
character \0 at the end.You can use the scanf() function to read a string. members within a union all share the same storage area within the computer’s memory
statement is encountered if(exp2)
union [union tag] { Eg:
continue; statement1; Eg: scanf("%s", name);
member 1; union car
Eg: else Scanf( ) printf("Your name is %s.", name);
member 2; {
Goto statement statement2; #include <stdio.h> return 0;
... char name[50];
It is jumps from one point to another point within a else int main() }
function. member n; int price;
statement3; { output
}; } car1, car2, *car3;
char name[20]; Enter name: Dennis Ritchie
User-defined function
printf("Enter name: "); Your name is Dennis.
A function is a block of code that performs a specific task.
C allows you to define functions according to your need. These functions are known as user-defined functions. variables that are declared outside of all functions are known as external or global variables. They are Syntax of calloc()
Advantages accessible from any function inside the program ptr = (cast-type*)calloc(n, element-size);
1. The subprogram are easier to write, understand and debug. 3. Static Example:
2. In C, a function can call itself again. It is called a recursive function. Many calculations can be done A static variable is declared by using keyword static. For example; ptr = (float*) calloc(25, sizeof(float));
easily by using recursive functions such as calculation of factorial of a number, etc. Static int i;
Opening a file - for creation and edit
3. Reduction in size of program due to program code of a function can be used again and again, by calling 4. Register
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
it. The register storage class is used to define local variables that should be stored in a register instead of
The syntax for opening a file in standard I/O is:
4. The complexity of the entire program can be divided into simple subtask and then function subprograms RAM
ptr = fopen("fileopen","mode")
can be written for each subtask. {
Register int miles; For Example:
5. A library of a function can be designed and tested for use of every programmer.
} fopen("E:\\cprogram\\newprogram.txt","w");
ACCESSING A FUNCTION
Pointers : Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C fopen("E:\\cprogram\\oldprogram.bin","rb");
A function can be accessed by specifying its name, followed by a list of arguments enclosed in parentheses and
is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the Closing a File
separated by commas
data type such as int, float, char, double, short etc. The file (both text and binary) should be closed after reading/writing.
Parameter.
Advantages: Closing a file is performed using library function fclose().
Formal parameters are parameters as they appear in function declarations.
Pointers are used in C program to access the memory and manipulate the address. fclose(fptr); //fptr is the file pointer associated with file to be closed.
Formal parameters
1. Pointers reduce the length and complexity of a program.
the identifier used in a method to stand for the value that is passed into the method by a caller
2. They increase execution speed. File Meaning of Mode During Inexistence of file
For example, amount is a formal parameter of process Deposit.
3. A pointer enables us to access a variable that is defined outside the function. Mode
they appear in function declarations.
4. Pointers are more efficient in handling the data tables. R Open for reading. If the file does not exist, fopen() returns NULL.
Actual parameters
5. The use of a pointer array of character strings results in saving of data storage space in memory. W Open for writing. If the file exists, its contents are overwritten. If the file does
they appear in function calls.
How to create a pointer variable? not exist, it will be created.
the actual value that is passed into the method by a caller.
data_type* pointer_variable_name; A Open for append. i.e, Data is added If the file does not exists, it will be created.
For example, the 200 used when process Deposit is called is an actual parameter.
int* p; to end of file.
actual parameters are often called arguments
Reference operator (&) and Dereference operator (*) r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
RECURSION
As discussed, & is called reference operator. It gives you the address of a variable. Likewise, there is another w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does
Recursion is a process by which a action calls itself repeatedly, until some specified condition has been
operator that gets you the value from the address, it is called a dereference operator *. not exist, it will be created.
satisfied. The process is used for repetitive computations in which each action is stated in terms of a previous
result. Dynamic memory allocation a+ Open for both reading and If the file does not exists, it will be created.
In c storage is allocated dynamically by using the library function malloc() and calloc() to see that you must appending.
would normally express this problem as n! = 1 x 2 x 3 x … * x n, where n is the specified positive integer.
However, we can also express this problem in another way, by writing n! =n x (n I)! This is a recursive include i/o operation on files in c
statement of the problem, #include<stdio.h> fgetc()
STORAGE CLASSES I. C malloc() this is used to read a character from the stream
There are four different storage-class specifications in C: automatic, external, static and registerThey are The name "malloc" stands for memory allocation. intfgetc(FILE *pointer)
identified by the keywords auto, extern, static, and register, respectively The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of fputc()
Syntax: type void which can be casted into pointer of any form fputc() is used to write a single character at a time to a given file. It writes the given character at the position
storage_classvar_data_typevar_name; Syntax of malloc() denoted by the file pointer and then advances the file pointer.
1. automatic ptr = (cast-type*) malloc(byte-size) Syntax: intfputc(int char, FILE *pointer)
The auto storage class is the default storage class for all local variables. Example: char: character to be written.
{ ptr = (int*) malloc(100 * sizeof(int)); This is passed as its int promotion.
int mount; II. C calloc() pointer: pointer to a FILE object that identifies the
autoint month; stream where the character is to be written.
The name "calloc" stands for contiguous allocation.
}
The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of fgets()
2. External
memory and initializes them to zero. It reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1)
characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
char *fgets(char *str, int n, FILE *stream) 1. int fscanf(FILE *stream, const char *format [, argument, ...])
str : Pointer to an array of chars where the string read is copied. Example:
n : Maximum number of characters to be copied into string 1. #include <stdio.h>
(including the terminating null-character). 2. main(){
*stream : Pointer to a FILE object that identifies an input stream. 3. FILE *fp;
stdin can be used as argument to read from the standard input. 4. char buff[255];//creating char array to store data of file
returns :the function returns str 5. fp = fopen("file.txt", "r");
fputs 6. while(fscanf(fp, "%s", buff)!=EOF){
The C library function intfputs(const char *str, FILE *stream) writes a string to the specified stream up to 7. printf("%s ", buff );
but not including the null character 8. }
Syntax: 9. fclose(fp);
intfputs(const char *str, FILE *stream) 10. }
Example Output:
#include <stdio.h> Hello file by fprintf...
int main () Feof()
{ The C library function intfeof(FILE *stream) tests the end-of-file indicator for the given stream.
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program, this will create a file file.txt with the following content −
This is c programming. This is a system programming language.
fscanf
The C library function intfscanf(FILE *stream, const char *format, ...) reads formatted input from a stream.
fprintf()
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
1. int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
fscanf()
The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at
the end of file.
Syntax: