Showing posts with label C Programming. Show all posts
Showing posts with label C Programming. Show all posts

Sunday, March 29, 2009

C Programs with Solution Logic

  • Transpose of a Matrix
Interchanging the Rows with Columns or Vice-Verse
for(i=0;i&k;i++)
for(j=i+1;j&l;j++)
{
temp=mat[i][j];
mat[i][j]=mat[j][i];
mat[j][i]=temp;
}
  • Finding the Saddle point of a Matrix
A matrix a is said to have a saddle point if some entry a[I][j] is the smallest value in the ith row and the largest value in the jth column. A matrix may have more than one saddle point.

for Eg:
7 6 5
1 8 1
2 9 2

Here saddle Point value is 5.

  • How to find year is leap year.
if a year is divisible by 4 and not by 100 is called leap year.
if a year is divisible by 400 is called leap year.

  • How to swap two variables without using temporary variable?
a^=b^=a^=b

How to know system is using little Endian or Big Endain?
int i=1;
if( * (char *)&i == 1)
printf("Little Endian");
else
printf("Big Endian");

Friday, March 20, 2009

Preprocessing in C

C's preprocessor provides a facility for defining constant and substitution, which are commonly called macros.
  • #include
The include directive tells the compiler to include all the contents of a specified file in the source file before giving the source file for compiling.

eg: #define TRUE 1
  • #undef
Nullify the effect of define directive.
eg: #undef TRUE
#define TRUE correct

#include
Angle brackets Searches in the default directories of include files.

Quotes specifies search in current directory.
  • #ifdef
ifdef is used to make a substitution depending on whether a certain identifier is defined. If defined returns true else false.

e.g: #ifdef TRUE
#define FALSE 0
#endif
Note: we can easily add multiple macros in between the two macros.
  • #ifndef
eg: #ifndef FALSE
#define WRONG 0
  • #if
#if allows you to define more generalized conditions. Multiple conditions, which are connected by relational operators such as AND(&&), OR(||), are allowed.
  • #error
Used to display error message by preprocessor.

#if !define FALSE
#error "Specify FALSE condition"
  • #line
Mainly used for debugging purpose.
eg: #line100 indicates it is in line 100

C has provided two special identifiers: __FILE__ and __LINE__, which indicate the file name of the source file and the current line number, respectively.

Macros allow replacement of the identifier by using a statement or expression.
eg: #define CUBE(x) x*x*x

Placeholders for Scanf

THE scanf PLACEHOLDERS

The scanf placeholder consists of % at the beginning and a type indicator at the end. Apart from that it can have *, a maximum field-width indicator, and a type indicator modifier, for example,

%10.2f,%10d
  • d, i Used for signed integers; the expected argument should be a pointer to int.

  • o Used for unsigned int expected's value. It should be an integer in octal form.

  • U Unsigned integer in decimal form.

  • X, Unsigned integer in hexadecimal form.

  • E, f, g, G Floating-point values.

  • S Character string. It matches a sequence of non-whitespace characters terminated by an end-of-line or end-of-file character. The additional argument should be a pointer to char and should point to an area that is large enough to hold the input string as well as the NULL terminator.

  • C Matches the number of characters according to a specified field-width. If no width is specified then a single character is assumed. The additional argument must be a pointer to char; the area pointed to should be large enough to hold the specified number of characters.

  • N Does not read any input but writes the number of characters so far in the target variable.

The * is used to suppress input. For example, with %*d, if your input consists of 5 values and you want to ignore the middle 3 values, you can write:

scanf(" %d %*d %*d%*d %d ", &i, &j)

So, if your input is

10 20 30 40 50

it will get the value 10 and j will get the value 50. This is useful when you are getting the input from a file.

Field-width

It indicates the maximum number of characters that are read into the variables.

Explanation

  1. scanf requires two inputs: the first is a string argument and the second is a set of additional arguments.

  2. You can define how the input is to be taken by using placeholders.

Thursday, March 19, 2009

PlaceHolders for printf

Placeholders are used to print values of arguments supplied in print. The directives in the placeholders control printing.

Program/Example

The general form of a placeholder is:

  • % flags field-width precision prefix type-identifier.

Type-identifiers

The type-identifiers are as follows:

  • d, i Signed integers

  • o Unsigned integers displayed in octal form.

  • u Unsigned integers in decimal form.

  • x Unsigned integers in hexadecimal form, and the hexadecimal characters a, b, c, d, e, and f printed in lowercase.

  • X Unsigned integer in hexadecimal form, and the hexadecimal characters A, B, C, D, E, and F printed in uppercase.

  • c Any value converted to unsigned char and displayed; c is used mainly for printing characters.

  • s The argument is converted to a character array and is printed; the last null in the string is not printed.

  • f Floating point.

  • e, E Floating point displayed in exponential form. It will have one digit to the left of the decimal point; the number of digits on the right side of the decimal point depends on the required precision.

  • g, G The value can be printed in floating point or exponential form. The exponential form is used if the exponent is less than –1 or if the exponent causes more places than required by the specified precision; the decimal point appears only if it is followed by a digit.

  • n This indicates to print the number of characters that are printed so far by printf.

  • p It indicates an additional argument pointer to void; the value of the pointer is converted to a sequence of characters.

Type prefixes

  • h It can appear before type indicators d, i, o, u, x, and X. It indicates that the value to be displayed should be interpreted as short; for example, short integer (hd) and short unsigned integer (hu).

  • l It can appear before type-identifiers d, i, o, u, x, and X. It indicates that the value to be displayed should be interpreted as long; for example, long integer (hd) and long unsigned integer (hu).

  • l, L Available for type-identifiers e, E, f, g, and G. It indicates that a value should be indicated as long double.

Field-width

  1. Field-width indicates the least number of columns that will be allocated to the output. For example, if you write %4d to i and the value of i is 10, then 4 columns are allocated for i and 2 blank are added on left side of value of i. So the output is bb10. Here, b indicates blank.

  2. If the value is more than the specified column, field-width is ignored and the number of columns used is equal to the number of columns required by the arguments. So if i is 12345 then 5 columns are used, even if %4d is specified.

  3. In any circumstance, the output width is not shortened, because of field-width.

  4. If you specify * instead of field-width then you have to specify additional arguments. For example,

    printf ("%*d\n", 5, 20);     // A
    printf ("%*d\n", 20, 5); // B

    In A, 5 is substituted for * and it indicates putting the value 20 in 5 columns.

    In B, 20 is substituted for * and it indicates putting the value 5 in 20 columns.

Precision

  1. Precision indicates the minimum number of digits printed for type integers d, i, o, u, x, and X. For example,

    i.    printf("%10.4d\n", 35)
  2. Here 10 is the field-width and 4 is the precision, so 10 columns are used for the 4-digit output. To make 35 into 4 digits, two 0s are added to the left side to make it 0035. To print 0035 in 10 columns, blanks are added to make the output bbbbbb0035.

  3. For floating arguments, precision indicates how many digits are printed after decimal points. If precision is more than the number of digits on the right side of the decimal point, 0s are added to the right side.

  4. If precision indicates too few digits, then it is ignored and the number of digits are printed as necessary.

Flags

  1. Flag characters are used to give directives for the output. You can use multiple flag characters in any order.

  2. The flag characters are as follows:

    • Indicates that output is left justified.

      printf("%-10.4d\n", 25)
    • It causes the number to be printed as 0025bbbbbb. Thus, blanks are added to the right side.

    • In the absence of a flag, it is printed as bbbbbb0025.

    • + Indicates that i number is printed using a sign character (+ or —).

      printf("%+d\n", -25);
      printf("%+d\n", 25);
    • It causes printing as

      -25
      +25
    • Indicates a space for positive values so that positive values and negative values are aligned. For example,

      printf("% d\n", 25);
      printf("% d", 25);
    • It causes printing in the form of

      b25
      25
    • In the first case, blank is displayed.

    • # Indicates that the value should be converted to another form before displaying. For example, for hexadecimal values you can indicate 0X; for the floating data type, # indicates that the decimal point should always be included in the output.

    • 0 Used with whole and real numbers, 0 causes 0s to be padded to complete the field width. If the precision is specified as 0, then this flag is ignored; if the 0 and – flags are both specified, the 0 flag is ignored.

    ESCAPE SEQUENCE

Escape sequences are the special directives used to format printing. For example, \n indicates that the next printing should start from the first column of the next line. Following are the escape sequences:

  • \a Alert

  • Produces a beep or flash; the cursor position is not changed.

  • \b Backspace

  • Moves the cursor to the last column of the previous line.

  • \f Form feed

  • Moves the cursor to start of next page.

  • \n New line

  • Moves the cursor to the first column of the next line.

  • \r Carriage Return

  • Moves the cursor to the first column of the current line.

  • \t Horizontal Tab

  • Moves the cursor to the next horizontal tab stop on the line.

  • \v Vertical Tab

  • Moves the cursor to the next vertical tab stop on the line.

  • \\

  • Prints \\.

  • \"

  • Prints "

  • %%

  • Prints %.

Tuesday, March 17, 2009

Facts About Computer and Programming

  • Most applications in a data warehouse consists of transactions.
  • A Transaction consist of one read and write operation.
  • For security purpose we use proxy server along with firewall.
  • Rollback command undo all changes of a transaction.
  • Applet is a dynamic document application program.
  • The speed of a Super Computer is mainly measured in FLOPS.
  • RAID 3 is a single parity drive depends on disk controller for finding out which disk has failed.
  • Propagation time is the time which takes by a signal to transmit from one point of a medium to other end.
  • Sliding window protocol is used in data link layer to store the information about frame sequences and respective acknowledgement.
  • archie is a program to find files in ftp site.
  • website to get kernel source code http://lxr.free-electrons.com/source/
  • The linux kernel mailing list http://www.tux.org/lkml/#s15-3
  • static library has extension .a and dynamic library has .so.
  • files which shown in colors in linux require permissions.
  • ./ is the relative path and starts with / is called absolute path.

Monday, March 16, 2009

Important facts in Writing a C Program

  • Preprocessor can be redefined any where in the Program so that most recently assigned value will be taken.
  • The scope of the labels is limited to functions.
  • The case statement can have only constant expressions (this implies that we cannot use variable names directly). Enumerated types can be used in case statements.
  • Scanf returns number of items successfully read.
  • A variable is available for use from the point of declaration.
  • Pointers give a facility to access the value of a variable indirectly.
  • Prefix/postfix increment(++) and decrement(--) must be used with variables.
  • Precedence is very important in writing a expression.
  • Execution of preprocessor is separate from execution of compiler(Note: we can use any keywords and inbuilt function names).
  • Every function name contains some address. So we can easily print that address using printf("%p",main);.
  • Array names are pointer constants.
  • Character constants are saved in code/data area but not in stack.
  • g1##g2,Here g1 and g2 joined together.
  • The default return value of a function is int. if it is not declared.
  • printf can be implemented using variable length argument list.
  • asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use, #undef NDEBUG and this will disable all the assertions from the source code. Assertion is a good debugging tool to make use of. if program terminates it shows <> <> of the program.
  • stdin,stdout,stderr these three files are opened automatically when c program executes.
  • SEEK_SET sets the file pointer to beginning of file.
  • SEEK_CUR and SEEK_END are set accordingly by the name.
  • if we want to read input between two quotation marks we should use scanf(" \"%[^\"]\"",s);.
  • fgets always return a pointer,So while reading end of file it returns NULL pointer.
  • If a program is continuously executed without any condition to terminate then its stack will filled completely and abnormally terminates.
  • -1 is a boolean true value,Hence in if statement it executes next instruction of if.
  • When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation).
  • For array elements, consecutive memory locations are allocated.
  • When a variable can be resolved by using multiple references, the local definition is given more preference.
  • The variables in C can have static or automatic lifetimes.
  • When a variable has a static lifetime, memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates.
  • When a variable has an automatic lifetime, the memory is allocated to the variable when the function is called and it is deallocated once the function completes its execution.
  • Global variables have static lifetimes.
  • By default, local variables have automatic lifetimes.
  • To make a local variable static, use the storage-class specifier.
  • Extern means that the variable or function is implemented elsewhere but is referred to in the current file.
  • memory is allocated to the global variable at the beginning of the program execution.
  • Register allocation is done for faster access, generally for loop counters.
  • You cannot declare global register variables.
  • The code between opening and closing curly brace called as block.
  • Array elements are Homogeneous(means their elements are of same type).
  • Structure elements are of Heterogeneous type (means their elements are of different type).
  • Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .

Common Mistakes in C

  • Initializing the structure member variables while declaring.
  • Converting a character Array into String without Appending NULL character.
  • Calling the function without declaring the Prototype.
  • Declared buffer must be initialized before use.
  • Using proper data types when copying functions from one project to another project.
  • Multiple definition of a function some times creates a problem when we are browsing the code through tags in some famous editors like vim etc.(NOTE: Enable the function which is currently in use.Comment the other ones).
  • Avoid same function names which are already defined in system library.

C Operator Precedence

()
[]
.
->
++ --
Parentheses (function call)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement

left-to-right

++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (change type)
Dereference
Address
Determine size in bytes
right-to-left
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <=
> >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
=
+= -=
*= /=
%= &=
^= |=
<<= >>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left

,

Comma (separate expressions) left-to-right