Single characters can be replaced in a string. Given the following declarations, several things are possible. [Read more…] about How can we replace single character in a String
What is the difference between printf and sprintf
sprintf: This Writes formatted data to a character string in memory instead of stdout [Read more…] about What is the difference between printf and sprintf
File management in C
The getw and putw functions, The fprintf & fscanf functions, Random access to files and fseek function. C supports a number of functions that have the ability to perform basic file operations, which include: [Read more…] about File management in C
What is Structures and Unions
Structures and Unions, Giving values to members, Initializing structure, Functions and structures, Passing structure to elements to functions, Passing entire function to functions, Arrays of structure, Structure within a structure and Union. [Read more…] about What is Structures and Unions
Advantages of Unions
Union is a collection of data items of different data types. It can hold data of only one member at a time though it has members of different data types. If a union has two members of different data types, they are allocated the same memory. [Read more…] about Advantages of Unions
Define a Structure with suitable program
A structure is a user-defined data type containing a collection of logically related data which may be of different types such as int, double, char, and so on. All of them are encapsulated (packed) in a single unit with a single name. The classes of C++ are in fact generalization of C-structures. A class in C++ with only public members is similar to a C-structure. All members of a structure in C are by default public. However, in a class declaration in C++, if there is no access specifier, the members are private by default. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. This restriction is not there in structures. [Read more…] about Define a Structure with suitable program
What is Arrays? Type of array
Declaration of arrays, initialization of arrays, Multi dimensional Arrays, Elements of multi dimension arrays and initialization of multidimensional arrays. The C language provides a capability that enables the user to define a set of ordered data items known as an array. [Read more…] about What is Arrays? Type of array
What is arrays? How is Array declared. Explain with Example
Often, we have to deal with groups of objects of same type such as names of persons, instrument readings in an experiment, roll numbers of students, and so on. These groups can be conveniently represented as elements of arrays. An array is defined as a sequence of objects of the same data type. All the elements of an array are either of type int (whole numbers), or all of them are of type char, or all of them are of floating decimal point type, etc. [Read more…] about What is arrays? How is Array declared. Explain with Example
How can we declare an Array
Declaring Arrays : Arrays are declared with the bracket punctuators [ ], as shown in the following syntax :
storage-class-specifier(opt) type-specifier declarator [constant-expression-list(opt)];
The following example shows a declaration of a 10-element array of integers, a
variable called table_one :
int table_one[10];
The type-specifier shows the data type of the elements. The elements of an array can be of any scalar or aggregate data type. The identifier table_one specifies the name of the array. The constant expression 10 gives the number of elements in a single dimension. Arrays in C are zero-based; that is, the first element of the array is identified with a 0 subscript, such as the one shown in the following example :
int x[5];
x[0] = 25; /* The first array element is assigned the value 25 */
The expression between the brackets in the declaration must be an integral constant expression with a value greater than zero. Omitting the constant expression creates an incomplete array declaration, which is useful in the following cases :
- If the array is declared external and its storage is allocated by a definition in another place, you can omit the constant expression for convenience when the array name is declared, as in the following example :
extern int array1[];
int first_function(void)
{
.
.
.
}
In a separate compilation unit :
int array1[10];
int second_function(void)
{
.
.
.
}
The array size specifier may only be omitted from the first pair of brackets in a multidimensional array declaration. This is because an array’s elements must have complete types, even if the array itself has an incomplete type.
- If the declaration of the array includes initializers, you can omit the size of the array, as in the following example :
char array_one[] = “Shemps”;
char array_two[] = { ‘S’, ‘h’, ‘e’, ‘m’, ‘p’, ‘s’, ‘\0’ };
The two definitions initialize variables with identical elements. These arrays have seven elements: six characters and the null character (\0), which terminates all character strings. The size of the array is determined from the number of characters in the initializing character-string constant or initialization list. Initializing an incomplete array completes the array type. An array is completed at the end of its initializer list.
- If you use the array as a function parameter, the array must be defined in the calling function. However, the declaration of the parameter in the called function can omit the constant expression within the brackets. The address of the first element of the array is passed. Subscripted references in the called function can modify elements of the array. The following example shows how to use an array in this manner :
main()
{
/* Initialize array */
static char arg_str[] = “Thomas”;
int sum;
sum = adder(arg_str); /* Pass address of first array element */
.
.
.
}
/* adder adds ASCII values of letters in array */
int adder( char param_string[])
{
int i, sum = 0; /* Incrementer and sum */
/* Loop until NULL char */
for (i = 0; param_string[i] != ‘\0’; i++)
sum += param_string[i];
return sum;
}
After the function adder is called, parameter param_string receives the address of the first character of argument arg_str, which can then be accessed in adder . The declaration of param_ string serves only to give the type of the parameter, not to reserve storage for it.
Array members can also be pointers. The following example declares an array of floating-point numbers and an array of pointers to floating-point numbers :
float fa[11], *afp[17];
When a function parameter is declared as an array, the compiler treats the declaration as a pointer to the first element of the array. For example, if x is a parameter and is intended to represent an array of integers, it can be declared as any one of the following declarations :
int x[];
int *x;
int x[10];
Note that the specified size of the array does not matter in the case of a function parameter, since the pointer always points to only the first element of the array.
C supports arrays declared as an array of arrays. These are sometimes called multidimensional arrays. Consider the following example, where variable table_one is a two-dimensional array containing 20 integers :
int table_one[10][2];
Arrays are stored in row-major order, which means the element table_one[0][0] (in the previous example) immediately precedes table_one[0][1], which in turn immediately precedes table_one[1][0] .
How do I know how many elements an Array can hold
The amount of memory an array can consume depends on the data type of an array. In DOS environment, the amount of memory an array can consume depends on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). [Read more…] about How do I know how many elements an Array can hold
Characteristics of Arrays in C
1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent memory locations.
3) Two-dimensional array elements are stored row by row in subsequent memory locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array size must be a constant expression and not a variable.
Compare and relate Pointers with Arrays
Pointers and Arrays : Data objects in an array can be referenced through pointers instead of using array subscripts. The data type of such a pointer is referred to as “pointer to array of type“. The array name itself behaves like a pointer, so there are several alternative methods to accessing array elements. For example :
int x[5] = { 0, 1, 2, 3, 4 }; /* Array x declared with five elements */
int *p = x; /* Pointer declared and initialized to point */
/* to the first element of the array x */
int a, b;
a = *(x + 3); /* Pointer x incremented by twelve bytes */
/* to reference element 3 of x */
b = x[3]; /* b now holds the same value as a */
In the previous example, a receives the value 3 by using the dereferencing operator (*). b receives the same value by using the subscripting operator For more information on the different unary operators.
Note that the assignment of a was a result of incrementing the pointer to x . This principle, known as scaling, applies to all types of pointer arithmetic. In scaling, the compiler considers the size of an array element when calculating memory addresses of array members. For example, each member of the array x is 4 bytes long, and adding three to the initial pointer value automatically converts that addition to 3 * (the size of the array member, which in this case is 4). Therefore, the intuitive meaning of z = *(y + 3); is preserved.
When passing arrays as function arguments, only a pointer to the first element of the array is passed to the called function. The conversion from array type to pointer type is implicit. Once the array name is converted to a pointer to the first element of the array, you can increment, decrement, or dereference the pointer, just like any other pointer, to manipulate data in the array. For example :
int func(int *x, int *y) /* The arrays are converted to pointers */
{
*y = *(x + 4); /* Various elements of the arrays are
accessed */
}
Remember that a pointer is large enough to hold only an address; a pointer into an array holds the address of an element of that array. The array itself is large enough to hold all members of the array. When applied to arrays, the size of operator returns the size of the entire array, not just the size of the first element in the array.
What are the steps to initialize an Array
Initializing Arrays : Arrays are initialized with a brace-enclosed list of constant expressions. A list of initializers for an incomplete array declaration completes the array’s type and completely defines the array size.
Therefore, when initializing an array of unknown size, the number of initializers in the initializer list determines the size of the array. For example, the following declaration initializes an array of three elements :
int x[ ] = { 1, 2, 3 };
If the array being initialized has a storage class of static , the initializers must be constant expressions.
Initializers for an array of a given size are assigned to array members on a oneto- one basis. If there are too few initializers for all members, the remaining members are initialized to 0. Listing too many initializers for a given size array is an error. For example :
int x[5] = { 0, 1, 2, 3, 4, 5 }; /* error */
String literals are often assigned to a char or wchar_t array. In this case, each character of the string represents one member of a one-dimensional array, and the array is terminated with the null character. When an array is initialized by a pointer to a string literal, the string literal cannot be modified through the pointer. When initializing an array with a string literal, use quotation marks around the initializing string. For example :
char string[26] = { “This is a string literal.” };
/* The braces above are optional here */
The terminating null character is appended to the end of the string if the size permits, as it does in this case. Another form for initializing an array with characters is the following :
char string[12] = {‘T’, ‘h’, ‘i’, ‘s’, ‘ ‘, ‘w’, ‘a’, ‘y’ };
The preceding example creates a one-dimensional array containing the string value “This way “. The characters in this array can be freely modified. Remaining uninitialized array members will be automatically initialized to zero.
If the size of the array used for a string literal is not explicitly stated, its size is determined by the number of characters in the string (including the terminating null character). If the size of the array is explicitly stated, initializing the array with a string literal longer than the array is an error.
Note : There is one special case where the null character is not automatically appended to the array. This case is when the array size is explicitly specified and the number of initializers completely fills the array size. For example :
char c[4] = “abcd”;
Here, the array c holds only the four specified characters, a , b , c , and d . No null character terminates the array.
Using the following rules, you can omit braces when initializing the members of a multidimensional arrays:
- When initializing arrays, you can omit the outermost pair of braces.
- If the initializer list includes all of the initializers for the object being initialized, you can omit the inner braces.
Consider the following example :
float x[4][2] = {
{ 1, 2 }
{ 3, 4 }
{ 5, 6 }
};
In this example, 1 and 2 initialize the first row of the array x , and the following two lines initialize the second and third rows, respectively. The initialization ends before the fourth row is initialized, so the members of the fourth row default to 0. Here is the result :
x[0][0] = 1;
x[0][1] = 2;
x[1][0] = 3;
x[1][1] = 4;
x[2][0] = 5;
x[2][1] = 6;
x[3][0] = 0;
x[3][1] = 0;
The following declaration achieves the same result :
float x[4][2] = { 1, 2, 3, 4, 5, 6 };
Here, the compiler fills the array row by row with the available initial values. The compiler places 1 and 2 in the first row (x[0] ), 3 and 4 in the second row (x[1] ), and 5 and 6 in the third row (x[2] ). The remaining members of the array are initialized to zero.
Difference Between Strings and Character Arrays
A major difference is: string will have static storage duration, whereas as a character array will not, unless it is explicitly specified by using the static keyword. Actually, a string is a character array with following properties :
The multi-byte character sequence, to which we generally call string, is used to initialize an array of static storage duration. The size of this array is just sufficient to contain these characters plus the terminating NUL character.
It not specified what happens if this array, i.e., string, is modified. So the value of a string is the sequence of the values of the contained characters, in order.
What is the difference between a String and an Array
An array is an array of anything. A string is a specific kind of an array with a well-known convention to determine its length.
[Read more…] about What is the difference between a String and an Array
What is Pointers in C
A pointer is a very powerful and sophisticated feature provided in the C language. A variable defined in a program the compiler allocates a space in the memory to store its value. The number of bytes allocated to the variable depends on its type. For instance, a character is allocated 1 byte, an int is, in general, allocated 4 bytes, and a float is also allocated 4 bytes on a typical 32-bit system. The memory in RAM is grouped into bytes; each byte has 8 bits of memory. Bytes are sequentially numbered. [Read more…] about What is Pointers in C
What is Functions ? Type of Function
It would not be wrong to say that C language is a function-based language. The C Standard Library contains a large number of predefined functions which may be called in programs for carrying out various processes. Related functions are grouped together under various header files. [Read more…] about What is Functions ? Type of Function
What is the difference between goto and longjmp() and setjmp()
A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a non local, or far, jump of program execution. Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program. [Read more…] about What is the difference between goto and longjmp() and setjmp()
How does the exit () and return () differ
exit () is used to exit the program as a whole. In other words it returns control to the operating system.
After exit () all memory and temporary storage areas are all flushed out and control goes out of program. In contrast the return statement is used to return from a function and return control to the calling function.
Also in a program there can be only one exit () statement but a function can have number of return statements. In other words there is no restriction on the number of return statements that can be present in a function.
exit () statement is placed as the last statement in a program since after this program is totally exited. In contrast return statement can take its presence anywhere in the function. It need not present as the last statement of the function.
It is important to note that whenever a control is passed to a function and when it returns back from the function some value gets returned. Only if one uses a return statement the correct value would get returned from the called function to the calling function.
For instance consider the program
main ()
{
int a;
int b= 5;
a = f1(b);
printf(“a=%d”,a);
}
f1(a1)
int a1;
{
int a2;
a2 = 5 * a1;
printf(“a2=%d”,a2);
return(a2);
}
The value of a2 is calculated in function f1 ( ) is returned to the calling function using return () statement and hence output of program is
a2=10
a=10
What are the Format Specifiers used with printf
There are several format Specifiers available in printf. The format specifier used varies depending on the data type used for printing. The given below are some of the format Specifiers used with printf in C program.
For integer data type the format specifier used with printf is %d or %i
For float data type the format specifier used with printf is %f
For double data type the format specifier used with printf is %lf
For char data type the format specifier used with printf is %c
For string data type the format specifier used with printf is %s
Apart from this the other format Specifiers used with printf are
For displaying a number in scientific notation %e is used with printf.
To get the output in next line the new line character n is used with printf.
To get a % sign in output the used symbol along with printf is %%.
Thus format Specifiers are used based on data type and are used to get the output in desired format
Illustrates the application of printf () with different data types.
#include <stdio.h>
void main()
{
int m = 10, n = 5;
float f = 45.8;
double F = 45.8;
double D = 678.98765;
char ch = 'A';
clrscr();
printf("%d\n", m); //Displays the value of m on monitor.
printf("%d, %d\n",m,n); /*Displays values separated by a comma*/
printf("%lf\n",D); //Displays value of D.
printf("%d\t%d\n",m,n); /*Displays values separated by spaces.*/
printf("%d,\t%f,\t%c\n",m, F, ch);
/*Displays values of m,F,ch separated by a comma and few spaces.*/
printf("m = %d\nf = %f\tch = %c\n",m, f, ch);
}
The comments given along the code in the program are meant to help the readers in understanding the output. The output displayed depends on the default settings of the computer. No field width or precision is specified by the user in the above program; however, these have been discussed below. Notice that for outputs of different types of data, different code letters (also called conversion characters) are required after the symbol% in the formatting string. For integers, the conversion character is d (i.e., the code is %d); for floating point numbers, the code is %f; for double numbers, the code is %lf; and for character values, the code is %c. If a real number is declared as float, it may get truncated resulting in an approximate value. (This can be observed in the value 45.8 which is stored after being declared as a float and then as a double. Compare the output in both cases.)
pass by value and pass by reference in functions
Pass by Value: In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. In pass by value, the changes made to formal arguments in the called function have no effect on the values of actual arguments in the calling function. [Read more…] about pass by value and pass by reference in functions
Differences Between Formal Arguments and Actual Arguments of a Function
Argument: An argument is an expression which is passed to a function by its caller (or macro by its invoker) in order for the function(or macro) to perform its task. It is an expression in the comma-separated list bound by the parentheses in a function call expression. [Read more…] about Differences Between Formal Arguments and Actual Arguments of a Function
Command Line Arguments in C
In C, we can supply arguments to ‘main’ function. Every C program has at least one function main(). The programs that we have discussed so far don’t pass any arguments to the main(). A question that immediately comes to one mind is that, can we pass any argument(s) to main()?
Yes, it is possible to pass arguments to main() on many systems like DOS and UNIX from the operating system’s prompt. These arguments passed to the main () by the user at the command prompt are known as command-line arguments. Command-line arguments are parameters to main when the program starts. These arguments are supplied at the time of invoking the program. [Read more…] about Command Line Arguments in C
What is the purpose of main() function
In C, program execution starts from the main() function. Every C program must contain a main() function. The main function may contain any number of statements. These statements are executed sequentially in the order which they are written. [Read more…] about What is the purpose of main() function
How is the main() function declared
The main () is a special function that marks the beginning of the program. The type int before main signifies that function main () returns an integer value to the system on its completion.
In C as well as in C++, the parentheses () after an identifier or a name signify that the identifier or the name on the left of the brackets is a function. Similar to the declaration of variables, the functions are also declared with different types. However, with main () only two types are used: int main () and void main (). The int type functions always return a whole number and the last statement of the function is return value; In case of int main (), the last statement is return 0;. The successful execution of the program function int main () will return 0 to the system. In case of void main (), the return statement is not required. However, compilers for C also allow the use of only main () and without a return statement. In C++ language, however, main () would be taken as int main () by default and the return statement would be required. The body of the program starts after main ().A program may consist of many statements and expressions that are placed between a pair of curly brackets { } after main () as illustrated below.
int main () {\* statements*/}
A function may or may not have arguments. Therefore, main() is also written either simply as above or with two arguments as given below.
int main (int argc, char* argv [])
{/* statements */}
Here, we shall take the first declaration, that is, int main (){}.Remember that every program in C must have one and only one main () function. A program may define or call any number of other functions but can have only one main function. The body of the function main (), as discussed above, starts with the left brace({) after the main ()and ends with the last right or closing brace(}) at the end. Between these two braces a program may contain several pairs of braces { }, each pair may contain a block of statements.
The function printf (), is a function of C Standard Library and is used for displaying the output on the monitor. In the present case, it displays the statement enclosed in double quotes on the monitor. You must have noted that the output of the program does not contain the character “\n”, which is the new line character (or escape sequence). Any statement written on the right hand side of “\n” would be displayed in next line. Similarly, “\t” is another escape sequence that shifts the curser a few spaces ahead in the same line.
What is the Return Value from Printf() Function
Printf function always returns the number of characters printed by the printf function. Let us see this in brief with an example:
main()
{
int a=10;
printf(“%d,printf(“%d %d %d,a,a,a));
}
In this above program the inner printf is first called which prints three times the value of a, with space between each value namely 10 10 10. So 5 characters namely 3 value of a namely 10 and 2 spaces which totals to 5 characters gets printed.
So as explained before the inner printf after printing the values returns the number of characters printed namely 5 which is printed by the outer printf .
The output of the above program is
10 10 10 5
So it is always that function returns a value and so is printf which returns the number of characters successfully printed.
What is the default return value of a function
The default returns value from a function in int. In other words generally unless explicitly specified the default return value by compiler would be integer value from function. So when a programmer wants other than integer values to be returned from function then it is essential that the programmer takes some steps in doing this namely: [Read more…] about What is the default return value of a function
Explain control statements those are used in C programming language
In some situations we may have to change the order of execution of statements based on certain conditions , or repeat a group of statements until certain specified conditions are met. For these situation C provides decision making statements also know as control statements. C has following control statements: [Read more…] about Explain control statements those are used in C programming language
What is the difference between ‘for’ and ‘while’ loops
For loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use ‘for’ loop. [Read more…] about What is the difference between ‘for’ and ‘while’ loops
Define iteration Statements
C has looping , in which a sequence of statements are executed until some conditions for termination of the loop are satisfied. [Read more…] about Define iteration Statements