>>Communication Skill
>>Logical Reasoning
>>Personality
>>Content
>>Leadership Skill
>>Team Building
>>Body Language
>eye contact
>Hand Movement
>>Articulation
Type of Group Discussion :--
1-Sturcture
2-Unstructured
3-Special
STRUCTURE= 1>not ON conclusion
2> unlimited Talk
3>NO for or against
Unstructured=
1>Leadership quality
2>conclusion
Special=
1>case study
to make 1-5 point INSTANTLY ..........
L-legal
{
P-Political
E-Economic
S-Social
T-Technical
}
(LPEST)
If you can dream IT, You can become it, If you can think IT, You can do IT,If you can believe it ,you can achieve IT.
like
Monday, December 26, 2011
Wednesday, December 21, 2011
TOP Question asked in C INTERVIEW
1. Write a program to find factorial of the given number.
2. Write a program to check whether the given number is even or odd.
3. Write a program to swap two numbers using a temporary variable.
4. Write a program to swap two numbers without using a temporary variable.
5. Write a program to swap two numbers using bitwise operators.
6. Write a program to find the greatest of three numbers.
7. Write a program to find the greatest among ten numbers.
8. Write a program to check whether the given number is a prime.
9. Write a program to check whether the given number is a palindromic number.
10.Write a program to check whether the given string is a palindrome.
11.Write a program to generate the Fibonacci series.
12.Write a program to print "Hello World" without using semicolon anywhere in the code.
13.Write a program to print a semicolon without using a semicolon anywhere in the code.
14.Write a program to compare two strings without using strcmp() function.
15.Write a program to concatenate two strings without using strcat() function.
16.Write a program to delete a specified line from a text file.
17.Write a program to replace a specified line in a text file.
18.Write a program to find the number of lines in a text file.
19.Write a C program which asks the user for a number between 1 to 9 and shows the number. If the user
inputs a number out of the specified range, the program should show an error and prompt the user for a
valid input.
20.Write a program to display the multiplication table of a given number.
ANSWERS
1. Write a program to find factorial of the given number.
Recursion: A function is called 'recursive' if a statement within the body of a function calls the same function. It
is also called 'circular definition'. Recursion is thus a process of defining something in terms of itself.
Program: To calculate the factorial value using recursion.
#include
int fact(int n);
int main() {
int x, i;
printf("Enter a value for x: \n");
scanf("%d", &x);
i = fact(x);
printf("\nFactorial of %d is %d", x, i);
return 0;
} int fact(int n) {
/* n=0 indicates a terminating condition */
if (n <= 0) { return (1); } else { /* function calling itself */ return (n * fact(n - 1)); /*n*fact(n-1) is a recursive expression */ } } Output: Enter a value for x: 4 Factorial of 4 is 24 Explanation: fact(n) = n * fact(n-1) If n=4 fact(4) = 4 * fact(3) there is a call to fact(3) fact(3) = 3 * fact(2) fact(2) = 2 * fact(1) fact(1) = 1 * fact(0) fact(0) = 1 fact(1) = 1 * 1 = 1 fact(2) = 2 * 1 = 2 fact(3) = 3 * 2 = 6 Thus fact(4) = 4 * 6 = 24 Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters into an infinite loop. 2. Write a program to check whether the given number is even or odd. Program: #include
int main() {
int a;
printf("Enter a: \n");
scanf("%d", &a);
/* logic */
if (a % 2 == 0) {
printf("The given number is EVEN\n");
}
else {
printf("The given number is ODD\n");
}
return 0;
}
Output:
Enter a: 2
The given number is EVEN
Explanation with examples:
Example 1: If entered number is an even number
Let value of 'a' entered is 4
if(a%2==0) then a is an even number, else odd.
i.e. if(4%2==0) then 4 is an even number, else odd.
To check whether 4 is even or odd, we need to calculate (4%2).
/* % (modulus) implies remainder value. */
/* Therefore if the remainder obtained when 4 is divided by 2 is 0, then 4 is even. */
4%2==0 is true
Thus 4 is an even number.
Example 2: If entered number is an odd number.
Let value of 'a' entered is 7
if(a%2==0) then a is an even number, else odd.
i.e. if(7%2==0) then 4 is an even number, else odd.
To check whether 7 is even or odd, we need to calculate (7%2).
7%2==0 is false /* 7%2==1 condition fails and else part is executed */
Thus 7 is an odd number.
3. Write a program to swap two numbers using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: temp=x;
step2: x=y;
step3: y=temp;
Example:
if x=5 and y=8, consider a temporary variable temp.
step1: temp=x=5;
step2: x=y=8;
step3: y=temp=5;
Thus the values of the variables x and y are interchanged.
Program:
#include
int main() {
int a, b, temp;
printf("Enter the value of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d \n", a, b);
/*Swapping logic */
temp = a;
a = b;
b = temp;
printf("After swapping a=%d, b=%d", a, b);
return 0;
}
Output:
Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2
4. Write a program to swap two numbers without using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: x=x+y;
step2: y=x-y;
step3: x=x-y;
Example:
if x=7 and y=4
step1: x=7+4=11;
step2: y=11-4=7;
step3: x=11-7=4;
Thus the values of the variables x and y are interchanged.
Program:
#include
int main() {
int a, b;
printf("Enter values of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d\n", a,b);
/*Swapping logic */
a = a + b;
b = a - b;
a = a - b;
printf("After swapping a=%d b=%d\n", a, b);
return 0;
}
Output:
Enter values of a and b: 2 3
Before swapping a=2, b=3
The values after swapping are a=3 b=2
5. Write a program to swap two numbers using bitwise operators.
Program:
#include
int main() {
int i = 65;
int k = 120;
printf("\n value of i=%d k=%d before swapping", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n value of i=%d k=%d after swapping", i, k);
return 0;
}
Explanation:
i = 65; binary equivalent of 65 is 0100 0001
k = 120; binary equivalent of 120 is 0111 1000
i = i^k;
i...0100 0001
k...0111 1000
---------
val of i = 0011 1001
---------
k = i^k
i...0011 1001
k...0111 1000
---------
val of k = 0100 0001 binary equivalent of this is 65
---------(that is the initial value of i)
i = i^k
i...0011 1001
k...0100 0001
---------
val of i = 0111 1000 binary equivalent of this is 120
--------- (that is the initial value of k)
6. Write a program to find the greatest of three numbers.
Program:
#include
int main(){
int a, b, c;
printf("Enter a,b,c: \n");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c) {
printf("a is Greater than b and c");
}
else if (b > a && b > c) {
printf("b is Greater than a and c");
}
else if (c > a && c > b) {
printf("c is Greater than a and b");
}
else {
printf("all are equal or any two values are equal");
}
return 0;
}
Output:
Enter a,b,c: 3 5 8
c is Greater than a and b
Explanation with examples:
Consider three numbers a=5,b=4,c=8
if(a>b && a>c) then a is greater than b and c
now check this condition for the three numbers 5,4,8 i.e.
if(5>4 && 5>8) /* 5>4 is true but 5>8 fails */
so the control shifts to else if condition
else if(b>a && b>c) then b is greater than a and c
now checking this condition for 5,4,8 i.e.
else if(4>5 && 4>8) /* both the conditions fail */
now the control shifts to the next else if condition
else if(c>a && c>b) then c is greater than a and b
now checking this condition for 5,4,8 i.e.
else if(8>5 && 8>4) /* both conditions are satisfied */
Thus c is greater than a and b.
7. Write a program to find the greatest among ten numbers.
Program:
#include
int main() {
int a[10];
int i;
int greatest;
printf("Enter ten values:");
//Store 10 numbers in an array
for (i = 0; i < 10; i++) { scanf("%d", &a[i]); } //Assume that a[0] is greatest greatest = a[0]; for (i = 0; i < 10; i++) { if (a[i] > greatest) {
greatest = a[i];
}
}
printf("\nGreatest of ten numbers is %d", greatest);
return 0;
}
Output:
Enter ten values: 2 53 65 3 88 8 14 5 77 64 Greatest of ten numbers is 88
Explanation with example:
Entered values are 2, 53, 65, 3, 88, 8, 14, 5, 77, 64
They are stored in an array of size 10. let a[] be an array holding these values.
/* how the greatest among ten numbers is found */
Let us consider a variable 'greatest'. At the beginning of the loop, variable 'greatest' is assinged with the value of
first element in the array greatest=a[0]. Here variable 'greatest' is assigned 2 as a[0]=2.
Below loop is executed until end of the array 'a[]';.
for(i=0; i<10; i++) { if(a[i]>greatest)
{
greatest= a[i];
}
}
For each value of 'i', value of a[i] is compared with value of variable 'greatest'. If any value greater than the value
of 'greatest' is encountered, it would be replaced by a[i]. After completion of 'for' loop, the value of variable
'greatest' holds the greatest number in the array. In this case 88 is the greatest of all the numbers.
8. Write a program to check whether the given number is a prime.
A prime number is a natural number that has only one and itself as factors. Examples: 2, 3, 13 are prime
numbers.
Program:
#include
main() {
int n, i, c = 0;
printf("Enter any number n: \n");
scanf("%d", &n);
/*logic*/
for (i = 1; i <= n; i++) { if (n % i == 0) { c++; } } if (c == 2) { printf("n is a Prime number"); } else { printf("n is not a Prime number"); } return 0; } Output: Enter any number n: 7 n is Prime Explanation with examples: consider a number n=5 for(i=0;i<=n;i++) /* for loop is executed until the n value equals i */ i.e. for(i=0;i<=5;i++) /* here the for loop is executed until i is equal to n */ 1st iteration: i=1;i<=5;i++ here i is incremented i.e. i value for next iteration is 2 now if(n%i==0) then c is incremented i.e.if(5%1==0)then c is incremented, here 5%1=0 thus c is incremented. now c=1; 2nd iteration: i=2;i<=5;i++ here i is incremented i.e. i value for next iteration is 3 now if(n%i==0) then c is incremented i.e.if(5%2==0) then c is incremented, but 5%2!=0 and so c is not incremented, c remains 1 c=1; 3rd iteration: i=3;i<=5;i++ here i is incremented i.e. i value for next iteration is 4 now if(n%i==0) then c is incremented i.e.if(5%3==0) then c ic incremented, but 5%3!=0 and so c is not incremented, c remains 1 c=1; 4th iteration: i=4;i<=5;i++ here i is incremented i.e. i value for next iteration is 5 now if(n%i==0) then c is incremented i.e. if(5%4==0) then c is incremented, but 5%4!=0 and so c is not incremented, c remains 1 c=1; 5th iteration: i=5;i<=5;i++ here i is incremented i.e. i value for next iteration is 6 now if(n%i==0) then c is incremented i.e. if(5%5==0) then c is incremented, 5%5=0 and so c is incremented. i.e. c=2 6th iteration: i=6;i<=5;i++ here i value is 6 and 6<=5 is false thus the condition fails and control leaves the for loop. now if(c==2) then n is a prime number we have c=2 from the 5th iteration and thus n=5 is a Prime number. 9. Write a program to check whether the given number is a palindromic number. If a number, which when read in both forward and backward way is same, then such a number is called a palindrome number. Program: #include
int main() {
int n, n1, rev = 0, rem;
printf("Enter any number: \n");
scanf("%d", &n);
n1 = n;
/* logic */
while (n > 0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev){
printf("Given number is a palindromic number");
}
else{
printf("Given number is not a palindromic number");
}
return 0;
}
Output:
Enter any number: 121
Given number is a palindrome
Explanation with an example:
Consider a number n=121, reverse=0, remainder;
number=121
now the while loop is executed /* the condition (n>0) is satisfied */
/* calculate remainder */
remainder of 121 divided by 10=(121%10)=1;
now reverse=(reverse*10)+remainder
=(0*10)+1 /* we have initialized reverse=0 */
=1
number=number/10
=121/10
=12
now the number is 12, greater than 0. The above process is repeated for number=12.
remainder=12%10=2;
reverse=(1*10)+2=12;
number=12/10=1;
now the number is 1, greater than 0. The above process is repeated for number=1.
remainder=1%10=1;
reverse=(12*10)+1=121;
number=1/10 /* the condition n>0 is not satisfied,control leaves the while loop */
Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a
palindrome number.
10.Write a program to check whether the given string is a palindrome.
Palindrome is a string, which when read in both forward and backward way is same.
Example: radar, madam, pop, lol, rubber, etc.,
Program:
#include
#include
int main() {
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){ if(string1[i] != string1[length-i-1]){ flag = 1; break; } } if (flag) { printf("%s is not a palindrome\n", string1); } else { printf("%s is a palindrome\n", string1); } return 0; } Output: Enter a string: radar "radar" is a palindrome Explanation with example: To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself. Consider a palindrome string: "radar", --------------------------- index: 0 1 2 3 4 value: r a d a r --------------------------- To compare it with the reverse of itself, the following logic is used: 0th character in the char array, string1 is same as 4th character in the same string. 1st character is same as 3rd character. 2nd character is same as 2nd character. . . . . ith character is same as 'length-i-1'th character. If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome. By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome. 11.Write a program to generate the Fibonacci series. Fibonacci series: Any number in the series is obtained by adding the previous two numbers of the series. Let f(n) be n'th term. f(0)=0; f(1)=1; f(n)=f(n-1)+f(n-2); (for n>=2)
Series is as follows
011
(1+0)
2 (1+1)
3 (1+2)
5 (2+3)
8 (3+5)
13 (5+8)
21 (8+13)
34 (13+21)
...and so on
Program: to generate Fibonacci Series(10 terms)
#include
int main() {
//array fib stores numbers of fibonacci series
int i, fib[25];
//initialized first element to 0
fib[0] = 0;
//initialized second element to 1
fib[1] = 1;
//loop to generate ten elements
for (i = 2; i < 10; i++) { //i'th element of series is equal to the sum of i-1'th element and i-2'th element. fib[i] = fib[i - 1] + fib[i - 2]; } printf("The fibonacci series is as follows \n"); //print all numbers in the series for (i = 0; i < 10; i++) { printf("%d \n", fib[i]); } return 0; } Output: The fibonacci series is as follows 01123581 3 21 34 Explanation: The first two elements are initialized to 0, 1 respectively. Other elements in the series are generated by looping and adding previous two numbes. These numbers are stored in an array and ten elements of the series are printed as output. 12.Write a program to print "Hello World" without using semicolon anywhere in the code. Generally when we use printf("") statement, we have to use a semicolon at the end. If printf is used inside an if Condition, semicolon can be avoided. Program: Program to print something without using semicolon (;) #include
int main() {
//printf returns the length of string being printed
if (printf("Hello World\n")) //prints Hello World and returns 11
{
//do nothing
}
return 0;
}
Output:
Hello World
Explanation:
The if statement checks for condition whether the return value of printf("Hello World") is greater than 0. printf
function returns the length of the string printed. Hence the statement if (printf("Hello World")) prints the string
"Hello World".
13.Write a program to print a semicolon without using a semicolon anywhere in the code.
Generally when use printf("") statement we have to use semicolon at the end.
If we want to print a semicolon, we use the statement: printf(";");
In above statement, we are using two semicolons. The task of printing a semicolon without using semicolon anywhere in the code can be accomplished by using the ascii value of ' ; ' which is equal to 59.
Program: Program to print a semicolon without using semicolon in the code.
#include
int main(void) {
//prints the character with ascii value 59, i.e., semicolon
if (printf("%c\n", 59)) {
//prints semicolon
}
return 0;
}
Output:
;
Explanation:
If statement checks whether return value of printf function is greater than zero or not. The return value of function
call printf("%c",59) is 1. As printf returns the length of the string printed. printf("%c",59) prints ascii value that
corresponds to 59, that is semicolon(;).
14.Write a program to compare two strings without using strcmp() function.
strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.
Syntax:
int strcmp (const char *s1, const char *s2);
Program: to compare two strings.
#include
#include
int cmpstr(char s1[10], char s2[10]);
int main() {
char arr1[10] = "Nodalo";
char arr2[10] = "nodalo";
printf(" %d", cmpstr(arr1, arr2));
//cmpstr() is equivalent of strcmp()
return 0;
}/
/s1, s2 are strings to be compared
int cmpstr(char s1[10], char s2[10]) {
//strlen function returns the length of argument string passed
int i = strlen(s1);
int k = strlen(s2);
int bigger;
if (i < k) { bigger = k; } else if (i > k) {
bigger = i;
}
else {
bigger = i;
}
//loops 'bigger' times
for (i = 0; i < bigger; i++) { //if ascii values of characters s1[i], s2[i] are equal do nothing if (s1[i] == s2[i]) { } //else return the ascii difference else { return (s1[i] - s2[i]); } } //return 0 when both strings are same //This statement is executed only when both strings are equal return (0); } Output: -32 Explanation: cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr(). Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ascii difference of the differing characters and exit. 15.Write a program to concatenate two strings without using strcat() function. strcat(string1,string2) is a C standard function declared in the header file string.h The strcat() function concatenates string2, string1 and returns string1. Program: Program to concatenate two strings #include
#include
char *strct(char *c1, char *c2);
char *strct(char *c1, char *c2) {
//strlen function returns length of argument string
int i = strlen(c1);
int k = 0;
//loops until null is encountered and appends string c2 to c1
while (c2[k] != '\0') {
c1[i + k] = c2[k];
k++;
}
return c1;
}
int main() {
char string1[15] = "first";
char string2[15] = "second";
char *finalstr;
printf("Before concatenation:"
" \n string1 = %s \n string2 = %s", string1, string2);
//addresses of string1, string2 are passed to strct()
finalstr = strcat(string1, string2);
printf("\nAfter concatenation:");
//prints the contents of string whose address is in finalstr
printf("\n finalstr = %s", finalstr);
//prints the contents of string1
printf("\n string1 = %s", string1);
//prints the contents of string2
printf("\n string2 = %s", string2);
return 0;
}
Output:
Before concatenation:
string1 = first
string2 = second
After concatenation:
finalstr = firstsecond
string1 = firstsecond
string2 = second
Explanation:
string2 is appended at the end of string1 and contents of string2 are unchanged.
In strct() function, using a for loop, all the characters of string 'c2' are copied at the end of c1. return (c1) is
equivalent to return &c1[0] and it returns the base address of 'c1'. 'finalstr' stores that address returned by the
function strct().
16.Write a program to delete a specified line from a text file.
In this program, user is asked for a filename he needs to change. User is also asked for the line number that is
to be deleted. The filename is stored in 'filename'. The file is opened and all the data is transferred to another file
except that one line the user specifies to delete.
Program: Program to delete a specific line.
#include
int main() {
FILE *fp1, *fp2;
//consider 40 character string to store filename
char filename[40];
char c;
int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
//open file in read mode
fp1 = fopen(filename, "r");
c = getc(fp1);
//until the last character of file is obtained
while (c != EOF)
{
printf("%c", c);
//print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
//accept number from user.
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF) {
c = getc(fp1);
if (c == '\n')
temp++;
//except the line to be deleted
if (temp != del_line)
{
//copy all lines in file copy.c
putc(c, fp2);
}
}
//close both the files.
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF) {
printf("%c", c);
c = getc(fp1);
}
fclose(fp1);
return 0;
}
Output:
Enter file name:abc.txt
hi.
Hello
how are you?
I am fine
hope the same
Enter line number of the line to be deleted:4
The contents of file after being modified are as follows:
hi.
hello
how are you?
hope the same
Explanation:
In this program, user is asked for a filename that needs to be modified. Entered file name is stored in a char
array 'filename'. This file is opened in read mode using file pointer 'fp1'. Character 'c' is used to read characters
from the file and print them to the output. User is asked for the line number in the file to be deleted. The file
pointer is rewinded back and all the lines of the file except for the line to be deleted are copied into another file
"copy.c". Now "copy.c" is renamed to the original filename. The original file is opened in read mode and the
modified contents of the file are displayed on the screen.
17.Write a program to replace a specified line in a text file.
Program: Program to replace a specified line in a text file.
#include
int main(void) {
FILE *fp1, *fp2;
//'filename'is a 40 character string to store filename
char filename[40];
char c;
int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
fp1 = fopen(filename, "r");
//open file in read mode
c = getc(fp1);
//print the contents of file .
while (c != EOF) {
printf("%c", c);
c = getc(fp1);
}
//ask user for line number to be deleted.
printf(" \n Enter line number to be deleted and replaced");
scanf("%d", &del_line);
//take fp1 to start point.
rewind(fp1);
//open copy.c in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF) {
if (c == '\n') {
temp++;
}
//till the line to be deleted comes,copy the content from one file to other
if (temp != del_line){
putc(c, fp2);
}
else //when the line to be deleted comes
{
while ((c = getc(fp1)) != '\n') {
}
//read and skip the line ask for new text
printf("Enter new text");
//flush the input stream
fflush(stdin);
putc('\n', fp2);
//put '\n' in new file
while ((c = getchar()) != '\n')
putc(c, fp2);
//take the data from user and place it in new file
fputs("\n", fp2);
temp++;
}
//continue this till EOF is encountered
c = getc(fp1);
}
//close both files
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename new file with old name opens the file in read mode
rename("copy.c", filename);
fp1 = fopen(filename, "r");
//reads the character from file
c = getc(fp1);
//until last character of file is encountered
while (c != EOF){
printf("%c", c);
//all characters are printed
c = getc(fp1);
}
//close the file pointer
fclose(fp1);
return 0;
}
Output:
Enter file name:abc.txt
hi.
hello
how are you?
hope the same
Enter line number of the line to be deleted and replaced:4
Enter new text: sayonara see you soon
hi.
hello
how are you?
sayonara see you soon
Explanation:
In this program, the user is asked to type the name of the file. The File by name entered by user is opened in
read mode. The line number of the line to be replaced is asked as input. Next the data to be replaced is asked. A
new file is opened in write mode named "copy.c". Now the contents of original file are transferred into new file
and the line to be modified is deleted. New data is stored in its place and remaining lines of the original file are
also transferred. The copied file with modified contents is replaced with the original file's name. Both the file
pointers are closed and the original file is again opened in read mode and the contents of the original file is
printed as output.
18.Write a program to find the number of lines in a text file.
Number of lines in a file can be determined by counting the number of new line characters present.
Program: Program to count number of lines in a file.
#include
int main()
/* Ask for a filename and count number of lines in the file*/
{
//a pointer to a FILE structure
FILE *fp;
int no_lines = 0;
//consider 40 character string to store filename
char filename[40], sample_chr;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in a string named 'filename'
scanf("%s", filename);
//open file in read mode
fp = fopen(filename, "r");
//get character from file and store in sample_chr
sample_chr = getc(fp);
while (sample_chr != EOF) {
//Count whenever sample_chr is '\n'(new line) is encountered
if (sample_chr == '\n')
{
//increment variable 'no_lines' by 1
no_lines=no_lines+1;
}
//take next character from file.
sample_chr = getc(fp);
}
fclose(fp); //close file.
printf("There are %d lines in %s \n", no_lines, filename);
return 0;
}
Output:
Enter file name:abc.txt
There are 4 lines in abc.txt
Explanation:
In this program, name of the file to be read is taken as input. A file by the given name is opened in read-mode
using a File pointer 'fp'. Characters from the file are read into a char variable 'sample_chr' with the help of getc
function. If a new line character('\n') is encountered, the integer variable 'no_lines' is incremented. If the
character read into 'sample_char' is not a new line character, next character is read from the file. This process is
continued until the last character of the file(EOF) is encountered. The file pointer is then closed and the total
number of lines is shown as output.
19.Write a C program which asks the user for a number between 1 to 9 and shows the number. If the
user inputs a number out of the specified range, the program should show an error and prompt
the user for a valid input.
Program: Program for accepting a number in a given range.
#include
int getnumber();
int main() {
int input = 0;
//call a function to input number from key board
input = getnumber();
//when input is not in the range of 1 to 9,print error message
while (!((input <= 9) && (input >= 1))) {
printf("[ERROR] The number you entered is out of range");
//input another number
input = getnumber();
}
//this function is repeated until a valid input is given by user.
printf("\nThe number you entered is %d", input);
return 0;
}/
/this function returns the number given by user
int getnumber() {
int number;
//asks user for a input in given range
printf("\nEnter a number between 1 to 9 \n");
scanf("%d", &number);
return (number);
}
Output:
Enter a number between 1 to 9
45
[ERROR] The number you entered is out of range
Enter a number between 1 to 9
4
The number you entered is 4
Explanation:
getfunction() function accepts input from user. 'while' loop checks whether the number falls within range or not
and accordingly either prints the number(If the number falls in desired range) or shows error message(number is
out of range).
20.Write a program to display the multiplication table of a given number.
Program: Multiplication table of a given number
#include
int main() {
int num, i = 1;
printf("\n Enter any Number:");
scanf("%d", &num);
printf("Multiplication table of %d: \n", num);
while (i <= 10) {
printf("\n %d x %d = %d", num, i, num * i);
i++;
}
return 0;
}
Output:
Enter any Number:5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Explanation:
We need to multiply the given number (i.e. the number for which we want the multiplication table)
with value of 'i' which increments from 1 to 10.
2. Write a program to check whether the given number is even or odd.
3. Write a program to swap two numbers using a temporary variable.
4. Write a program to swap two numbers without using a temporary variable.
5. Write a program to swap two numbers using bitwise operators.
6. Write a program to find the greatest of three numbers.
7. Write a program to find the greatest among ten numbers.
8. Write a program to check whether the given number is a prime.
9. Write a program to check whether the given number is a palindromic number.
10.Write a program to check whether the given string is a palindrome.
11.Write a program to generate the Fibonacci series.
12.Write a program to print "Hello World" without using semicolon anywhere in the code.
13.Write a program to print a semicolon without using a semicolon anywhere in the code.
14.Write a program to compare two strings without using strcmp() function.
15.Write a program to concatenate two strings without using strcat() function.
16.Write a program to delete a specified line from a text file.
17.Write a program to replace a specified line in a text file.
18.Write a program to find the number of lines in a text file.
19.Write a C program which asks the user for a number between 1 to 9 and shows the number. If the user
inputs a number out of the specified range, the program should show an error and prompt the user for a
valid input.
20.Write a program to display the multiplication table of a given number.
ANSWERS
1. Write a program to find factorial of the given number.
Recursion: A function is called 'recursive' if a statement within the body of a function calls the same function. It
is also called 'circular definition'. Recursion is thus a process of defining something in terms of itself.
Program: To calculate the factorial value using recursion.
#include
int fact(int n);
int main() {
int x, i;
printf("Enter a value for x: \n");
scanf("%d", &x);
i = fact(x);
printf("\nFactorial of %d is %d", x, i);
return 0;
} int fact(int n) {
/* n=0 indicates a terminating condition */
if (n <= 0) { return (1); } else { /* function calling itself */ return (n * fact(n - 1)); /*n*fact(n-1) is a recursive expression */ } } Output: Enter a value for x: 4 Factorial of 4 is 24 Explanation: fact(n) = n * fact(n-1) If n=4 fact(4) = 4 * fact(3) there is a call to fact(3) fact(3) = 3 * fact(2) fact(2) = 2 * fact(1) fact(1) = 1 * fact(0) fact(0) = 1 fact(1) = 1 * 1 = 1 fact(2) = 2 * 1 = 2 fact(3) = 3 * 2 = 6 Thus fact(4) = 4 * 6 = 24 Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters into an infinite loop. 2. Write a program to check whether the given number is even or odd. Program: #include
int main() {
int a;
printf("Enter a: \n");
scanf("%d", &a);
/* logic */
if (a % 2 == 0) {
printf("The given number is EVEN\n");
}
else {
printf("The given number is ODD\n");
}
return 0;
}
Output:
Enter a: 2
The given number is EVEN
Explanation with examples:
Example 1: If entered number is an even number
Let value of 'a' entered is 4
if(a%2==0) then a is an even number, else odd.
i.e. if(4%2==0) then 4 is an even number, else odd.
To check whether 4 is even or odd, we need to calculate (4%2).
/* % (modulus) implies remainder value. */
/* Therefore if the remainder obtained when 4 is divided by 2 is 0, then 4 is even. */
4%2==0 is true
Thus 4 is an even number.
Example 2: If entered number is an odd number.
Let value of 'a' entered is 7
if(a%2==0) then a is an even number, else odd.
i.e. if(7%2==0) then 4 is an even number, else odd.
To check whether 7 is even or odd, we need to calculate (7%2).
7%2==0 is false /* 7%2==1 condition fails and else part is executed */
Thus 7 is an odd number.
3. Write a program to swap two numbers using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: temp=x;
step2: x=y;
step3: y=temp;
Example:
if x=5 and y=8, consider a temporary variable temp.
step1: temp=x=5;
step2: x=y=8;
step3: y=temp=5;
Thus the values of the variables x and y are interchanged.
Program:
#include
int main() {
int a, b, temp;
printf("Enter the value of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d \n", a, b);
/*Swapping logic */
temp = a;
a = b;
b = temp;
printf("After swapping a=%d, b=%d", a, b);
return 0;
}
Output:
Enter the values of a and b: 2 3
Before swapping a=2, b=3
After swapping a=3, b=2
4. Write a program to swap two numbers without using a temporary variable.
Swapping interchanges the values of two given variables.
Logic:
step1: x=x+y;
step2: y=x-y;
step3: x=x-y;
Example:
if x=7 and y=4
step1: x=7+4=11;
step2: y=11-4=7;
step3: x=11-7=4;
Thus the values of the variables x and y are interchanged.
Program:
#include
int main() {
int a, b;
printf("Enter values of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d, b=%d\n", a,b);
/*Swapping logic */
a = a + b;
b = a - b;
a = a - b;
printf("After swapping a=%d b=%d\n", a, b);
return 0;
}
Output:
Enter values of a and b: 2 3
Before swapping a=2, b=3
The values after swapping are a=3 b=2
5. Write a program to swap two numbers using bitwise operators.
Program:
#include
int main() {
int i = 65;
int k = 120;
printf("\n value of i=%d k=%d before swapping", i, k);
i = i ^ k;
k = i ^ k;
i = i ^ k;
printf("\n value of i=%d k=%d after swapping", i, k);
return 0;
}
Explanation:
i = 65; binary equivalent of 65 is 0100 0001
k = 120; binary equivalent of 120 is 0111 1000
i = i^k;
i...0100 0001
k...0111 1000
---------
val of i = 0011 1001
---------
k = i^k
i...0011 1001
k...0111 1000
---------
val of k = 0100 0001 binary equivalent of this is 65
---------(that is the initial value of i)
i = i^k
i...0011 1001
k...0100 0001
---------
val of i = 0111 1000 binary equivalent of this is 120
--------- (that is the initial value of k)
6. Write a program to find the greatest of three numbers.
Program:
#include
int main(){
int a, b, c;
printf("Enter a,b,c: \n");
scanf("%d %d %d", &a, &b, &c);
if (a > b && a > c) {
printf("a is Greater than b and c");
}
else if (b > a && b > c) {
printf("b is Greater than a and c");
}
else if (c > a && c > b) {
printf("c is Greater than a and b");
}
else {
printf("all are equal or any two values are equal");
}
return 0;
}
Output:
Enter a,b,c: 3 5 8
c is Greater than a and b
Explanation with examples:
Consider three numbers a=5,b=4,c=8
if(a>b && a>c) then a is greater than b and c
now check this condition for the three numbers 5,4,8 i.e.
if(5>4 && 5>8) /* 5>4 is true but 5>8 fails */
so the control shifts to else if condition
else if(b>a && b>c) then b is greater than a and c
now checking this condition for 5,4,8 i.e.
else if(4>5 && 4>8) /* both the conditions fail */
now the control shifts to the next else if condition
else if(c>a && c>b) then c is greater than a and b
now checking this condition for 5,4,8 i.e.
else if(8>5 && 8>4) /* both conditions are satisfied */
Thus c is greater than a and b.
7. Write a program to find the greatest among ten numbers.
Program:
#include
int main() {
int a[10];
int i;
int greatest;
printf("Enter ten values:");
//Store 10 numbers in an array
for (i = 0; i < 10; i++) { scanf("%d", &a[i]); } //Assume that a[0] is greatest greatest = a[0]; for (i = 0; i < 10; i++) { if (a[i] > greatest) {
greatest = a[i];
}
}
printf("\nGreatest of ten numbers is %d", greatest);
return 0;
}
Output:
Enter ten values: 2 53 65 3 88 8 14 5 77 64 Greatest of ten numbers is 88
Explanation with example:
Entered values are 2, 53, 65, 3, 88, 8, 14, 5, 77, 64
They are stored in an array of size 10. let a[] be an array holding these values.
/* how the greatest among ten numbers is found */
Let us consider a variable 'greatest'. At the beginning of the loop, variable 'greatest' is assinged with the value of
first element in the array greatest=a[0]. Here variable 'greatest' is assigned 2 as a[0]=2.
Below loop is executed until end of the array 'a[]';.
for(i=0; i<10; i++) { if(a[i]>greatest)
{
greatest= a[i];
}
}
For each value of 'i', value of a[i] is compared with value of variable 'greatest'. If any value greater than the value
of 'greatest' is encountered, it would be replaced by a[i]. After completion of 'for' loop, the value of variable
'greatest' holds the greatest number in the array. In this case 88 is the greatest of all the numbers.
8. Write a program to check whether the given number is a prime.
A prime number is a natural number that has only one and itself as factors. Examples: 2, 3, 13 are prime
numbers.
Program:
#include
main() {
int n, i, c = 0;
printf("Enter any number n: \n");
scanf("%d", &n);
/*logic*/
for (i = 1; i <= n; i++) { if (n % i == 0) { c++; } } if (c == 2) { printf("n is a Prime number"); } else { printf("n is not a Prime number"); } return 0; } Output: Enter any number n: 7 n is Prime Explanation with examples: consider a number n=5 for(i=0;i<=n;i++) /* for loop is executed until the n value equals i */ i.e. for(i=0;i<=5;i++) /* here the for loop is executed until i is equal to n */ 1st iteration: i=1;i<=5;i++ here i is incremented i.e. i value for next iteration is 2 now if(n%i==0) then c is incremented i.e.if(5%1==0)then c is incremented, here 5%1=0 thus c is incremented. now c=1; 2nd iteration: i=2;i<=5;i++ here i is incremented i.e. i value for next iteration is 3 now if(n%i==0) then c is incremented i.e.if(5%2==0) then c is incremented, but 5%2!=0 and so c is not incremented, c remains 1 c=1; 3rd iteration: i=3;i<=5;i++ here i is incremented i.e. i value for next iteration is 4 now if(n%i==0) then c is incremented i.e.if(5%3==0) then c ic incremented, but 5%3!=0 and so c is not incremented, c remains 1 c=1; 4th iteration: i=4;i<=5;i++ here i is incremented i.e. i value for next iteration is 5 now if(n%i==0) then c is incremented i.e. if(5%4==0) then c is incremented, but 5%4!=0 and so c is not incremented, c remains 1 c=1; 5th iteration: i=5;i<=5;i++ here i is incremented i.e. i value for next iteration is 6 now if(n%i==0) then c is incremented i.e. if(5%5==0) then c is incremented, 5%5=0 and so c is incremented. i.e. c=2 6th iteration: i=6;i<=5;i++ here i value is 6 and 6<=5 is false thus the condition fails and control leaves the for loop. now if(c==2) then n is a prime number we have c=2 from the 5th iteration and thus n=5 is a Prime number. 9. Write a program to check whether the given number is a palindromic number. If a number, which when read in both forward and backward way is same, then such a number is called a palindrome number. Program: #include
int main() {
int n, n1, rev = 0, rem;
printf("Enter any number: \n");
scanf("%d", &n);
n1 = n;
/* logic */
while (n > 0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev){
printf("Given number is a palindromic number");
}
else{
printf("Given number is not a palindromic number");
}
return 0;
}
Output:
Enter any number: 121
Given number is a palindrome
Explanation with an example:
Consider a number n=121, reverse=0, remainder;
number=121
now the while loop is executed /* the condition (n>0) is satisfied */
/* calculate remainder */
remainder of 121 divided by 10=(121%10)=1;
now reverse=(reverse*10)+remainder
=(0*10)+1 /* we have initialized reverse=0 */
=1
number=number/10
=121/10
=12
now the number is 12, greater than 0. The above process is repeated for number=12.
remainder=12%10=2;
reverse=(1*10)+2=12;
number=12/10=1;
now the number is 1, greater than 0. The above process is repeated for number=1.
remainder=1%10=1;
reverse=(12*10)+1=121;
number=1/10 /* the condition n>0 is not satisfied,control leaves the while loop */
Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a
palindrome number.
10.Write a program to check whether the given string is a palindrome.
Palindrome is a string, which when read in both forward and backward way is same.
Example: radar, madam, pop, lol, rubber, etc.,
Program:
#include
#include
int main() {
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++){ if(string1[i] != string1[length-i-1]){ flag = 1; break; } } if (flag) { printf("%s is not a palindrome\n", string1); } else { printf("%s is a palindrome\n", string1); } return 0; } Output: Enter a string: radar "radar" is a palindrome Explanation with example: To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself. Consider a palindrome string: "radar", --------------------------- index: 0 1 2 3 4 value: r a d a r --------------------------- To compare it with the reverse of itself, the following logic is used: 0th character in the char array, string1 is same as 4th character in the same string. 1st character is same as 3rd character. 2nd character is same as 2nd character. . . . . ith character is same as 'length-i-1'th character. If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome. By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome. 11.Write a program to generate the Fibonacci series. Fibonacci series: Any number in the series is obtained by adding the previous two numbers of the series. Let f(n) be n'th term. f(0)=0; f(1)=1; f(n)=f(n-1)+f(n-2); (for n>=2)
Series is as follows
011
(1+0)
2 (1+1)
3 (1+2)
5 (2+3)
8 (3+5)
13 (5+8)
21 (8+13)
34 (13+21)
...and so on
Program: to generate Fibonacci Series(10 terms)
#include
int main() {
//array fib stores numbers of fibonacci series
int i, fib[25];
//initialized first element to 0
fib[0] = 0;
//initialized second element to 1
fib[1] = 1;
//loop to generate ten elements
for (i = 2; i < 10; i++) { //i'th element of series is equal to the sum of i-1'th element and i-2'th element. fib[i] = fib[i - 1] + fib[i - 2]; } printf("The fibonacci series is as follows \n"); //print all numbers in the series for (i = 0; i < 10; i++) { printf("%d \n", fib[i]); } return 0; } Output: The fibonacci series is as follows 01123581 3 21 34 Explanation: The first two elements are initialized to 0, 1 respectively. Other elements in the series are generated by looping and adding previous two numbes. These numbers are stored in an array and ten elements of the series are printed as output. 12.Write a program to print "Hello World" without using semicolon anywhere in the code. Generally when we use printf("") statement, we have to use a semicolon at the end. If printf is used inside an if Condition, semicolon can be avoided. Program: Program to print something without using semicolon (;) #include
int main() {
//printf returns the length of string being printed
if (printf("Hello World\n")) //prints Hello World and returns 11
{
//do nothing
}
return 0;
}
Output:
Hello World
Explanation:
The if statement checks for condition whether the return value of printf("Hello World") is greater than 0. printf
function returns the length of the string printed. Hence the statement if (printf("Hello World")) prints the string
"Hello World".
13.Write a program to print a semicolon without using a semicolon anywhere in the code.
Generally when use printf("") statement we have to use semicolon at the end.
If we want to print a semicolon, we use the statement: printf(";");
In above statement, we are using two semicolons. The task of printing a semicolon without using semicolon anywhere in the code can be accomplished by using the ascii value of ' ; ' which is equal to 59.
Program: Program to print a semicolon without using semicolon in the code.
#include
int main(void) {
//prints the character with ascii value 59, i.e., semicolon
if (printf("%c\n", 59)) {
//prints semicolon
}
return 0;
}
Output:
;
Explanation:
If statement checks whether return value of printf function is greater than zero or not. The return value of function
call printf("%c",59) is 1. As printf returns the length of the string printed. printf("%c",59) prints ascii value that
corresponds to 59, that is semicolon(;).
14.Write a program to compare two strings without using strcmp() function.
strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.
Syntax:
int strcmp (const char *s1, const char *s2);
Program: to compare two strings.
#include
#include
int cmpstr(char s1[10], char s2[10]);
int main() {
char arr1[10] = "Nodalo";
char arr2[10] = "nodalo";
printf(" %d", cmpstr(arr1, arr2));
//cmpstr() is equivalent of strcmp()
return 0;
}/
/s1, s2 are strings to be compared
int cmpstr(char s1[10], char s2[10]) {
//strlen function returns the length of argument string passed
int i = strlen(s1);
int k = strlen(s2);
int bigger;
if (i < k) { bigger = k; } else if (i > k) {
bigger = i;
}
else {
bigger = i;
}
//loops 'bigger' times
for (i = 0; i < bigger; i++) { //if ascii values of characters s1[i], s2[i] are equal do nothing if (s1[i] == s2[i]) { } //else return the ascii difference else { return (s1[i] - s2[i]); } } //return 0 when both strings are same //This statement is executed only when both strings are equal return (0); } Output: -32 Explanation: cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr(). Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ascii difference of the differing characters and exit. 15.Write a program to concatenate two strings without using strcat() function. strcat(string1,string2) is a C standard function declared in the header file string.h The strcat() function concatenates string2, string1 and returns string1. Program: Program to concatenate two strings #include
#include
char *strct(char *c1, char *c2);
char *strct(char *c1, char *c2) {
//strlen function returns length of argument string
int i = strlen(c1);
int k = 0;
//loops until null is encountered and appends string c2 to c1
while (c2[k] != '\0') {
c1[i + k] = c2[k];
k++;
}
return c1;
}
int main() {
char string1[15] = "first";
char string2[15] = "second";
char *finalstr;
printf("Before concatenation:"
" \n string1 = %s \n string2 = %s", string1, string2);
//addresses of string1, string2 are passed to strct()
finalstr = strcat(string1, string2);
printf("\nAfter concatenation:");
//prints the contents of string whose address is in finalstr
printf("\n finalstr = %s", finalstr);
//prints the contents of string1
printf("\n string1 = %s", string1);
//prints the contents of string2
printf("\n string2 = %s", string2);
return 0;
}
Output:
Before concatenation:
string1 = first
string2 = second
After concatenation:
finalstr = firstsecond
string1 = firstsecond
string2 = second
Explanation:
string2 is appended at the end of string1 and contents of string2 are unchanged.
In strct() function, using a for loop, all the characters of string 'c2' are copied at the end of c1. return (c1) is
equivalent to return &c1[0] and it returns the base address of 'c1'. 'finalstr' stores that address returned by the
function strct().
16.Write a program to delete a specified line from a text file.
In this program, user is asked for a filename he needs to change. User is also asked for the line number that is
to be deleted. The filename is stored in 'filename'. The file is opened and all the data is transferred to another file
except that one line the user specifies to delete.
Program: Program to delete a specific line.
#include
int main() {
FILE *fp1, *fp2;
//consider 40 character string to store filename
char filename[40];
char c;
int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
//open file in read mode
fp1 = fopen(filename, "r");
c = getc(fp1);
//until the last character of file is obtained
while (c != EOF)
{
printf("%c", c);
//print current character and read next character
c = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
//accept number from user.
scanf("%d", &del_line);
//open new file in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF) {
c = getc(fp1);
if (c == '\n')
temp++;
//except the line to be deleted
if (temp != del_line)
{
//copy all lines in file copy.c
putc(c, fp2);
}
}
//close both the files.
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename the file copy.c to original name
rename("copy.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename, "r");
c = getc(fp1);
while (c != EOF) {
printf("%c", c);
c = getc(fp1);
}
fclose(fp1);
return 0;
}
Output:
Enter file name:abc.txt
hi.
Hello
how are you?
I am fine
hope the same
Enter line number of the line to be deleted:4
The contents of file after being modified are as follows:
hi.
hello
how are you?
hope the same
Explanation:
In this program, user is asked for a filename that needs to be modified. Entered file name is stored in a char
array 'filename'. This file is opened in read mode using file pointer 'fp1'. Character 'c' is used to read characters
from the file and print them to the output. User is asked for the line number in the file to be deleted. The file
pointer is rewinded back and all the lines of the file except for the line to be deleted are copied into another file
"copy.c". Now "copy.c" is renamed to the original filename. The original file is opened in read mode and the
modified contents of the file are displayed on the screen.
17.Write a program to replace a specified line in a text file.
Program: Program to replace a specified line in a text file.
#include
int main(void) {
FILE *fp1, *fp2;
//'filename'is a 40 character string to store filename
char filename[40];
char c;
int del_line, temp = 1;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in 'filename'
scanf("%s", filename);
fp1 = fopen(filename, "r");
//open file in read mode
c = getc(fp1);
//print the contents of file .
while (c != EOF) {
printf("%c", c);
c = getc(fp1);
}
//ask user for line number to be deleted.
printf(" \n Enter line number to be deleted and replaced");
scanf("%d", &del_line);
//take fp1 to start point.
rewind(fp1);
//open copy.c in write mode
fp2 = fopen("copy.c", "w");
c = getc(fp1);
while (c != EOF) {
if (c == '\n') {
temp++;
}
//till the line to be deleted comes,copy the content from one file to other
if (temp != del_line){
putc(c, fp2);
}
else //when the line to be deleted comes
{
while ((c = getc(fp1)) != '\n') {
}
//read and skip the line ask for new text
printf("Enter new text");
//flush the input stream
fflush(stdin);
putc('\n', fp2);
//put '\n' in new file
while ((c = getchar()) != '\n')
putc(c, fp2);
//take the data from user and place it in new file
fputs("\n", fp2);
temp++;
}
//continue this till EOF is encountered
c = getc(fp1);
}
//close both files
fclose(fp1);
fclose(fp2);
//remove original file
remove(filename);
//rename new file with old name opens the file in read mode
rename("copy.c", filename);
fp1 = fopen(filename, "r");
//reads the character from file
c = getc(fp1);
//until last character of file is encountered
while (c != EOF){
printf("%c", c);
//all characters are printed
c = getc(fp1);
}
//close the file pointer
fclose(fp1);
return 0;
}
Output:
Enter file name:abc.txt
hi.
hello
how are you?
hope the same
Enter line number of the line to be deleted and replaced:4
Enter new text: sayonara see you soon
hi.
hello
how are you?
sayonara see you soon
Explanation:
In this program, the user is asked to type the name of the file. The File by name entered by user is opened in
read mode. The line number of the line to be replaced is asked as input. Next the data to be replaced is asked. A
new file is opened in write mode named "copy.c". Now the contents of original file are transferred into new file
and the line to be modified is deleted. New data is stored in its place and remaining lines of the original file are
also transferred. The copied file with modified contents is replaced with the original file's name. Both the file
pointers are closed and the original file is again opened in read mode and the contents of the original file is
printed as output.
18.Write a program to find the number of lines in a text file.
Number of lines in a file can be determined by counting the number of new line characters present.
Program: Program to count number of lines in a file.
#include
int main()
/* Ask for a filename and count number of lines in the file*/
{
//a pointer to a FILE structure
FILE *fp;
int no_lines = 0;
//consider 40 character string to store filename
char filename[40], sample_chr;
//asks user for file name
printf("Enter file name: ");
//receives file name from user and stores in a string named 'filename'
scanf("%s", filename);
//open file in read mode
fp = fopen(filename, "r");
//get character from file and store in sample_chr
sample_chr = getc(fp);
while (sample_chr != EOF) {
//Count whenever sample_chr is '\n'(new line) is encountered
if (sample_chr == '\n')
{
//increment variable 'no_lines' by 1
no_lines=no_lines+1;
}
//take next character from file.
sample_chr = getc(fp);
}
fclose(fp); //close file.
printf("There are %d lines in %s \n", no_lines, filename);
return 0;
}
Output:
Enter file name:abc.txt
There are 4 lines in abc.txt
Explanation:
In this program, name of the file to be read is taken as input. A file by the given name is opened in read-mode
using a File pointer 'fp'. Characters from the file are read into a char variable 'sample_chr' with the help of getc
function. If a new line character('\n') is encountered, the integer variable 'no_lines' is incremented. If the
character read into 'sample_char' is not a new line character, next character is read from the file. This process is
continued until the last character of the file(EOF) is encountered. The file pointer is then closed and the total
number of lines is shown as output.
19.Write a C program which asks the user for a number between 1 to 9 and shows the number. If the
user inputs a number out of the specified range, the program should show an error and prompt
the user for a valid input.
Program: Program for accepting a number in a given range.
#include
int getnumber();
int main() {
int input = 0;
//call a function to input number from key board
input = getnumber();
//when input is not in the range of 1 to 9,print error message
while (!((input <= 9) && (input >= 1))) {
printf("[ERROR] The number you entered is out of range");
//input another number
input = getnumber();
}
//this function is repeated until a valid input is given by user.
printf("\nThe number you entered is %d", input);
return 0;
}/
/this function returns the number given by user
int getnumber() {
int number;
//asks user for a input in given range
printf("\nEnter a number between 1 to 9 \n");
scanf("%d", &number);
return (number);
}
Output:
Enter a number between 1 to 9
45
[ERROR] The number you entered is out of range
Enter a number between 1 to 9
4
The number you entered is 4
Explanation:
getfunction() function accepts input from user. 'while' loop checks whether the number falls within range or not
and accordingly either prints the number(If the number falls in desired range) or shows error message(number is
out of range).
20.Write a program to display the multiplication table of a given number.
Program: Multiplication table of a given number
#include
int main() {
int num, i = 1;
printf("\n Enter any Number:");
scanf("%d", &num);
printf("Multiplication table of %d: \n", num);
while (i <= 10) {
printf("\n %d x %d = %d", num, i, num * i);
i++;
}
return 0;
}
Output:
Enter any Number:5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Explanation:
We need to multiply the given number (i.e. the number for which we want the multiplication table)
with value of 'i' which increments from 1 to 10.
Tuesday, December 20, 2011
Some IMP question Phased by me (CISCO,AMAZON,White Thomas India PvtlTD)
1>wap for finding the nth element in NODE.
2>wap to finding the given
3>how to reverse a LINKED list ?
4>there are 50 elements(1-50) in a 100size array ,they put randomly.how to find the how many no. are repeated and how many time ?(complexity should be 0(n)).
2>wap to finding the given
linked list is palindrome
or not .3>how to reverse a LINKED list ?
4>there are 50 elements(1-50) in a 100size array ,they put randomly.how to find the how many no. are repeated and how many time ?(complexity should be 0(n)).
*********************** THE C PREPROCESSOR *************************
***********************************************************************
1] If the file to be included doesn't exist, the preprocessor flashes an error message. < True / False>
2] The preprocessor can trap simple errors like missing declarations, nested comments or mismatck of braces.
3] What would be the output of the following program?
# define SQR(x) (x * x)
main()
{
int a, b = 3;
a = SQR(b + 2);
printf("\n %d",a);
}
OPTIONS:
(a) 25
(b) 11
(c) Error
(d) Some garbage value
4] How would you define the SQR macro in 6.3 above such that it gives the result of a as 25.
5] What would be the output of the following program?
# define CUBE(x) (x * x * x)
main()
{
int a, b = 3;
a = CUBE(b++);
printf("\n %d %d",a,b);
}
6] Indicate what would the SWAP macro be expanded to on preprocessing. Would the code compile?
# define SWAP(a,b,c) (ct; t = a; a = b; b = t;)
main()
{
int x = 10,y = 20;
SWAP(x,y,int);
printf("%d %d",x,y);
}
7] How would you modify the SWAP macro in 6.6 above such that it is able to exchange two integers.
8] What is the limitation of the SWAP macro of 6.7 above?
9] In which line of the following program an error would be reported?
(1) #define CIRCUM(R) (3.14 * R * R);
(2) main()
(3) {
(4) float r = 1.0, c;
(5) c = CIRCUM(r);
(6) printf("\n %f",c);
(7) if(CIRCUM(r) == 6.28)
(8) printf("\n Gobbledygook");
(9) }
10] What is the type of the variable 'b' in the following declaration?
# define FLOATPTR float*
FLOATPTR a,b;
11] Is it necessary that the header files should have a '.h' extension?
12] What do the header files usually contain?
13] Would it result into an error if a header file is included twice? < Yes / No>
14] How can a header file ensure that it doesn't get included more than once?
15] On inclusion, where are the header files searched for?
16] Would the following typedef work?
typedef #include I;
17] Would the following code compile correctly?
main()
{
#ifdef NOTE
/* unterminated comment */
int a;
a = 10;
#else
int a;
a = 20;
#endif
printf("%d",a);
}
18] What would be the output of the following program?
#define MESS Junk
main()
{
printf("MESS");
}
19] Would the following program print the message infinite number of times?
#define INFINITELOOP while(1)
main()
{
INFINITELOOP
printf("\n Grey haired");
}
20] What would be the output of the following program?
#define MAX(a,b) ( a>b? a:b)
main()
{
int x;
x = MAX(3 + 2,2 + 7);
printf("%d",x);
}
21] What would be the output of the following program?
#define PRINT(int) printf("%d",int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
22] What would be the output of the following program?
#define PRINT(int) printf(*int = %d*,int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
23] How would you modify the macro of 6.22 such that it outputs:
x = 2 y = 3 z = 4
24] Would the following program compile successfully? < Yes / No) main() { printf("Tips" "Traps); } 25] Define the macro DEBUG such that the following program outputs: DEBUG: x = 4 DEBUG: y = 3.140000 DEBUG: ch = A main() { int x = 4; float a = 3.14; char ch = 'A'; DEBUG(x,%d); DEBUG(a,%f); DEBUG(ch,%c); } *********************************************************************** ********************** ANSWERS *************************** *********************************************************************** 1] True 2] False 3] B. Because, on preprocessing the expression becomes 'a = a(3 + 2 * 3 + 2). 4] #define SQR(x) ((x) * (x)) 5] 27 6. Though some compilers may give this as the answer, according to the ANSI C standard the expression b++ * b++ * b++ is undefined. Refer Chapter 3 for more details on this. 6] (int t; t = a, a = b, b= t); This code won't compile since declaration of t cannot occur within parentheses. 7] #define SWAP(a,b,c) ct; t = a, a = b, b = t; 8] It cannot swap pointers. For example, the following code would not compile. #define SWAP(a,b,c) ct; t = a, a = b, b = t; main() { float x = 10,y = 20; float *p,*q; p = &x; q = &y; SWAP(p,q,float*); printf("%f %f",x,y); } 9] Line number 7, whereas the culprit is really the semicolon in line number 1. On expansion line 7 becomes ' if ((3.14 * 1.0 * 1.0); == 6.28). Hence the error. 10] 'float' and not a pointer to a float, since on expansion the declaration becomes: float *a,b; 11] No. However, traditionally they have been given a .h extension to identify them as someting different than the .c program files. 12] Preprocessor directives like #define, structure, union and enum declarations, typedef declarations, global variable declarations and external function declarations. YOu should not write the actual code ( i.e. function bodies) or global variable definition (that is difining or initialising instances) in header files. The # include directives should be used to pull in header files, not other .c files. 13] Yes, unless the header file has taken care to ensure that if already included it doesn't get included again. 14] All declarations must be written in the manner shown below. Assume that the name of the header file in FUNCS.H. /* funcs.h */ #ifdef_FUNCS #define_FUNCS /* all declarations would go here */ #endif Now if we include this file twice as shown below, it would get included only once. #include "goto.c" #include "goto.c" main() { /* some code */ } 15] If included using <> the files get searched in the predefined (can be changed) include path. If included withe the " " syntax in addition to the predefined include path the files also get searched in the current directory ( usually the directory form which you inboked the compiler).
16] No. Because 'typedef' goes to work after preprocessing.
17] No. Even though the #ifdef fails in this case ( NOTE being undefined) and the if block doesn't go for compilation errors in it are not permitted.
18] MESS
19] Yes
20] 9
21] 2 3 4
22] int = 2 int = 3 int = 4
23] #defien PRINT(int) printf(#int "= %d", int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
The rule is if the parameter name is preceded by a # in the macro expansion, the combination(of # and parameter) will be expanded into quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to print the output desired in our program. On expansion the macro becomes:
printf("x" "= %d",x);
The two strings get concatenated, so the effect is
printf("x = %d",x);
24] Yes. The output would be TipsTraps. In fact this result has been used in 6.23 above.
25] #define DEBUG(var,fmt) printf("DEBUG:" #var "="#fmt"\n",var)
26] multiply
Here two operations are being carried out expansion and stringizinf. Xstr() macro expands its argument, and then str() stringizes it.
27] #define PRINT(var1,var2,var3) printf("\n" #var1 "= %d" #var2 "= %d" #var3 "= %d",var1,var2,var3)
1] If the file to be included doesn't exist, the preprocessor flashes an error message. < True / False>
2] The preprocessor can trap simple errors like missing declarations, nested comments or mismatck of braces.
3] What would be the output of the following program?
# define SQR(x) (x * x)
main()
{
int a, b = 3;
a = SQR(b + 2);
printf("\n %d",a);
}
OPTIONS:
(a) 25
(b) 11
(c) Error
(d) Some garbage value
4] How would you define the SQR macro in 6.3 above such that it gives the result of a as 25.
5] What would be the output of the following program?
# define CUBE(x) (x * x * x)
main()
{
int a, b = 3;
a = CUBE(b++);
printf("\n %d %d",a,b);
}
6] Indicate what would the SWAP macro be expanded to on preprocessing. Would the code compile?
# define SWAP(a,b,c) (ct; t = a; a = b; b = t;)
main()
{
int x = 10,y = 20;
SWAP(x,y,int);
printf("%d %d",x,y);
}
7] How would you modify the SWAP macro in 6.6 above such that it is able to exchange two integers.
8] What is the limitation of the SWAP macro of 6.7 above?
9] In which line of the following program an error would be reported?
(1) #define CIRCUM(R) (3.14 * R * R);
(2) main()
(3) {
(4) float r = 1.0, c;
(5) c = CIRCUM(r);
(6) printf("\n %f",c);
(7) if(CIRCUM(r) == 6.28)
(8) printf("\n Gobbledygook");
(9) }
10] What is the type of the variable 'b' in the following declaration?
# define FLOATPTR float*
FLOATPTR a,b;
11] Is it necessary that the header files should have a '.h' extension?
12] What do the header files usually contain?
13] Would it result into an error if a header file is included twice? < Yes / No>
14] How can a header file ensure that it doesn't get included more than once?
15] On inclusion, where are the header files searched for?
16] Would the following typedef work?
typedef #include I;
17] Would the following code compile correctly?
main()
{
#ifdef NOTE
/* unterminated comment */
int a;
a = 10;
#else
int a;
a = 20;
#endif
printf("%d",a);
}
18] What would be the output of the following program?
#define MESS Junk
main()
{
printf("MESS");
}
19] Would the following program print the message infinite number of times?
#define INFINITELOOP while(1)
main()
{
INFINITELOOP
printf("\n Grey haired");
}
20] What would be the output of the following program?
#define MAX(a,b) ( a>b? a:b)
main()
{
int x;
x = MAX(3 + 2,2 + 7);
printf("%d",x);
}
21] What would be the output of the following program?
#define PRINT(int) printf("%d",int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
22] What would be the output of the following program?
#define PRINT(int) printf(*int = %d*,int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
23] How would you modify the macro of 6.22 such that it outputs:
x = 2 y = 3 z = 4
24] Would the following program compile successfully? < Yes / No) main() { printf("Tips" "Traps); } 25] Define the macro DEBUG such that the following program outputs: DEBUG: x = 4 DEBUG: y = 3.140000 DEBUG: ch = A main() { int x = 4; float a = 3.14; char ch = 'A'; DEBUG(x,%d); DEBUG(a,%f); DEBUG(ch,%c); } *********************************************************************** ********************** ANSWERS *************************** *********************************************************************** 1] True 2] False 3] B. Because, on preprocessing the expression becomes 'a = a(3 + 2 * 3 + 2). 4] #define SQR(x) ((x) * (x)) 5] 27 6. Though some compilers may give this as the answer, according to the ANSI C standard the expression b++ * b++ * b++ is undefined. Refer Chapter 3 for more details on this. 6] (int t; t = a, a = b, b= t); This code won't compile since declaration of t cannot occur within parentheses. 7] #define SWAP(a,b,c) ct; t = a, a = b, b = t; 8] It cannot swap pointers. For example, the following code would not compile. #define SWAP(a,b,c) ct; t = a, a = b, b = t; main() { float x = 10,y = 20; float *p,*q; p = &x; q = &y; SWAP(p,q,float*); printf("%f %f",x,y); } 9] Line number 7, whereas the culprit is really the semicolon in line number 1. On expansion line 7 becomes ' if ((3.14 * 1.0 * 1.0); == 6.28). Hence the error. 10] 'float' and not a pointer to a float, since on expansion the declaration becomes: float *a,b; 11] No. However, traditionally they have been given a .h extension to identify them as someting different than the .c program files. 12] Preprocessor directives like #define, structure, union and enum declarations, typedef declarations, global variable declarations and external function declarations. YOu should not write the actual code ( i.e. function bodies) or global variable definition (that is difining or initialising instances) in header files. The # include directives should be used to pull in header files, not other .c files. 13] Yes, unless the header file has taken care to ensure that if already included it doesn't get included again. 14] All declarations must be written in the manner shown below. Assume that the name of the header file in FUNCS.H. /* funcs.h */ #ifdef_FUNCS #define_FUNCS /* all declarations would go here */ #endif Now if we include this file twice as shown below, it would get included only once. #include "goto.c" #include "goto.c" main() { /* some code */ } 15] If included using <> the files get searched in the predefined (can be changed) include path. If included withe the " " syntax in addition to the predefined include path the files also get searched in the current directory ( usually the directory form which you inboked the compiler).
16] No. Because 'typedef' goes to work after preprocessing.
17] No. Even though the #ifdef fails in this case ( NOTE being undefined) and the if block doesn't go for compilation errors in it are not permitted.
18] MESS
19] Yes
20] 9
21] 2 3 4
22] int = 2 int = 3 int = 4
23] #defien PRINT(int) printf(#int "= %d", int)
main()
{
int x = 2, y = 3, z = 4;
PRINT(x);
PRINT(y);
PRINT(z);
}
The rule is if the parameter name is preceded by a # in the macro expansion, the combination(of # and parameter) will be expanded into quoted string with the parameter replaced by the actual argument. This can be combined with string concatenation to print the output desired in our program. On expansion the macro becomes:
printf("x" "= %d",x);
The two strings get concatenated, so the effect is
printf("x = %d",x);
24] Yes. The output would be TipsTraps. In fact this result has been used in 6.23 above.
25] #define DEBUG(var,fmt) printf("DEBUG:" #var "="#fmt"\n",var)
26] multiply
Here two operations are being carried out expansion and stringizinf. Xstr() macro expands its argument, and then str() stringizes it.
27] #define PRINT(var1,var2,var3) printf("\n" #var1 "= %d" #var2 "= %d" #var3 "= %d",var1,var2,var3)
Variable Number of arguments
1] Which header file should you include if you are to develop a function which can accept variable number of arguments?
Options:
(a) vararg.h
(b) stdlib.h
(c) stdio.h
(d) stdarg.h
2] What would be the output of the following program?
# include
# include
main()
{
fun("Nothing specific", 1,4,7,11,0);
}
fun(char *msg, ...)
{
int tot = 0;
va_list ptr;
int num;
va_start(ptr, msg);
num = va_org(ptr,int);
num = va_arg(ptr,int);
printf("\n%d",num);
}
3] Is it necessary that in a function which accepts variable argument list there should at least be one fixed argument?
< Yes / No >
4] Can the fixed arguments passed to the functio which accepts variable argument list occur at the end? < Yes / No >
5] Point out the error, if any, in the follwoing program.
# include
main()
{
varfun(3,7,-11,0);
}
varfun(intn, ...)
{
va_list ptr;
int num;
num = va_arg(ptr,int);
printf("\n %d",num);
}
6] Point out the error, if any, in the follwoing program.
# include
main()
{
varfun(3,7.5,-11.2,0.66);
}
varfun(int n, ... )
{
float * ptr;
int num;
va_start(ptr,n);
num = va_arg(ptr,int);
printf("\n %d",num);
}
7] Point out the error, if any, in the follwoing program.
# include
main()
{
fun(1,4,7,11,0);
}
fun( ... )
{
va_list ptr;
int num;
va_start(ptr,int);
num = va_arg(ptr,int);
printf("\n %d",num);
}
8] The macro va_start is used to initialise a pointer to the beginning of the list of fixed arguments. < True / False >
9] The macro va_arg is used to extract an argument from the variable argumetn list and advance the pointer to the next argument. < True / False >
10] Point out the error, if any, in the following program.
# include"stdarg.h"
main()
{
display(4,'A','a','b','c');
}
display(int num, ... )
{
char c; int j;
va_list ptr;
va_start(ptr,num);
for(j = 1; j <= num; j++) { c = va_arg(ptr,char); printf("%c",c); } } 11] Mention any variable argument list function that you have used and its prototype. 12] Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display(4,12.5,13.5,14.5,44.3); } display(int num, ... ) { float c; int j; va_list ptr; va_start(ptr, num); for(j = 1; j <= num; j++) { c = va_arg(ptr,float); printf("\n %f",c); } } 13] Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display("Hello",4,2,12.5,13.5,14.5,44); } display(char *s,int num1, int num2, ... ) { float c; int j; va_list ptr; va_start(ptr, num); c = va_arg(ptr,double); printf("\n %f",c); } 14] Can we pass a variable argumetn list to a function at run-time? < Yes / No >
15] While defining a variable argument list function can we drop the ellipsis. ( ... ) < Yes / No >
16] Can we write a function that takes a variable argumetn list and passes the list to another function (which takes a variable number of argumetns) < Yes / No>
17] Point out the error, if any, in the foll0wing program.
# include "stdarg.h"
main()
{
display("Hello",4,12,13,14,44);
}
display(char *s, ... )
{
show(s, ... )
}
show(char *t, ... )
{
va_list ptr;
int a;
va_start(ptr,t);
a = va_arg(ptr,int);
printf("%f",a);
}
18] How would you rewrite program 18.17 such that show() is able to handle variable argument list?
19] If I use the following printf() to proint a long int why I am not warned about the type mismatch?
printf("%d",num);
20] Can you write a function that works similar to 'printf()'?
21] How can a called function determine the number of arguments that have been passed to it?
22] Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
23] Point out the error in the following program.
# include "stdarg.h"
main()
{
int (*p1)();
int (*p2)();
int fun1(),fun();
p1 = fun1();
p2 = fun2();
display("Bye",p1,p2);
}
display(char *s, ... )
{
int (*pp1)();
va_list ptr;
va_start(ptr,s);
pp1 = va_arg(ptr,int(*)());
(*pp1)();
pp2 = va_arg(ptr,int(*)());
(*pp2)();
}
fun1()
{
printf("Hello");
}
fun2()
{
printf("Hi");
}
24] How would you rectify the error in the program 18.23 above?
***********************************************************************
************************* ANSWERS *****************************
***********************************************************************
1] D
2] 4
3] Yes
4] No
5] Since 'ptr' has not been set at the beginning of the variable argument list using va_start it may be pointing anywhere and hence a call to va_arg would fetch a wrong integer.
6] Irrespective of the type of argument passed to a function receiving variable argument list, 'ptr' must be of the type va_list.
7] There is no fixed argument i n the definition of 'fun()'.
8] False
9] True
10] While extracting a 'char' argument using va_arg we should have used c = va_arg(ptr,int).
11] printf(const char *format, ... )
12] While extracting a float argrment using va_arg we should have used c = va_arg(ptr,double).
13] While setting the 'ptr' to the beginning of variable argument list we should have used va_start(ptr,num2).
14] No. Every actual argument list must be completely known at compile time. In that sense it is not truely a variable argument list.
15] Yes
16] Yes
17] The call to 'show()' is improper. This is not the way to pass variable argument list to a function.
18] # include"stdarg.h"
main()
{
display("Hello",4,12,13,14,44);
}
display(char *s, ... )
{
va_list ptr;
va_start(ptr,s);
show(s,ptr);
}
show(char *,va_list ptr1)
{
int a,n,i;
a = va_arg(ptr1,int);
for(i = 0; i < a; i++) { n = va_arg(ptr1,int); printf("\n %d",n); } } 19] When a function accepts a variable number of arguments, its prototype cannot provide any information about the number of arguments and type of those variable arguments. Hence the compiler cannot warn about the mismatches. The programmer must make sure that arguments match or must manually insert explicit typecasts. 20] # include
# include
main()
{
void myprintf(char *, ... )
char *convert(unsigned int,int);
int i = 65;
char str[] = "Intranets are here to stay ..";
myprintf("\n Message = %s, %d %x",str,i,i);
}
void myprintf(char *fmt, ... )
{
char *p;
int i;
unsigned j;
char *s;
va_list argp;
va_start(argp,fmt);
p = fmt;
for(p = fmt; *p != '\0\; p++)
{
if(*p != '%')
{
putchar (*p);
continue;
}
p++;
switch(*p)
{
case 'c':
i = va_arg(argp,int);
putchar(i);
break;
case 'd':
i = va_arg(argp,int);
if(i < 0)
{
i = -i;
purchar('-');
}
puts(cionvert(i,10));
break;
case 'o':
u = va_arg(argp,unsigned int);
puts(convert(u,8));
break;
case 's':
s = va_arg(argp,char *);
puts(s);
break;
case 'u':
u = va_arg(argp,unsigned int);
puts(convert(u,10));
break;
case 'x':
u = va_arg(argp,unsigned int);
puts(convert(u,16));
break;
case '%':
purchar('%');
break;
}
}
va_end(argp);
}
char *convert(unsigned int num, int base)
{
static char buff[33];
char *ptr;
ptr = &buff[sizeof(buff) - 1];
*ptr = '\0\;
do
{
*--ptr = "0123456789abcdef"[num % base];
num /= base;
}while(num != 0);
returnptr;
}
21] It cannot. Any function that takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. The printf() function, for example, does this by looking for format specifiers (%d etc.) in the format string. This is the reason why such functions fail badly if the format string does not match the argument list.
22] When the arguments passed are all of same type we can think of passing a sentinel value like -1 or 0 or a NULL pointer at the end of the variable argument list. Another way could be to explicitly pass the count of number of variable arguments.
23] 'va_arg' cannot extract the function pointer from the variable argument list in the manner tried here.
24] Use 'typedef' as shown below:
# include"stdarg.h"
main()
{
int(*p1)();
int(*p2)();
int fun1(),fun2();
p1 = fun1;
p2 = fun2;
display("Bye",p1,p2);
}
display(char *s, ... )
{
int (*pp1)(),(*pp2)();
va_list ptr;
typedef int(*funcptr)();
va_start(ptr,s);
pp1 = va_arg(ptr,funcptr);
(*pp1)();
pp2 = va_arg(ptr,funcptr);
(*pp2)();
}
fun1()
{
printf("\n Hello");
}
fun2()
{
printf("\n Hi");
}
Options:
(a) vararg.h
(b) stdlib.h
(c) stdio.h
(d) stdarg.h
2] What would be the output of the following program?
# include
# include
main()
{
fun("Nothing specific", 1,4,7,11,0);
}
fun(char *msg, ...)
{
int tot = 0;
va_list ptr;
int num;
va_start(ptr, msg);
num = va_org(ptr,int);
num = va_arg(ptr,int);
printf("\n%d",num);
}
3] Is it necessary that in a function which accepts variable argument list there should at least be one fixed argument?
< Yes / No >
4] Can the fixed arguments passed to the functio which accepts variable argument list occur at the end? < Yes / No >
5] Point out the error, if any, in the follwoing program.
# include
main()
{
varfun(3,7,-11,0);
}
varfun(intn, ...)
{
va_list ptr;
int num;
num = va_arg(ptr,int);
printf("\n %d",num);
}
6] Point out the error, if any, in the follwoing program.
# include
main()
{
varfun(3,7.5,-11.2,0.66);
}
varfun(int n, ... )
{
float * ptr;
int num;
va_start(ptr,n);
num = va_arg(ptr,int);
printf("\n %d",num);
}
7] Point out the error, if any, in the follwoing program.
# include
main()
{
fun(1,4,7,11,0);
}
fun( ... )
{
va_list ptr;
int num;
va_start(ptr,int);
num = va_arg(ptr,int);
printf("\n %d",num);
}
8] The macro va_start is used to initialise a pointer to the beginning of the list of fixed arguments. < True / False >
9] The macro va_arg is used to extract an argument from the variable argumetn list and advance the pointer to the next argument. < True / False >
10] Point out the error, if any, in the following program.
# include"stdarg.h"
main()
{
display(4,'A','a','b','c');
}
display(int num, ... )
{
char c; int j;
va_list ptr;
va_start(ptr,num);
for(j = 1; j <= num; j++) { c = va_arg(ptr,char); printf("%c",c); } } 11] Mention any variable argument list function that you have used and its prototype. 12] Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display(4,12.5,13.5,14.5,44.3); } display(int num, ... ) { float c; int j; va_list ptr; va_start(ptr, num); for(j = 1; j <= num; j++) { c = va_arg(ptr,float); printf("\n %f",c); } } 13] Point out the error, if any, in the follwoing program. # include"stdarg.h" main() { display("Hello",4,2,12.5,13.5,14.5,44); } display(char *s,int num1, int num2, ... ) { float c; int j; va_list ptr; va_start(ptr, num); c = va_arg(ptr,double); printf("\n %f",c); } 14] Can we pass a variable argumetn list to a function at run-time? < Yes / No >
15] While defining a variable argument list function can we drop the ellipsis. ( ... ) < Yes / No >
16] Can we write a function that takes a variable argumetn list and passes the list to another function (which takes a variable number of argumetns) < Yes / No>
17] Point out the error, if any, in the foll0wing program.
# include "stdarg.h"
main()
{
display("Hello",4,12,13,14,44);
}
display(char *s, ... )
{
show(s, ... )
}
show(char *t, ... )
{
va_list ptr;
int a;
va_start(ptr,t);
a = va_arg(ptr,int);
printf("%f",a);
}
18] How would you rewrite program 18.17 such that show() is able to handle variable argument list?
19] If I use the following printf() to proint a long int why I am not warned about the type mismatch?
printf("%d",num);
20] Can you write a function that works similar to 'printf()'?
21] How can a called function determine the number of arguments that have been passed to it?
22] Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
23] Point out the error in the following program.
# include "stdarg.h"
main()
{
int (*p1)();
int (*p2)();
int fun1(),fun();
p1 = fun1();
p2 = fun2();
display("Bye",p1,p2);
}
display(char *s, ... )
{
int (*pp1)();
va_list ptr;
va_start(ptr,s);
pp1 = va_arg(ptr,int(*)());
(*pp1)();
pp2 = va_arg(ptr,int(*)());
(*pp2)();
}
fun1()
{
printf("Hello");
}
fun2()
{
printf("Hi");
}
24] How would you rectify the error in the program 18.23 above?
***********************************************************************
************************* ANSWERS *****************************
***********************************************************************
1] D
2] 4
3] Yes
4] No
5] Since 'ptr' has not been set at the beginning of the variable argument list using va_start it may be pointing anywhere and hence a call to va_arg would fetch a wrong integer.
6] Irrespective of the type of argument passed to a function receiving variable argument list, 'ptr' must be of the type va_list.
7] There is no fixed argument i n the definition of 'fun()'.
8] False
9] True
10] While extracting a 'char' argument using va_arg we should have used c = va_arg(ptr,int).
11] printf(const char *format, ... )
12] While extracting a float argrment using va_arg we should have used c = va_arg(ptr,double).
13] While setting the 'ptr' to the beginning of variable argument list we should have used va_start(ptr,num2).
14] No. Every actual argument list must be completely known at compile time. In that sense it is not truely a variable argument list.
15] Yes
16] Yes
17] The call to 'show()' is improper. This is not the way to pass variable argument list to a function.
18] # include"stdarg.h"
main()
{
display("Hello",4,12,13,14,44);
}
display(char *s, ... )
{
va_list ptr;
va_start(ptr,s);
show(s,ptr);
}
show(char *,va_list ptr1)
{
int a,n,i;
a = va_arg(ptr1,int);
for(i = 0; i < a; i++) { n = va_arg(ptr1,int); printf("\n %d",n); } } 19] When a function accepts a variable number of arguments, its prototype cannot provide any information about the number of arguments and type of those variable arguments. Hence the compiler cannot warn about the mismatches. The programmer must make sure that arguments match or must manually insert explicit typecasts. 20] # include
# include
main()
{
void myprintf(char *, ... )
char *convert(unsigned int,int);
int i = 65;
char str[] = "Intranets are here to stay ..";
myprintf("\n Message = %s, %d %x",str,i,i);
}
void myprintf(char *fmt, ... )
{
char *p;
int i;
unsigned j;
char *s;
va_list argp;
va_start(argp,fmt);
p = fmt;
for(p = fmt; *p != '\0\; p++)
{
if(*p != '%')
{
putchar (*p);
continue;
}
p++;
switch(*p)
{
case 'c':
i = va_arg(argp,int);
putchar(i);
break;
case 'd':
i = va_arg(argp,int);
if(i < 0)
{
i = -i;
purchar('-');
}
puts(cionvert(i,10));
break;
case 'o':
u = va_arg(argp,unsigned int);
puts(convert(u,8));
break;
case 's':
s = va_arg(argp,char *);
puts(s);
break;
case 'u':
u = va_arg(argp,unsigned int);
puts(convert(u,10));
break;
case 'x':
u = va_arg(argp,unsigned int);
puts(convert(u,16));
break;
case '%':
purchar('%');
break;
}
}
va_end(argp);
}
char *convert(unsigned int num, int base)
{
static char buff[33];
char *ptr;
ptr = &buff[sizeof(buff) - 1];
*ptr = '\0\;
do
{
*--ptr = "0123456789abcdef"[num % base];
num /= base;
}while(num != 0);
returnptr;
}
21] It cannot. Any function that takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. The printf() function, for example, does this by looking for format specifiers (%d etc.) in the format string. This is the reason why such functions fail badly if the format string does not match the argument list.
22] When the arguments passed are all of same type we can think of passing a sentinel value like -1 or 0 or a NULL pointer at the end of the variable argument list. Another way could be to explicitly pass the count of number of variable arguments.
23] 'va_arg' cannot extract the function pointer from the variable argument list in the manner tried here.
24] Use 'typedef' as shown below:
# include"stdarg.h"
main()
{
int(*p1)();
int(*p2)();
int fun1(),fun2();
p1 = fun1;
p2 = fun2;
display("Bye",p1,p2);
}
display(char *s, ... )
{
int (*pp1)(),(*pp2)();
va_list ptr;
typedef int(*funcptr)();
va_start(ptr,s);
pp1 = va_arg(ptr,funcptr);
(*pp1)();
pp2 = va_arg(ptr,funcptr);
(*pp2)();
}
fun1()
{
printf("\n Hello");
}
fun2()
{
printf("\n Hi");
}
FACTS ABOUT ARRAYS
1] An array is a collection of similar elements. It is also known as a subscripted variable.
2] Before using an array its type and size must be declared. For example
int arr[30];
float a[60];
char ch[25];
3] The first element in the array is numbered as 0, so the last element is 1 less than the seze of the array.
4] However big an array may be, its elements are always stored in contigouos locations.
5] If we desire an array can be initilised at the same place where it is declared. For example,
int num[6] = {2,3,12,5,45,5};
int n[] = {2,4,12,5,45,5};
float press[] = {12.3,34.2,-23.4,-11.3};
6] If the array is initialised where it is declared, mentioning the dimension of the array is optional as in 2nd example above.
7] Till the array elements are not given any specific values, they are supposed to contain garbage values.
8] In 'C' there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; porbably on top of other data, or on the porgram itself. This will lead to unpredictable results, to say the least, and there will be no error message to warn you that you are going beyond the array size. In some cases the computer may just hang. Thus, the following program may turn out to be suicidal;:
/* program */
main()
{
int num[40];
for(i = 0;i<= 100;i++)
num[i] = i;
}
So do remember that, to see to it that we do not reach beyond the array size is entirely the programmer's botheraation and not the compiler's.
While accessing array elements call by reference method is faster as compared to accessing elements by subscripts. However for convenience in programming we should observe the following :
Array elements should be accessed using pointers, if the elements are to be accessed in a fixed order, say form beginning to end, or form end to beginning, or every alternate element or any such definite logic.
It would be easier to access the elements using a subscript if there is no fixed logic in accessing the elements. However, in this case also, accessing the elements by pointers would work faster than subscripts.
2] Before using an array its type and size must be declared. For example
int arr[30];
float a[60];
char ch[25];
3] The first element in the array is numbered as 0, so the last element is 1 less than the seze of the array.
4] However big an array may be, its elements are always stored in contigouos locations.
5] If we desire an array can be initilised at the same place where it is declared. For example,
int num[6] = {2,3,12,5,45,5};
int n[] = {2,4,12,5,45,5};
float press[] = {12.3,34.2,-23.4,-11.3};
6] If the array is initialised where it is declared, mentioning the dimension of the array is optional as in 2nd example above.
7] Till the array elements are not given any specific values, they are supposed to contain garbage values.
8] In 'C' there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; porbably on top of other data, or on the porgram itself. This will lead to unpredictable results, to say the least, and there will be no error message to warn you that you are going beyond the array size. In some cases the computer may just hang. Thus, the following program may turn out to be suicidal;:
/* program */
main()
{
int num[40];
for(i = 0;i<= 100;i++)
num[i] = i;
}
So do remember that, to see to it that we do not reach beyond the array size is entirely the programmer's botheraation and not the compiler's.
While accessing array elements call by reference method is faster as compared to accessing elements by subscripts. However for convenience in programming we should observe the following :
Array elements should be accessed using pointers, if the elements are to be accessed in a fixed order, say form beginning to end, or form end to beginning, or every alternate element or any such definite logic.
It would be easier to access the elements using a subscript if there is no fixed logic in accessing the elements. However, in this case also, accessing the elements by pointers would work faster than subscripts.
Control Funtion in C
1] What would be the output of the following program?
main()
{
int i = 4;
switch(i)
{
default:
printf("\n a mouse is an elephant built by the japanese.");
case 1:
printf("\n Breeding rabbits is a hare raising experience.");
case 2:
printf("\n Friction is drag.");
case3:
printf("\n If practice makes perfect, then nobody's perfect");
}
}
2] Point out the error, if any, in the for loop:
main()
{
int i = 1;
for( ; ; )
{
printf("%d",i++);
if (i > 10)
break;
}
}
OPTIONS:
(a) The condition in the for loop is a must.
(b) The two semicolons should be dropped.
(c) The for loop should be replaced by a while loop.
(d) No error.
3] Point out to the error, if any, in the while loop:
main()
{
int i = 1;
while()
{
printf("%d",i++);
if (i > 10)
break;
}
}
OPTIONS:
(a) The condition in the while loop is a must.
(b) Thereshould be a semicolons in the while loop.
(c) The while loop should be replaced by a for loop.
(d) No error.
4] Point out the error, if any, in the while loop:
main()
{
int i = 1;
while(i <= 5) { printf("%d",i); if( i > 2)
goto here;
}
}
fun()
{
here:
printf("\n If it works, Don't fix it.");
}
5] Point out the error, if any, in the following program:
main()
{
int i = 4, j = 2;
switch(i)
{
case 1:
printf("\n To err is human, to forgive is against company policy.");
case j:
printf("\n If you have nothing to do, don't do it here.");
break;
}
}
6] Point out the error, if any, in the following program:
main()
{
int i = 1;
switch(i)
{
case 1:
printf("\n Radioactive cats have 18 half-lives.");
break;
case 1*2+4:
printf("\n Bottle for rent-inquire within.");
break;
}
}
7] Point out the error, if any, in the following program:
main()
{
int i = 10;
switch(a)
{
}
printf("Programmers never die. They just get lost in the processing.");
}
8] Point out the error,if any, in the following program:
main()
{
int i = 1;
switch(i)
{
printf("Hello");
case 1:
printf("\n Individualists unite.");
break;
case 2:
printf("\n Money is the root of all wealth.");
break;
}
}
9] Rewrite the following set of statements using conditional operators:
int a = 1,b;
if(a > 10)
b = 20;
10] Point out the error, if any, in the following program:
main()
{
int a = 10, b;
a >= 5? b = 100: b = 200;
printf("\n %d",b);
}
11] What would be the output of the following program?
main()
{
char str[] = "part-time musicians are semiconductors";
int a = 5;
printf( a > 10 ? "%50s":"%s",str);
}
OPTIONS:
(a) Part-time musicians are semiconductors
(b) Part-time musicians are semiconductors
(c) Error
(d) None of the above
12] What is more efficient a 'switch' statement or an 'if-else' chain?
13] Can we use a 'switch' statement to switch on strings?
14] We want to test whether a value lies in the range 2 to 4 or 5 to 7. Can we do this using a 'switch'?
15] The way 'break' is used to take the control out of 'switch' can 'continue' be used to take the control to the beginning of the 'switch?
************************ ANSWERS ***********************
1] A mouse is an elephant built by the Japanese
Breeding rabbits is a hare raising experience
2] D
3] A
4] 'goto' cannot take control to a different function.
5] Constant expression required in the second case, we cannot use j.
6] No error. Constant exprerssions like 1*2+4 are acceptable in cases of a 'switch'.
7] Though never required, there can exist a 'switch which has no cases.
8] Though there is no error, irrespective of the value of i the first 'printf()' can never get executed. In other words, all statements in a switch have to beling to some case or the other.
9] int a = 1,b,dummy;
a > 10 ? b = 20: dummy = 1;
Note that the following would not have worked:
a > 10 ? b = 20: ; ;
10] 1value required in function 'amin()'. The second assignment should be written in parentheses as follows:
a >= 5 ? b = 100: (b = 200);
11] A
12] As far as eficiency is concerned there would hardly be any difference if at all. If the cases in a 'switch' are sparsely distributed the compiler may internally use the equivalent of an 'if-else' chain instead of a compact jump table. However, one should use 'switch' where one can. It is definitely a cleaner way to program and certainly is not any less efficient than the 'if-else' chain.
13] No. The cases in a 'switch' must either have integer constants or constant experssion.
14] Yes, though in a way which would not be very pratical if the ranges are bigger. The vay is ahown below:
switch(a)
{
case 2:
case 3:
case 4:
/* statements */
case 5:
case 6:
case 7:
/* some other statements */
break;
}
15] No. 'continue' can work only with loops and not with 'switch'.
main()
{
int i = 4;
switch(i)
{
default:
printf("\n a mouse is an elephant built by the japanese.");
case 1:
printf("\n Breeding rabbits is a hare raising experience.");
case 2:
printf("\n Friction is drag.");
case3:
printf("\n If practice makes perfect, then nobody's perfect");
}
}
2] Point out the error, if any, in the for loop:
main()
{
int i = 1;
for( ; ; )
{
printf("%d",i++);
if (i > 10)
break;
}
}
OPTIONS:
(a) The condition in the for loop is a must.
(b) The two semicolons should be dropped.
(c) The for loop should be replaced by a while loop.
(d) No error.
3] Point out to the error, if any, in the while loop:
main()
{
int i = 1;
while()
{
printf("%d",i++);
if (i > 10)
break;
}
}
OPTIONS:
(a) The condition in the while loop is a must.
(b) Thereshould be a semicolons in the while loop.
(c) The while loop should be replaced by a for loop.
(d) No error.
4] Point out the error, if any, in the while loop:
main()
{
int i = 1;
while(i <= 5) { printf("%d",i); if( i > 2)
goto here;
}
}
fun()
{
here:
printf("\n If it works, Don't fix it.");
}
5] Point out the error, if any, in the following program:
main()
{
int i = 4, j = 2;
switch(i)
{
case 1:
printf("\n To err is human, to forgive is against company policy.");
case j:
printf("\n If you have nothing to do, don't do it here.");
break;
}
}
6] Point out the error, if any, in the following program:
main()
{
int i = 1;
switch(i)
{
case 1:
printf("\n Radioactive cats have 18 half-lives.");
break;
case 1*2+4:
printf("\n Bottle for rent-inquire within.");
break;
}
}
7] Point out the error, if any, in the following program:
main()
{
int i = 10;
switch(a)
{
}
printf("Programmers never die. They just get lost in the processing.");
}
8] Point out the error,if any, in the following program:
main()
{
int i = 1;
switch(i)
{
printf("Hello");
case 1:
printf("\n Individualists unite.");
break;
case 2:
printf("\n Money is the root of all wealth.");
break;
}
}
9] Rewrite the following set of statements using conditional operators:
int a = 1,b;
if(a > 10)
b = 20;
10] Point out the error, if any, in the following program:
main()
{
int a = 10, b;
a >= 5? b = 100: b = 200;
printf("\n %d",b);
}
11] What would be the output of the following program?
main()
{
char str[] = "part-time musicians are semiconductors";
int a = 5;
printf( a > 10 ? "%50s":"%s",str);
}
OPTIONS:
(a) Part-time musicians are semiconductors
(b) Part-time musicians are semiconductors
(c) Error
(d) None of the above
12] What is more efficient a 'switch' statement or an 'if-else' chain?
13] Can we use a 'switch' statement to switch on strings?
14] We want to test whether a value lies in the range 2 to 4 or 5 to 7. Can we do this using a 'switch'?
15] The way 'break' is used to take the control out of 'switch' can 'continue' be used to take the control to the beginning of the 'switch?
************************ ANSWERS ***********************
1] A mouse is an elephant built by the Japanese
Breeding rabbits is a hare raising experience
2] D
3] A
4] 'goto' cannot take control to a different function.
5] Constant expression required in the second case, we cannot use j.
6] No error. Constant exprerssions like 1*2+4 are acceptable in cases of a 'switch'.
7] Though never required, there can exist a 'switch which has no cases.
8] Though there is no error, irrespective of the value of i the first 'printf()' can never get executed. In other words, all statements in a switch have to beling to some case or the other.
9] int a = 1,b,dummy;
a > 10 ? b = 20: dummy = 1;
Note that the following would not have worked:
a > 10 ? b = 20: ; ;
10] 1value required in function 'amin()'. The second assignment should be written in parentheses as follows:
a >= 5 ? b = 100: (b = 200);
11] A
12] As far as eficiency is concerned there would hardly be any difference if at all. If the cases in a 'switch' are sparsely distributed the compiler may internally use the equivalent of an 'if-else' chain instead of a compact jump table. However, one should use 'switch' where one can. It is definitely a cleaner way to program and certainly is not any less efficient than the 'if-else' chain.
13] No. The cases in a 'switch' must either have integer constants or constant experssion.
14] Yes, though in a way which would not be very pratical if the ranges are bigger. The vay is ahown below:
switch(a)
{
case 2:
case 3:
case 4:
/* statements */
case 5:
case 6:
case 7:
/* some other statements */
break;
}
15] No. 'continue' can work only with loops and not with 'switch'.
When Declaration get complicated
1] What do the following declarations signify?
A. int *f();
B. int (*pf)();
C. char **argv;
D. void (*f[10])(int,int);
E. char far *scr;
F. char far *arr[10];
G. int (*a[5])(int far *p);
H. char far *scr1, *scr2;
I. int (*ftable[])(void) = {fadd,fsub,fmul,fdiv};
J. int (*ptr)[30];
K. int *ptr[30];
L. void *cmp();
M. void (*cmp)();
N. char (*(*f())[])();
O. char (*(*x[3])())[5];
P. void (*f)(int, void(*)());
Q. int **(*)(int **, int **(*)(int **, int **));
R. void(*)(void(*)(int *, void **), int(*)(void **, int *));
S. char far * far *ptr;
T. char far * near *ptr;
U. char far * huge *ptr;
2] What would be the output of the following program?
main()
{
char near * near *ptr1;
char near * far *ptr2;
char near * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
3] What would be the output of the following program?
main()
{
char far * near *ptr1;
char far * far *ptr2;
char far * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
4] What would be the output of the following program?
main()
{
char huge * near *ptr1;
char huge * far *ptr2;
char huge * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
5] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
6] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(*ptr2),sizeof(**ptr3));
}
7] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(*ptr1),sizeof(**ptr2),sizeof(ptr3));
}
8] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(**ptr1),sizeof(ptr2),sizeof(*ptr3));
}
9] Are the following two declarations same? < Yes / No>
char far * far *scr;
char far far **scr;
10] How would you declare the following:
- An array of three pointers to chars.
- An array of three char pointers.
- A pointer to an array of three chars.
- A pointer to a function which receives an int pointer and returns a float pointer.
- A pointer to a function which receives nothing and returns nothing.
11] Can you write a program which would implement the follwoing declaration.
void (*f)(int, void (*)());
***********************************************************************
*********************** ANSWERS ***************************
***********************************************************************
1]
A] f is a funciton returning pointer to an int.
B] pf is a pointer to function which returns an int.
C] argv is a pointer to a char pointer.
D] f is an array of 10 function pointers, where each function receives two ints and returns nothing.
E] scr is a far pointer to a char. ( far pointer is a pointer which contains an address which lies outside the data segment).
F] arr is an array of 10 character pointers.
G] a is an array of 5 function pointers. Each of these functions receive a far pointer to an int and returns an int.
H] scr1 is a far pointer to a char, whereas scr2 is a near pointer to a char.
I] ftable is an array of 4 function pointers which point to the functions fadd(), fsub() etc. Each of these functions accept nothing and return an int.
J] ptr is a pointer to an array of 30 integers.
K] ptr is an array of 30 pointers ot integers.
L] cmp is a function returning pointer to void.
M] cmp is a pointer to function which returns a void.
N] f is a funciton returning pointer to array[] of pointer to function returning char.
O] x is an array of 3 pointers to functions returning pointer to an array of 5 chars.
P] f is a pointer to a funciton which returns nothing and receives as its parameter an integer and a pointer to a funciton which receives nothing and returns nothing.
Q] f is a pointer to a function which returns a pointer to an int pointer and receives two arguments: a pointer to an int pointer and a function pointer which points to a function which receives two pointers to int pointers an returns a pointer to an int pointer.
R] f is a pointer to a function which returns nothing and receives two arguments, both function pointers: the first function pointer points to a function which returns nothing but receives two arguments - an int pointer and a pointer to a void pointer; the second function pointer points to a function which returns an int pointer an receives a pointer to a void pointer and an int pointer.
S] ptr is a far pointer to a far pointer to a char, or in easier words, ptr contains a far address of a far pointer to a char.
T] ptr is a near pointer to a far pointer to a char, or in easier words, ptr contains a near address of a far pointer to a char.
U] ptr is a huge pointer to a far pointer to a char, or in easier words, ptr contains a huge address of a far pointer to a char.
2] 2 4 4
3] 2 4 4
4] 2 4 4
5] 4 4 2
6] 4 4 4
7] 2 2 2
8] 4 4 4
9] No.
10] char *ptr[3];
char *ptr[3];
char (*ptr)[3];
float *(*ptr)(int *);
void( *ptr)();
11] main()
{
void( *f)(int, void(*)());
void fun(int, void(*)());
void fun1();
void(*p)();
f = fun;
p = fun1;
(*f)(23,p);
}
void fun(int i, voud (*q)())
{
printf("Hello");
}
void fun1()
{
;
}
A. int *f();
B. int (*pf)();
C. char **argv;
D. void (*f[10])(int,int);
E. char far *scr;
F. char far *arr[10];
G. int (*a[5])(int far *p);
H. char far *scr1, *scr2;
I. int (*ftable[])(void) = {fadd,fsub,fmul,fdiv};
J. int (*ptr)[30];
K. int *ptr[30];
L. void *cmp();
M. void (*cmp)();
N. char (*(*f())[])();
O. char (*(*x[3])())[5];
P. void (*f)(int, void(*)());
Q. int **(*)(int **, int **(*)(int **, int **));
R. void(*)(void(*)(int *, void **), int(*)(void **, int *));
S. char far * far *ptr;
T. char far * near *ptr;
U. char far * huge *ptr;
2] What would be the output of the following program?
main()
{
char near * near *ptr1;
char near * far *ptr2;
char near * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
3] What would be the output of the following program?
main()
{
char far * near *ptr1;
char far * far *ptr2;
char far * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
4] What would be the output of the following program?
main()
{
char huge * near *ptr1;
char huge * far *ptr2;
char huge * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
5] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
6] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(*ptr2),sizeof(**ptr3));
}
7] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(*ptr1),sizeof(**ptr2),sizeof(ptr3));
}
8] What would be the output of the following program?
main()
{
char huge * near * far *ptr1;
char near * far * huge *ptr2;
char far * huge * near *ptr3;
printf("%d %d %d",sizeof(**ptr1),sizeof(ptr2),sizeof(*ptr3));
}
9] Are the following two declarations same? < Yes / No>
char far * far *scr;
char far far **scr;
10] How would you declare the following:
- An array of three pointers to chars.
- An array of three char pointers.
- A pointer to an array of three chars.
- A pointer to a function which receives an int pointer and returns a float pointer.
- A pointer to a function which receives nothing and returns nothing.
11] Can you write a program which would implement the follwoing declaration.
void (*f)(int, void (*)());
***********************************************************************
*********************** ANSWERS ***************************
***********************************************************************
1]
A] f is a funciton returning pointer to an int.
B] pf is a pointer to function which returns an int.
C] argv is a pointer to a char pointer.
D] f is an array of 10 function pointers, where each function receives two ints and returns nothing.
E] scr is a far pointer to a char. ( far pointer is a pointer which contains an address which lies outside the data segment).
F] arr is an array of 10 character pointers.
G] a is an array of 5 function pointers. Each of these functions receive a far pointer to an int and returns an int.
H] scr1 is a far pointer to a char, whereas scr2 is a near pointer to a char.
I] ftable is an array of 4 function pointers which point to the functions fadd(), fsub() etc. Each of these functions accept nothing and return an int.
J] ptr is a pointer to an array of 30 integers.
K] ptr is an array of 30 pointers ot integers.
L] cmp is a function returning pointer to void.
M] cmp is a pointer to function which returns a void.
N] f is a funciton returning pointer to array[] of pointer to function returning char.
O] x is an array of 3 pointers to functions returning pointer to an array of 5 chars.
P] f is a pointer to a funciton which returns nothing and receives as its parameter an integer and a pointer to a funciton which receives nothing and returns nothing.
Q] f is a pointer to a function which returns a pointer to an int pointer and receives two arguments: a pointer to an int pointer and a function pointer which points to a function which receives two pointers to int pointers an returns a pointer to an int pointer.
R] f is a pointer to a function which returns nothing and receives two arguments, both function pointers: the first function pointer points to a function which returns nothing but receives two arguments - an int pointer and a pointer to a void pointer; the second function pointer points to a function which returns an int pointer an receives a pointer to a void pointer and an int pointer.
S] ptr is a far pointer to a far pointer to a char, or in easier words, ptr contains a far address of a far pointer to a char.
T] ptr is a near pointer to a far pointer to a char, or in easier words, ptr contains a near address of a far pointer to a char.
U] ptr is a huge pointer to a far pointer to a char, or in easier words, ptr contains a huge address of a far pointer to a char.
2] 2 4 4
3] 2 4 4
4] 2 4 4
5] 4 4 2
6] 4 4 4
7] 2 2 2
8] 4 4 4
9] No.
10] char *ptr[3];
char *ptr[3];
char (*ptr)[3];
float *(*ptr)(int *);
void( *ptr)();
11] main()
{
void( *f)(int, void(*)());
void fun(int, void(*)());
void fun1();
void(*p)();
f = fun;
p = fun1;
(*f)(23,p);
}
void fun(int i, voud (*q)())
{
printf("Hello");
}
void fun1()
{
;
}
Command Line Argument
1] What do the 'c' and 'v' in 'argc' and 'argv' stand for?
2] According to ANSI specifications which is the correct way of decalrating main() when it receives command line arguments?
A] main(int argc, char *argv[])
B] main(argc,argv)
int argc; char *argv[];
C] main()
{
int argc; char *argv[];
}
D] None of the above.
3] What would be the output of the following program?
/* sample.c*/
main(int argc,char **argv)
{
argc = argc - (argc - 1);
printf("%s",argv[argc - 1]);
}
4] If different command line arguments are supplied at different times would the output of the following program change?
< Yes / No>
main(int argc, char *argv[])
{
printf("%d",argv[argc]);
}
5] If the following program (myprog) is run form the command line as myprog 1 2 3
What would be the output/
main(int argc, char *argv[])
{
int i;
for(i = 0; i < argc; i++) printf("%s",argv[i]); } 6] If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i; i = argv[1] + argv[2] + argv[3]; printf("%d",i); } A] 123 B] 6 C] Error. D] "123" 7] If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i,j = 0; for(i = o; i < argc; i++) j = j + atoi(argv[i]); printf("%d",j); } A] 123 B] 6 C] Error. D] "123" 8] Would the following program give the same output at all times? < Yes / No>
main(int argc, char*argv[])
{
strcpy(argv[0],"hello");
strcpy(argv[1],"good morning");
printf("%s %s",argv[0],argc[1]);
}
9] If the following program (myprog) is run from the command line as
myprog one two three
What would be the output?
main(int argc, char *argv[])
{
printf("%s",*++argv);
}
10] If the following program (myprog) is run from the command line as
myprog one two three
What would be the output?
main(int argc, char *argv[])
{
printf("%c",*++argv);
}
11] The variables 'argc' and 'argv' are always local to main.
12] The maximum combined length of the command line arguments including the spaces between adjacent arguments is
A] 128 characters.
B] 256 characters.
C] 67 hcaracters.
D] It may vary from one operating system to another.
13] What will the following program output?
main(int argc, char *argv[],char *env[])
{
int i;
for(i = 1; i < argc ; i++) printf("%s",env[i]); } A] List of all environment variables. B] List of all command line arguments. C] Error. D] NULL. 14] If the following program (myprog) is run from the command line as myprog "*.c" What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); } A] *.c B] List of all .c files in the current directory C] "*.c" D] None of the above 15] If the following program (myprog) is run from the command line as myprog *.c What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); } A] *.c B] List of all .c files in the current directory C] "*.c" D] None of the above 16] If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which? 17] Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function? < Yes / No>
18] If the following program (myprog) is run from the command line as
myprog Jan Feb Mar
What would be the output?
#include "dos.h"
main()
{
fun();
}
fun()
{
int i;
for(i = 0; i <_argc; i++) printf("%s",_argv[i]); } 19] If the following program (myprog) is present in the directory c:\bc\tucs then what would be its output? main(int argc, char *argv[]) { printf("%s",argv[0]); } A] MYPROG B] C:\BC\TUCS\MYPROG C] Error D] C:\BC\TUCS 20] Which is an easy way to extract myprog form the output of program 13.19 above? 21] Which of the following is true about argv? A] It is an array of character pointers. B] It is a pointer to an array of character pointers. C] It is an array of strings. D] None of the above. 22] If the following program (myprog) is run from the command line as myprog monday tuesday wednesday thursday What would be the output? main(int argc, char *argv[]) { while(--argc > 0)
printf("%s",*++argv);
}
A] myprog monday tuesday wednesday thursday
B] monday tuesday wednesday thursday
C] myprog tuesday thursday
D] None of the above.
23] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",(*++argv)[0]);
}
A] m
B] f
C] myprog
D] friday
24] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",**++argv);
}
A] m
B] f
C] myprog
D] friday
25] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",*++argv[1]);
}
A] r
B] f
C] m
D] y
26] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int sizeofargv, char *argv[])
{
while(sizeofargv)
printf("%s",argv[--sizeofargv]);
}
A] myprog friday tuesday sunday
B] myprog friday tuesday
C] sunday tuesday friday myprog
D] sunday tuesday friday
***********************************************************************
************************* ANSWERS *******************************
***********************************************************************
1] Count of arguments and vector(array) of arguments.
2] A
3] C:\SAMPLE.EXE
4] No
5] C:\MYPROG.EXE 1 2 3
6] C
7] B. When atoi() tries to convert argv[0] to a number it cannot do so (argv[0] being a file name) and hence returns a zero.
8] No
9] one
10] P
11] True
12] D
13] B
14] A
15] A
16] Yes. Compile the program as
tcc myprog wildargs.obj
This compiles the file myprog.c and links it withe the wildcard expansion module WILDCARGs.OBJ, then run the resulting executable file MYPROG.EXE.
If you want the wildcard expansion to be default so that you won't have to link your program explicitly with WILDCARGS.OBJ, you can midigy our standard C?.LIB library files to have WILDCARGS.OBJ linked automatically. To acheive htis we have to remove SET ARGV from the library and add WILDCRAGS. The commands will invoke the Turbo Librarian to modify all the standard library files (assuming the current directory contains the standard C libraries, and WILDCRAGS.OBJ):
tlib cs -setargv +wildargs
tlib cc -setragv +wildargs
tlib cm -strargv +wildargs
tlib cl -setargv +wildargs
tlib ch -setargv +wildargs
17] Yes. Using the predefined variables_arcg,_argv.
18] C:\MYPROG.EXE Jan Feb Mar
19] B
20] #include "dir.h"
main(int arc, char *argv[])
{
char drive[3],dir[50],name[8],ext[3];
printf("\n %s",argv[0]);
fnsplit(argv[0],drive,dir,name,ext);
printf("\n %s \n %s \n %s \n %s",drive,dir,name,ext);
}
21] A
22] B
23] B
24] B
25] A
26] C
2] According to ANSI specifications which is the correct way of decalrating main() when it receives command line arguments?
A] main(int argc, char *argv[])
B] main(argc,argv)
int argc; char *argv[];
C] main()
{
int argc; char *argv[];
}
D] None of the above.
3] What would be the output of the following program?
/* sample.c*/
main(int argc,char **argv)
{
argc = argc - (argc - 1);
printf("%s",argv[argc - 1]);
}
4] If different command line arguments are supplied at different times would the output of the following program change?
< Yes / No>
main(int argc, char *argv[])
{
printf("%d",argv[argc]);
}
5] If the following program (myprog) is run form the command line as myprog 1 2 3
What would be the output/
main(int argc, char *argv[])
{
int i;
for(i = 0; i < argc; i++) printf("%s",argv[i]); } 6] If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i; i = argv[1] + argv[2] + argv[3]; printf("%d",i); } A] 123 B] 6 C] Error. D] "123" 7] If the following program (myprog) is run form the command line as myprog 1 2 3 What would be the output? main(int argc,char *argv[]) { int i,j = 0; for(i = o; i < argc; i++) j = j + atoi(argv[i]); printf("%d",j); } A] 123 B] 6 C] Error. D] "123" 8] Would the following program give the same output at all times? < Yes / No>
main(int argc, char*argv[])
{
strcpy(argv[0],"hello");
strcpy(argv[1],"good morning");
printf("%s %s",argv[0],argc[1]);
}
9] If the following program (myprog) is run from the command line as
myprog one two three
What would be the output?
main(int argc, char *argv[])
{
printf("%s",*++argv);
}
10] If the following program (myprog) is run from the command line as
myprog one two three
What would be the output?
main(int argc, char *argv[])
{
printf("%c",*++argv);
}
11] The variables 'argc' and 'argv' are always local to main.
12] The maximum combined length of the command line arguments including the spaces between adjacent arguments is
A] 128 characters.
B] 256 characters.
C] 67 hcaracters.
D] It may vary from one operating system to another.
13] What will the following program output?
main(int argc, char *argv[],char *env[])
{
int i;
for(i = 1; i < argc ; i++) printf("%s",env[i]); } A] List of all environment variables. B] List of all command line arguments. C] Error. D] NULL. 14] If the following program (myprog) is run from the command line as myprog "*.c" What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); } A] *.c B] List of all .c files in the current directory C] "*.c" D] None of the above 15] If the following program (myprog) is run from the command line as myprog *.c What would be the output? main(int argc, char *argv[]) { int i; for(i = 1; i < argc; i++) printf("%s",argv[i]); } A] *.c B] List of all .c files in the current directory C] "*.c" D] None of the above 16] If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which? 17] Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function? < Yes / No>
18] If the following program (myprog) is run from the command line as
myprog Jan Feb Mar
What would be the output?
#include "dos.h"
main()
{
fun();
}
fun()
{
int i;
for(i = 0; i <_argc; i++) printf("%s",_argv[i]); } 19] If the following program (myprog) is present in the directory c:\bc\tucs then what would be its output? main(int argc, char *argv[]) { printf("%s",argv[0]); } A] MYPROG B] C:\BC\TUCS\MYPROG C] Error D] C:\BC\TUCS 20] Which is an easy way to extract myprog form the output of program 13.19 above? 21] Which of the following is true about argv? A] It is an array of character pointers. B] It is a pointer to an array of character pointers. C] It is an array of strings. D] None of the above. 22] If the following program (myprog) is run from the command line as myprog monday tuesday wednesday thursday What would be the output? main(int argc, char *argv[]) { while(--argc > 0)
printf("%s",*++argv);
}
A] myprog monday tuesday wednesday thursday
B] monday tuesday wednesday thursday
C] myprog tuesday thursday
D] None of the above.
23] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",(*++argv)[0]);
}
A] m
B] f
C] myprog
D] friday
24] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",**++argv);
}
A] m
B] f
C] myprog
D] friday
25] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int argc, char *argv[])
{
printf("%c",*++argv[1]);
}
A] r
B] f
C] m
D] y
26] If the following program (myprog) is run form the command line as
myprog friday tuesday sunday
What will be the output?
main(int sizeofargv, char *argv[])
{
while(sizeofargv)
printf("%s",argv[--sizeofargv]);
}
A] myprog friday tuesday sunday
B] myprog friday tuesday
C] sunday tuesday friday myprog
D] sunday tuesday friday
***********************************************************************
************************* ANSWERS *******************************
***********************************************************************
1] Count of arguments and vector(array) of arguments.
2] A
3] C:\SAMPLE.EXE
4] No
5] C:\MYPROG.EXE 1 2 3
6] C
7] B. When atoi() tries to convert argv[0] to a number it cannot do so (argv[0] being a file name) and hence returns a zero.
8] No
9] one
10] P
11] True
12] D
13] B
14] A
15] A
16] Yes. Compile the program as
tcc myprog wildargs.obj
This compiles the file myprog.c and links it withe the wildcard expansion module WILDCARGs.OBJ, then run the resulting executable file MYPROG.EXE.
If you want the wildcard expansion to be default so that you won't have to link your program explicitly with WILDCARGS.OBJ, you can midigy our standard C?.LIB library files to have WILDCARGS.OBJ linked automatically. To acheive htis we have to remove SET ARGV from the library and add WILDCRAGS. The commands will invoke the Turbo Librarian to modify all the standard library files (assuming the current directory contains the standard C libraries, and WILDCRAGS.OBJ):
tlib cs -setargv +wildargs
tlib cc -setragv +wildargs
tlib cm -strargv +wildargs
tlib cl -setargv +wildargs
tlib ch -setargv +wildargs
17] Yes. Using the predefined variables_arcg,_argv.
18] C:\MYPROG.EXE Jan Feb Mar
19] B
20] #include "dir.h"
main(int arc, char *argv[])
{
char drive[3],dir[50],name[8],ext[3];
printf("\n %s",argv[0]);
fnsplit(argv[0],drive,dir,name,ext);
printf("\n %s \n %s \n %s \n %s",drive,dir,name,ext);
}
21] A
22] B
23] B
24] B
25] A
26] C
+++++++++++++BIT wise OPERATOR------------------------------
1] What would be the output of the following program?
main()
{
int i = 32,j = 0x20,k,l,m;
k = j | j;
l = i & j;
m = k ^ l;
printf("%d %d %d %d %d",i,j,k,l,m);
}
A] 32 32 32 32 0
B] 0 0 0 0 0
C] 0 32 32 32 32
D] 32 32 32 32 32
2] What would be the output of the following program?//65535
main()
{
unsigned int m = 32;
printf("%x",~m);
}
A] ffff
B] 0000
C] ffdf
D] ddfd
3] What would be the output of the following program?
main()
{
unsigned int a = 0xffff;
~a;
printf("%x",a);
}
A] ffff
B] 0000
C] 00ff
D] None of the above.
4] Point out the error in the following program.
main()
{
unsigned int a,b,c,d,e,f;
a = b = c = d = e = f = 32;
a <<= 2; b >>= 2;
c ^= 2;
d |= 2;
e &= 2;
f ~= 2;
printf("\n %x %x %x %x %x %x",a,b,c,d,e,f);
}
5] To which numbering system can the binary number 1011011111000101 be easily converted to?
6] Which bitwise operator is suitable for checking whether a particular bit is 'on' or 'off'?
7] Which bitwise operator is suitable for turning of a particular bit in a number?
8] Which bitwise operator is suitable for putting on a particular bit in a number?
9] On left shifting, the bits from the left are rotated an brought to the right and accommodated where there is empty space on the right? < True / False >
10] Left shifthing a number by 1 is always equibalent to multiplying it by 2. < Yes / No >
11] Left shifting an unsigned int or char by 1 is always equivalent to multiplying it by 2. < Yes / No >
12] What would be the output of the following program?
main()
{
unsigned char i = 0x80;
printf("\n %d",i << 1); } A] 0 B] 256 C] 100 D] None of the above. 13] What is the following program doing? main() { unsigned int m[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; unsinged char n,i; scanf("%d",&n); for(i = 0; i <= 7; i++) { if (n & m[i]) printf("\n yes"); } } 14] What does the follwing program do? main() { char *s; s = fun(128,2); printf("\n %s",s) } fun(unsigned int num,int base) { static char buff[33]; char *ptr; ptr = &buff[ sizeof(buff) - 1]; *ptr = '\0'; do { *--ptr = "0123456789abcdef"[num % base]; num /= base; }while (num != 0); return ptr; } A] It converts a number to given base. B] It gives a compilation error. C] None of the above. 15] #define CHARSIZE 8 #define MASK(y) ( 1 << % CHARSIZE) #define BITSLOT(y) (y / CHARSIZE) #define SET(x,y) (x[BITSLOT(y) |= MASK(y)) #define TEST(x,y) (x[BITSLOT(y)] & MASK(y)) #define NUMSLOTS(n) ((n + CHARSIZE - 1) / CHARSIZE) Given the above macros how would you (a) declare an array arr of 50 bits. (b) put the 20th bit on. (c) test whether the 40th bit is 'on' or 'off'. 16] Consider the macros in problem 14.15 above. On similar lines can you define a macro which would clear a given bit in a bit array? 17] What does the following progaram do? main() { unsigned int num; int c = 0; scanf("%u",&num); for( ; num; num>>= 1)
{
if(num & 1)
c++;
}
printf("%d",c);
}
A] It counts the number of bits which are on in the number num.
B] It sets all bits in the number num to 1.
C] It sets all bits in the number num to 0.
D] None of the above.
18] What would be the output of the following program?
main()
{
printf("\n %x", -1 >> 4);
}
A] ffff
B] 0fff
C] 0000
D] fff0
19] In the statement expression1 >> expression2 if expressin1 is a signed integer with its leftmost bit set to 1 then on right-shifting it the result of the statement would vary from computer to computer. < True / False >
20] What does the following program do?
main()
{
unsigned int num;
int i;
scanf("%u",&num);
for( i = 0; i < 16; i++)
printf("%d",(num << 1 & 1 << 15)? 1: 0);
}
A] It prints all even bits from num.
B] It prints all odd bits from num.
C] It prints binary equivalent fo num.
D] None of the above.
***********************************************************************
****************** ANSWERS ******************
***********************************************************************
1] A
2] C
3] A
4] Error is in f~= 2, since there is no operator as '~='.
5] Hexadecimal, since each 4-digit binary represents one hexadecimal digit.
6] The '&' operator.
7] The '|' operator.
8] False.
10] No.
11] Yes.
12] B
13] B
14] A
15] char arr[NUMSLOTS(50)];
SET(arr,20);
if (TEST(arr,40))
16] #define CLEAR(x,y) (x[BITSLOT(y)] &= ~MASK(y))
17] A
18] A. On computers which don't support sign extension you may get B.
19] True.
20] C
main()
{
int i = 32,j = 0x20,k,l,m;
k = j | j;
l = i & j;
m = k ^ l;
printf("%d %d %d %d %d",i,j,k,l,m);
}
A] 32 32 32 32 0
B] 0 0 0 0 0
C] 0 32 32 32 32
D] 32 32 32 32 32
2] What would be the output of the following program?//65535
main()
{
unsigned int m = 32;
printf("%x",~m);
}
A] ffff
B] 0000
C] ffdf
D] ddfd
3] What would be the output of the following program?
main()
{
unsigned int a = 0xffff;
~a;
printf("%x",a);
}
A] ffff
B] 0000
C] 00ff
D] None of the above.
4] Point out the error in the following program.
main()
{
unsigned int a,b,c,d,e,f;
a = b = c = d = e = f = 32;
a <<= 2; b >>= 2;
c ^= 2;
d |= 2;
e &= 2;
f ~= 2;
printf("\n %x %x %x %x %x %x",a,b,c,d,e,f);
}
5] To which numbering system can the binary number 1011011111000101 be easily converted to?
6] Which bitwise operator is suitable for checking whether a particular bit is 'on' or 'off'?
7] Which bitwise operator is suitable for turning of a particular bit in a number?
8] Which bitwise operator is suitable for putting on a particular bit in a number?
9] On left shifting, the bits from the left are rotated an brought to the right and accommodated where there is empty space on the right? < True / False >
10] Left shifthing a number by 1 is always equibalent to multiplying it by 2. < Yes / No >
11] Left shifting an unsigned int or char by 1 is always equivalent to multiplying it by 2. < Yes / No >
12] What would be the output of the following program?
main()
{
unsigned char i = 0x80;
printf("\n %d",i << 1); } A] 0 B] 256 C] 100 D] None of the above. 13] What is the following program doing? main() { unsigned int m[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; unsinged char n,i; scanf("%d",&n); for(i = 0; i <= 7; i++) { if (n & m[i]) printf("\n yes"); } } 14] What does the follwing program do? main() { char *s; s = fun(128,2); printf("\n %s",s) } fun(unsigned int num,int base) { static char buff[33]; char *ptr; ptr = &buff[ sizeof(buff) - 1]; *ptr = '\0'; do { *--ptr = "0123456789abcdef"[num % base]; num /= base; }while (num != 0); return ptr; } A] It converts a number to given base. B] It gives a compilation error. C] None of the above. 15] #define CHARSIZE 8 #define MASK(y) ( 1 << % CHARSIZE) #define BITSLOT(y) (y / CHARSIZE) #define SET(x,y) (x[BITSLOT(y) |= MASK(y)) #define TEST(x,y) (x[BITSLOT(y)] & MASK(y)) #define NUMSLOTS(n) ((n + CHARSIZE - 1) / CHARSIZE) Given the above macros how would you (a) declare an array arr of 50 bits. (b) put the 20th bit on. (c) test whether the 40th bit is 'on' or 'off'. 16] Consider the macros in problem 14.15 above. On similar lines can you define a macro which would clear a given bit in a bit array? 17] What does the following progaram do? main() { unsigned int num; int c = 0; scanf("%u",&num); for( ; num; num>>= 1)
{
if(num & 1)
c++;
}
printf("%d",c);
}
A] It counts the number of bits which are on in the number num.
B] It sets all bits in the number num to 1.
C] It sets all bits in the number num to 0.
D] None of the above.
18] What would be the output of the following program?
main()
{
printf("\n %x", -1 >> 4);
}
A] ffff
B] 0fff
C] 0000
D] fff0
19] In the statement expression1 >> expression2 if expressin1 is a signed integer with its leftmost bit set to 1 then on right-shifting it the result of the statement would vary from computer to computer. < True / False >
20] What does the following program do?
main()
{
unsigned int num;
int i;
scanf("%u",&num);
for( i = 0; i < 16; i++)
printf("%d",(num << 1 & 1 << 15)? 1: 0);
}
A] It prints all even bits from num.
B] It prints all odd bits from num.
C] It prints binary equivalent fo num.
D] None of the above.
***********************************************************************
****************** ANSWERS ******************
***********************************************************************
1] A
2] C
3] A
4] Error is in f~= 2, since there is no operator as '~='.
5] Hexadecimal, since each 4-digit binary represents one hexadecimal digit.
6] The '&' operator.
7] The '|' operator.
8] False.
10] No.
11] Yes.
12] B
13] B
14] A
15] char arr[NUMSLOTS(50)];
SET(arr,20);
if (TEST(arr,40))
16] #define CLEAR(x,y) (x[BITSLOT(y)] &= ~MASK(y))
17] A
18] A. On computers which don't support sign extension you may get B.
19] True.
20] C
**********Array****************
***********************************************************************
*********************** ARRAYS ******************************
***********************************************************************
1] What would the output of the following program?
main()
{
char a[] = "Visual C++";
char *b = "Visual C++";
printf("\n %d %d",sizeof(a),sizeof(b));
printf("\n %d %d",sizeof(*a),sizeof(*b));
}
2] For the following statements would arr[3] and ptr[3] fetch the same character?
char arr[] = "Surprised";
char *ptr = "surprised";
3] For the statements in 9.2 does the compiler fetch the character arr[3] and ptr[3] in the same manner?
4] What would be the output of the following program, if the array begins at address 1200?
main()
{
int arr[] = {2,3,4,1,6};
printf("%d %d",arr, sizeof(arr));
}
5] Does mentioning the array name gives the base address in all the contexts?
6] What would be the output of the following prograam, if the aray begins at address 65486 ?
main()
{
int arr[] = {12,14,15,23,45};
printf("%u %u",arr, &arr);
}
7] Are the expressions arr and &arr same for an array of 10 integers ?
8] What would be the output of the following prograam, if the aray begins at address 65486 ?
main()
{
int arr[] = {12,14,15,23,45};
printf("%u %u",arr + 1, &arr + 1);
}
9] When are 'char a[]' and 'char *a' treated as same by the compiler ?
10] Would the following program compile successfully ?
main()
{
char a[] = "Sunstroke";
char *p = "Coldwave";
a = "Coldwave";
b = "Sunstroke";
printf("\n %s %s",a,p);
}
11] What would be the output of the following program ?
main()
{
float a[] = {12.4,2.3,4.5,6.7};
printf("\n %d",sizeof(a) / sizeof(a[0]));
}
12] A pointer to a block of memory is effectively same as an array.
13] What would be the output of the following program if the array begins at 65472?
main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,1,
7,8,9,0
};
printf("\n %u %u",a + 1, &a + 1);
}
14] What does the follwoing declaration mean:
int(*ptr)[10];
15] If we pass the name of a 1-D int array to a function it decays into a pointer to an int. If we pass the name of a 2-D array of integers to a function what would it decay into ?
16] How would you define the function f() in the following program?
int arr[MAXROW][MAXCOL];
fun(arr);
17] What would be the output of the following program ?
main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,8,
7,8,9,0
};
int *ptr;
ptr = &a[0][0];
fun(&ptr);
}
fun(int **p)
{
printf("\n %d",**p);
}
***********************************************************************
************************* ANSWERS ****************************
***********************************************************************
1] 11 2
1 1
2] Yes
3] No. For arr[3] the compiler generates code to start at location arr, move past it, and fetch the character there. When it sees the expression ptr[3] it generates the code to start at location stored in ptr, add three to the pointer, and finally fetch the character pointed to.
In other words, arr[3] is three places past the start of the object named arr, whereas ptr[3] is three places past the object pointed to by ptr.
4] 1200 10
5] No. Whenever mentioning the array name gives its base address it is said that the array has decayed into a pointer. This decaying doesn't take place in two situations:
--- When array name is used with sizeof operator.
--- When the array name is an operand of the & operator.
6] 65486 65486
7] No. Even though both may give the same addresses as in (6) they mean two different things. 'arr' gives the address of the first 'int' whereas '&arr' gives the address of array of 'ints'. Since these addresses happen to be same the results of the expressions are same.
8] 65488 65496
9] When using them as formal parameters while defining a function.
10] No, because we may assign a new string ot a pointer but not to an array.
11] 4
12] True
13] 65480 65496
14] 'ptr' is a pointer to an array of 10 integers.
15] It decays into a pointer to an array and not a pointer to a pointer.
16] fun(int a[][MAXCOL])
{
}
OR
fun(int (*ptr)[MAXCOL]) /* ptr is pointer to an array */
{
}
17] 1
*********************** ARRAYS ******************************
***********************************************************************
1] What would the output of the following program?
main()
{
char a[] = "Visual C++";
char *b = "Visual C++";
printf("\n %d %d",sizeof(a),sizeof(b));
printf("\n %d %d",sizeof(*a),sizeof(*b));
}
2] For the following statements would arr[3] and ptr[3] fetch the same character?
char arr[] = "Surprised";
char *ptr = "surprised";
3] For the statements in 9.2 does the compiler fetch the character arr[3] and ptr[3] in the same manner?
4] What would be the output of the following program, if the array begins at address 1200?
main()
{
int arr[] = {2,3,4,1,6};
printf("%d %d",arr, sizeof(arr));
}
5] Does mentioning the array name gives the base address in all the contexts?
6] What would be the output of the following prograam, if the aray begins at address 65486 ?
main()
{
int arr[] = {12,14,15,23,45};
printf("%u %u",arr, &arr);
}
7] Are the expressions arr and &arr same for an array of 10 integers ?
8] What would be the output of the following prograam, if the aray begins at address 65486 ?
main()
{
int arr[] = {12,14,15,23,45};
printf("%u %u",arr + 1, &arr + 1);
}
9] When are 'char a[]' and 'char *a' treated as same by the compiler ?
10] Would the following program compile successfully ?
main()
{
char a[] = "Sunstroke";
char *p = "Coldwave";
a = "Coldwave";
b = "Sunstroke";
printf("\n %s %s",a,p);
}
11] What would be the output of the following program ?
main()
{
float a[] = {12.4,2.3,4.5,6.7};
printf("\n %d",sizeof(a) / sizeof(a[0]));
}
12] A pointer to a block of memory is effectively same as an array.
13] What would be the output of the following program if the array begins at 65472?
main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,1,
7,8,9,0
};
printf("\n %u %u",a + 1, &a + 1);
}
14] What does the follwoing declaration mean:
int(*ptr)[10];
15] If we pass the name of a 1-D int array to a function it decays into a pointer to an int. If we pass the name of a 2-D array of integers to a function what would it decay into ?
16] How would you define the function f() in the following program?
int arr[MAXROW][MAXCOL];
fun(arr);
17] What would be the output of the following program ?
main()
{
int a[3][4] = {
1,2,3,4,
4,3,2,8,
7,8,9,0
};
int *ptr;
ptr = &a[0][0];
fun(&ptr);
}
fun(int **p)
{
printf("\n %d",**p);
}
***********************************************************************
************************* ANSWERS ****************************
***********************************************************************
1] 11 2
1 1
2] Yes
3] No. For arr[3] the compiler generates code to start at location arr, move past it, and fetch the character there. When it sees the expression ptr[3] it generates the code to start at location stored in ptr, add three to the pointer, and finally fetch the character pointed to.
In other words, arr[3] is three places past the start of the object named arr, whereas ptr[3] is three places past the object pointed to by ptr.
4] 1200 10
5] No. Whenever mentioning the array name gives its base address it is said that the array has decayed into a pointer. This decaying doesn't take place in two situations:
--- When array name is used with sizeof operator.
--- When the array name is an operand of the & operator.
6] 65486 65486
7] No. Even though both may give the same addresses as in (6) they mean two different things. 'arr' gives the address of the first 'int' whereas '&arr' gives the address of array of 'ints'. Since these addresses happen to be same the results of the expressions are same.
8] 65488 65496
9] When using them as formal parameters while defining a function.
10] No, because we may assign a new string ot a pointer but not to an array.
11] 4
12] True
13] 65480 65496
14] 'ptr' is a pointer to an array of 10 integers.
15] It decays into a pointer to an array and not a pointer to a pointer.
16] fun(int a[][MAXCOL])
{
}
OR
fun(int (*ptr)[MAXCOL]) /* ptr is pointer to an array */
{
}
17] 1
When u are in Interview............
The following are some of the most difficult questions you will face in the course of your job interviews. Some questions may seem rather simple on the surface--such as "Tell me about yourself"--but these questions can have a variety of answers. The more open-ended the question, the wider the variation in the answers. Once you have become practiced in your interviewing skills, you will find that you can use almost any question as a launching pad for a particular topic or compelling story.
1. Tell me about yourself.
My background to date has been centered around preparing myself to become the very best _____ I can become. Let me tell you specifically how I've prepared myself . . .
2. Why should I hire you?
Because I sincerely believe that I'm the best person for the job. I realize that there are many other college students who have the ability to do this job. I also have that ability. But I also bring an additional quality that makes me the very best person for the job--my attitude for excellence. Not just giving lip service to excellence, but putting every part of myself into achieving it. In _____ and _____ I have consistently reached for becoming the very best I can become by doing the following . . .
3. What is your long-range objective? Where do you want to be 10 or 15 years from now?
Although it's certainly difficult to predict things far into the future, I know what direction I want to develop toward. Within five years, I would like to become the very best _____ your company has. In fact, my personal career mission statement is to become a world-class _____ in the _____ industry. I will work toward becoming the expert that others rely upon. And in doing so, I feel I will be fully prepared to take on any greater responsibilities that might be presented in the long term.
4. How has your education prepared you for your career?
As you will note on my résumé, I've taken not only the required core classes in the _____ field, I've also gone above and beyond. I've taken every class the college has to offer in the field and also completed an independent study project specifically in this area. But it's not just taking the classes to gain academic knowledge--I've taken each class, both inside and outside of my major, with this profession in mind. So when we're studying _____ in _____, I've viewed it from the perspective of _____. In addition, I've always tried to keep a practical view of how the information would apply to my job. Not just theory, but how it would actually apply. My capstone course project in my final semester involved developing a real-world model of _____, which is very similar to what might be used within your company. Let me tell you more about it . . .
5. Are you a team player?
Very much so. In fact, I've had opportunities in both athletics and academics to develop my skills as a team player. I was involved in _____ at the intramural level, including leading my team in assists during the past year--I always try to help others achieve their best. In academics, I've worked on several team projects, serving as both a member and team leader. I've seen the value of working together as a team to achieve a greater goal than any one of us could have achieved individually. As an example . . .
6. Have you ever had a conflict with a boss or professor? How was it resolved?
Yes, I have had conflicts in the past. Never major ones, but certainly there have been situations where there was a disagreement that needed to be resolved. I've found that when conflict occurs, it's because of a failure to see both sides of the situation. Therefore, I ask the other person to give me their perspective and at the same time ask that they allow me to fully explain my perspective. At that point, I would work with the person to find out if a compromise could be reached. If not, I would submit to their decision because they are my superior. In the end, you have to be willing to submit yourself to the directives of your superior, whether you're in full agreement or not. An example of this was when . . .
7. What is your greatest weakness?
I would say my greatest weakness has been my lack of proper planning in the past. I would overcommit myself with too many variant tasks, then not be able to fully accomplish each as I would like. However, since I've come to recognize that weakness, I've taken steps to correct it. For example, I now carry a planning calendar in my pocket so that I can plan all of my appointments and "to do" items. Here, let me show you how I have this week planned out . . .
8. If I were to ask your professors to describe you, what would they say?
I believe they would say I'm a very energetic person, that I put my mind to the task at hand and see to it that it's accomplished. They would say that if they ever had something that needed to be done, I was the person who they could always depend on to see that it was accomplished. They would say that I always took a keen interest in the subjects I was studying and always sought ways to apply the knowledge in real world settings. Am I just guessing that they would say these things? No, in fact, I'm quite certain they would say those things because I have with me several letters of recommendation from my professors and those are their very words. Let me show you . . .
9. What qualities do you feel a successful manager should have?
The key quality should be leadership--the ability to be the visionary for the people who are working under them. The person who can set the course and direction for subordinates. A manager should also be a positive role model for others to follow. The highest calling of a true leader is inspiring others to reach the highest of their abilities. I'd like to tell you about a person who I consider to be a true leader . . .
10. If you had to live your life over again, what would you change?
That's a good question. I realize that it can be very easy to continually look back and wish that things had been different in the past. But I also realize that things in the past cannot be changed, that only things in the future can be changed. That's why I continually strive to improve myself each and every day and that's why I'm working hard to continually increase my knowledge in the _____ field. That's also the reason why I want to become the very best _____ your company has ever had. To make positive change. And all of that is still in the future. So in answer to your question, there isn't anything in my past that I would change. I look only to the future to make changes in my life.
Important:
• Do not reproduce the answers verbatim.
• Do not repeat the same answer in each and every company, as this might put you in a tight situation. Research the company well before attending the interview.
• If possible, try to know the area in which you are expected to work and model your answers accordingly.
• Give a small pause before you start answering a question and also in between your answers. This conveys a fact to the interviewers that you are thinking before answering, and not just blurting out the mugged up answers.
If this work of mine has really helped you in any way or if you think this is a very useful reference tool, please send me an e-mail. I will be looking forward for all those gratitude mails. BYE.
CHEERS!!!!!!!!
1. Tell me about yourself.
My background to date has been centered around preparing myself to become the very best _____ I can become. Let me tell you specifically how I've prepared myself . . .
2. Why should I hire you?
Because I sincerely believe that I'm the best person for the job. I realize that there are many other college students who have the ability to do this job. I also have that ability. But I also bring an additional quality that makes me the very best person for the job--my attitude for excellence. Not just giving lip service to excellence, but putting every part of myself into achieving it. In _____ and _____ I have consistently reached for becoming the very best I can become by doing the following . . .
3. What is your long-range objective? Where do you want to be 10 or 15 years from now?
Although it's certainly difficult to predict things far into the future, I know what direction I want to develop toward. Within five years, I would like to become the very best _____ your company has. In fact, my personal career mission statement is to become a world-class _____ in the _____ industry. I will work toward becoming the expert that others rely upon. And in doing so, I feel I will be fully prepared to take on any greater responsibilities that might be presented in the long term.
4. How has your education prepared you for your career?
As you will note on my résumé, I've taken not only the required core classes in the _____ field, I've also gone above and beyond. I've taken every class the college has to offer in the field and also completed an independent study project specifically in this area. But it's not just taking the classes to gain academic knowledge--I've taken each class, both inside and outside of my major, with this profession in mind. So when we're studying _____ in _____, I've viewed it from the perspective of _____. In addition, I've always tried to keep a practical view of how the information would apply to my job. Not just theory, but how it would actually apply. My capstone course project in my final semester involved developing a real-world model of _____, which is very similar to what might be used within your company. Let me tell you more about it . . .
5. Are you a team player?
Very much so. In fact, I've had opportunities in both athletics and academics to develop my skills as a team player. I was involved in _____ at the intramural level, including leading my team in assists during the past year--I always try to help others achieve their best. In academics, I've worked on several team projects, serving as both a member and team leader. I've seen the value of working together as a team to achieve a greater goal than any one of us could have achieved individually. As an example . . .
6. Have you ever had a conflict with a boss or professor? How was it resolved?
Yes, I have had conflicts in the past. Never major ones, but certainly there have been situations where there was a disagreement that needed to be resolved. I've found that when conflict occurs, it's because of a failure to see both sides of the situation. Therefore, I ask the other person to give me their perspective and at the same time ask that they allow me to fully explain my perspective. At that point, I would work with the person to find out if a compromise could be reached. If not, I would submit to their decision because they are my superior. In the end, you have to be willing to submit yourself to the directives of your superior, whether you're in full agreement or not. An example of this was when . . .
7. What is your greatest weakness?
I would say my greatest weakness has been my lack of proper planning in the past. I would overcommit myself with too many variant tasks, then not be able to fully accomplish each as I would like. However, since I've come to recognize that weakness, I've taken steps to correct it. For example, I now carry a planning calendar in my pocket so that I can plan all of my appointments and "to do" items. Here, let me show you how I have this week planned out . . .
8. If I were to ask your professors to describe you, what would they say?
I believe they would say I'm a very energetic person, that I put my mind to the task at hand and see to it that it's accomplished. They would say that if they ever had something that needed to be done, I was the person who they could always depend on to see that it was accomplished. They would say that I always took a keen interest in the subjects I was studying and always sought ways to apply the knowledge in real world settings. Am I just guessing that they would say these things? No, in fact, I'm quite certain they would say those things because I have with me several letters of recommendation from my professors and those are their very words. Let me show you . . .
9. What qualities do you feel a successful manager should have?
The key quality should be leadership--the ability to be the visionary for the people who are working under them. The person who can set the course and direction for subordinates. A manager should also be a positive role model for others to follow. The highest calling of a true leader is inspiring others to reach the highest of their abilities. I'd like to tell you about a person who I consider to be a true leader . . .
10. If you had to live your life over again, what would you change?
That's a good question. I realize that it can be very easy to continually look back and wish that things had been different in the past. But I also realize that things in the past cannot be changed, that only things in the future can be changed. That's why I continually strive to improve myself each and every day and that's why I'm working hard to continually increase my knowledge in the _____ field. That's also the reason why I want to become the very best _____ your company has ever had. To make positive change. And all of that is still in the future. So in answer to your question, there isn't anything in my past that I would change. I look only to the future to make changes in my life.
Important:
• Do not reproduce the answers verbatim.
• Do not repeat the same answer in each and every company, as this might put you in a tight situation. Research the company well before attending the interview.
• If possible, try to know the area in which you are expected to work and model your answers accordingly.
• Give a small pause before you start answering a question and also in between your answers. This conveys a fact to the interviewers that you are thinking before answering, and not just blurting out the mugged up answers.
If this work of mine has really helped you in any way or if you think this is a very useful reference tool, please send me an e-mail. I will be looking forward for all those gratitude mails. BYE.
CHEERS!!!!!!!!
Sunday, March 27, 2011
Wednesday, January 12, 2011
Subscribe to:
Posts (Atom)