Sunday, 29 August 2010

Tricky questions on C

1)Write a C program to find a peculiar two digit number which is three times the sum of its digits.

2) Bacteria are known to multiply very rapidly. If a certain container contains just one bacterium on the first day and there are twice as many on the next day. In this manner the number of bacteria in the container doubles itself everyday. Assuming that the container would be full on the 10th day with 13,312 bacteria, find the number of bacteria that was initially in the container on the first day.

3) Calculate the factorial of a number recursively. From that calculate the value of COS(X) = 1 - X2/2! + X4 /4! - X6/ 6! +…….

4) A number of “Cats” got together and decided to kill between them 999919 mice. Every cat killed equal number of “mice”. Write a program to find number of cats.

5) Consider the following number 45*45=2025; 20+25=45.Write a program to generate number between 32 and 99 that satisfies the above property.

6) Rita has a money pouch containing Rs.700. There are equal number of 25 paise coins, 50 paise and one rupee coins. Write a C program to find how many of each are there?

7) Calculate the factorial of a number recursively and from that calculate the value of ex=1+ (X1/1!) + (X2 /2!) + (X3/3!) + ……….

8) There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. Write a program to find number of goats and ducks in the farm.

9) Write a C program to find a three digit number which is greater than the aggregate of its third, tenth and the twelfth parts by 58.

10) Write a C program to find a two digit number, the second digit of which is smaller than its first digit by 4, and if the number was divided by the digit’s sum, the quotient would be 7.

Read more: http://cmagical.blogspot.com/2009/11/technical-question-31-of-32-print.html#ixzz0y16ofSCW

C Programming on Unix ( Creating menu driven environment in C in Unix)


Creating menu driven environment in C in Unix

#include
#include
#define ENTER 10
#define ESCAPE 27
void init_curses()
{
initscr();
start_color();
init_pair(1,COLOR_WHITE,COLOR_BLUE);
init_pair(2,COLOR_RED,COLOR_GREEN);
init_pair(3,COLOR_RED,COLOR_WHITE);
init_pair(4,COLOR_BLUE,COLOR_YELLOW);
init_pair(5,COLOR_BLUE,COLOR_CYAN);
curs_set(0);
noecho();
keypad(stdscr,TRUE);
}
void draw_menubar(WINDOW *menubar)
{
wbkgd(menubar,COLOR_PAIR(5));
waddstr(menubar,"File");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F1)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,10);
waddstr(menubar,"Edit");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F2)");
wmove(menubar,0,20);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Search");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F3)");
wmove(menubar,0,31);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Cursor ");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F4)");
wmove(menubar,0,43);
wattroff(menubar,COLOR_PAIR(3));
waddstr(menubar,"Compile");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F5)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,56);
waddstr(menubar,"Help");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F6)");
wattroff(menubar,COLOR_PAIR(3));
wmove(menubar,0,66);
waddstr(menubar,"Exit");
wattron(menubar,COLOR_PAIR(3));
waddstr(menubar,"(F7)");

}
WINDOW **draw_menu(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW **)malloc(9*sizeof(WINDOW *));
items[0]=newwin(6,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));
// box(items[0],ACS_VLINE,ACS_HLINE);
//wprintw(items[1],"new");

items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);
/// items[7]=subwin(items[0],1,17,8,start_col+1);
// items[8]=subwin(items[0],1,17,9,start_col+1);
/// for (i=1;i<9;i++)

wprintw(items[1],"Load",i);
wprintw(items[2],"New",i);
wprintw(items[3],"Save");
wprintw(items[4],"Save as");
wprintw(items[5],"Printer");
/// wprintw(items[],"FILE%d",i);
/// wprintw(item[1],"File%d",i);
// wbkgd(items[1],COLOR_PAIR(1));
wrefresh(items[0]);
return items;
}
WINDOW **draw_menu2(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(5,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));

items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);

wprintw(items[1],"Find");
wprintw(items[2],"Find and replace");
wprintw(items[3],"Repeat last find");
wprintw(items[4],"Goto line number");
wrefresh(items[0]);
return items;
}


WINDOW **draw_menu1(int start_col)
{

int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(6,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));

items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,3,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,5,start_col+1);
items[5]=subwin(items[0],1,17,6,start_col+1);
items[6]=subwin(items[0],1,17,7,start_col+1);

wprintw(items[1],"Undo");
wprintw(items[2],"Cut");
wprintw(items[3],"Copy");
wprintw(items[4],"Paste");
wprintw(items[5],"Delete");
wrefresh(items[0]);
return items;
}

WINDOW **draw_menu4(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(5,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));

items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,2,start_col+1);
items[3]=subwin(items[0],1,17,4,start_col+1);
items[4]=subwin(items[0],1,17,4,start_col+1);
// items[5]=subwin(items[0],1,17,4,start_col+1);
// items[6]=subwin(items[0],1,17,4,start_col+1);
wprintw(items[2],"C Compiler");
wprintw(items[4],"C++ Compiler");
wrefresh(items[0]);

return items;
}


WINDOW **draw_menu5(int start_col)
{
int i;
WINDOW **items;
items=(WINDOW**) malloc(9*sizeof(WINDOW*));
items[0]=newwin(4,19,1,start_col);
wbkgd(items[0],COLOR_PAIR(2));


items[1]=subwin(items[0],1,17,2,start_col+1);
items[2]=subwin(items[0],1,17,2,start_col+1);
items[3]=subwin(items[0],1,17,2,start_col+1);
items[4]=subwin(items[0],1,17,4,start_col+1);
// items[5]=subwin(items[0],1,17,4,start_col+1);
// items[6]=subwin(items[0],1,17,4,start_col+1);

wprintw(items[2],"Key words");
// wprintw(items[4]," perator");
wprintw(items[4],"Operator");
// wprintw(items[6],"Help");
wrefresh(items[0]);

return items;

}

void delete_menu(WINDOW **items,int count)
{
int i;
for (i=0;i
delwin(items[i]);
free(items);
}
int scroll_menu(WINDOW **items,int count,int menu_start_col)
{
int key;
int selected=0;
while (1) {
key=getch();
if (key==KEY_DOWN || key==KEY_UP) {
wbkgd(items[selected+1],COLOR_PAIR(2));
wnoutrefresh(items[selected+1]);
if (key==KEY_DOWN) {
selected=(selected+1) % count;
} else {
selected=(selected+count-1) % count;
}
wbkgd(items[selected+1],COLOR_PAIR(1));
wnoutrefresh(items[selected+1]);
doupdate();
} else if (key==KEY_LEFT || key==KEY_RIGHT) {
delete_menu(items,count+1);
touchwin(stdscr);
refresh();
items=draw_menu(60-menu_start_col);
return scroll_menu(items,5,60-menu_start_col);
} else if (key==ESCAPE) {
return -1;
} else if (key==ENTER) {
return selected;
}
}
}
int main()
{
int key,t;
WINDOW *menubar,*messagebar,*window;
init_curses();
bkgd(COLOR_PAIR(1));
window=subwin(stdscr,1,80,24,0);
wbkgd(window,COLOR_PAIR(4));
menubar=subwin(stdscr,1,80,0,0);
messagebar=subwin(stdscr,1,79,23,1);
draw_menubar(menubar);
move(2,1);
printw("Press F1 or F2 to open the menus. ");
printw("F9 quits.");
/// window=newwin(2,68,23,8);
/// wbkgd(window,COLOR_PAIR(4));
///t=wgetch(window);
refresh();

do {
int selected_item;
WINDOW **menu_items;
key=getch();
werase(messagebar);
wrefresh(messagebar);
if (key==KEY_F(1))
{
menu_items=draw_menu(0);
selected_item=scroll_menu(menu_items,5,0);
delete_menu(menu_items,9);

if (selected_item<0)
wprintw(messagebar,
"You haven't selected any item.");
else
wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
touchwin(stdscr);
refresh();
} else if (key==KEY_F(2))
{
menu_items=draw_menu1(10);
selected_item=scroll_menu(menu_items,5,10);
delete_menu(menu_items,9);

if (selected_item<0)
wprintw(messagebar,"You haven't selected any item.");
else
wprintw(messagebar, "You have selected menu item %d.",selected_item+1);
// touchwin(stdscr);
/// window=newwin(2,68,23,12);
///wbkgd(window,COLOR_PAIR(4));
/// t=wgetch(window);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(3))
{
menu_items=draw_menu2(20);
selected_item=scroll_menu(menu_items,5,20);
delete_menu(menu_items,9);

if(selected_item<0)
wprintw(messagebar,"don't select any item");
else
wprintw(messagebar, "You have select menu item %d",selected_item+1);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(5))
{
menu_items=draw_menu4(40);
selected_item=scroll_menu(menu_items,5,40);
delete_menu(menu_items,9);

if(selected_item<0)
wprintw(messagebar, "No item is selected");
else
wprintw(messagebar, "You have selected menu %d",selected_item+1);
touchwin(stdscr);
refresh();
}
else if(key==KEY_F(6))
{
menu_items=draw_menu5(55);
selected_item=scroll_menu(menu_items,5,55);
delete_menu(menu_items,9);

if(selected_item<0)
wprintw(messagebar,
" No item is selected");
else
wprintw(messagebar, "You have selected menu %d",selected_item+1);
touchwin(stdscr);
refresh();
}

else if(key==KEY_F(7))
{
menu_items=draw_menu4(60);
selected_item=scroll_menu(menu_items,5,60);
delete_menu(menu_items,9);

if(selected_item<0)
wprintw(messagebar, "No item is selected");
else
wprintw(messagebar, "You have to select menu %d",selected_item+1);

touchwin(stdscr);
refresh();
}
} while (key!=KEY_F(9));

delwin(menubar);
delwin(messagebar);
delwin(window);
endwin();
return 0;
}


Read more: http://cmagical.blogspot.com/2010/01/c-programming-on-unix-creating-menu.html#ixzz0y16dZleY
Under Creative Commons License: Attribution Non-Commercial No Derivatives

datatypes Questions on c

(1) How many type of data c?
Ans:
In c, there are three types of data.



(2) What is qualifier or modifier of data type?
Ans:
It qualify the primary data type.There are five group of qualifier in C.

(There is another type qualifier near, far, huge, which qualify only pointer type data type ,interrupt is also qualifier of data)
We can write all five (one for each group) qualifiers for same data type. If we will not write then it will take its default quantifier.We can write quantifier in any order.We cannot write two qualifier of the same group.
E.g short unsigned volatile const int a=5;
It is right. Qualifier of each group is:

E.g static auto int a=5;
It is wrong, because we cannot write two qualifier of the same group.Both static and auto comes under group 1 i.e storage class.
Note. There is not any keyword for the opposite const and volatile .So if does not write qualifier const it means the default qualifier is opposite of const.Same this happen for volatile.Default qualifier of group 3 has also not any keyword .It is between the short and long i.e normal data type.
It not necessary that each primary data type support all five group of quantifier.

g
(3) What is size of each data type?


Ans:
Size of data type depends upon microprocessor.
Size of int is word length
Size of short int can be >= word length/2 but <=word length Size of long int can be <= 2*word length but >=word length
Size of char, float, double, long double is always fix.
Size of enum is size of int.
Turbo C is based on 8086 microprocessor and its word length is two byte

For TURBO C
Data type size (in byte)
char 1
Short int 2
int 2
long int or long 4
enum 2
float 4
double 8
long double 10
(4) What is const and volatile qualifier?
Ans:
Value of any variable can be changed either by program or external device.const. and volatile is not opposite to each other.
Const : when any variable has qualified with const keyword in declaration statement then later it is not possible to assigne any value or modify by the program.But indirectly with the help of pointer its value can be changed.
When any variable is not qualified by const variable then it’s default qualifier is not const .There is not any keyword for not const.It’s meaning is that value of variable can be changed after the declaration statement by the program.
e.g
What will be output?
void main()
{
const int a=5;
a++;


printf(“%d”,a);
}
Ans: compiler error, we cannot modify const variable.

Volatile: when any variable has qualified by volatile keyword in declaration statement then value of variable can be changed by any external device or hardware interrupt.
If any variable has not qualified by volatile keyword in declaration statement, then then compiler will take not volatile as default quantifier .There is not any special keyword for not volatile.Not volatile means when any variable has qualified by volatile keyword in declaration statement then value of variable cannot be changed by any external device or hardware interrupt.
(5) What is meaning of the declaration:
const volatile int a=6;
Ans:
Value of variable cannot be changed by program (due to const) but its value can be changed by external device or hardware interrupt (due to volatile).
(9) How char data type is represented in the memory?
Ans:
char data type may be signed or unsigned .Both has different memory representation.Both are 8 bit data type.
unsigned char:
All 8 bit is used as data bit.
e.g memory representation of unsigned char a= 7;
Binary equivalent of 7 is 111
For 8 bit we will add 5 zero in the left side i.e 00000111
In the memory:




Here MSD is most significant digit and LSD is list significant digit.
signed char:
1 bit: signed bit
7 bit: data bit
Note: In C, negative number is stored in the 2’s complement format.
Signed bit is 0: Number is positive.
Signed bit is 1: Number is negative.

e.g memory representation of char a=7;
Binary equivalent of 7 is 111
For 8 bit we will add 5 zero in the left side i.e 00000111
Memory representation:

e.g memory representation of char a= -7;
Binary equivalent of 7 is 111
For 8 bit we will add 5 zero in the left side i.e 00000111
Since a is negative number so it will store in the memory in the 2’s complement format

Memory representation:

.
(10) What is endianness of processor?
Ans:
If the size of data type is more than one byte then endianness decides the memory representation of data type.
There are two type of endianness.
Little-endian: The processor which follow the following memory representation of data is known as little-endian processor.


First A will fill then B then C then D then E and so on from right to left.
Example of processor: 8085,8086,8088,80286,80386,p1,p2 etc.
Big-endian:
The processor which follow the following memory representation of data is known as big-endian processor.

First A will fill then B then C then D then E from right to left.
Example of processor:
Motorola, IBM PC etc.

Thursday, 26 August 2010

Virtual Table ln c

Here is a short description of the virtual tables layout. This is mostly taken out of the existing Taligent runtime.

Virtual tables

Virtual tables (vtables) are used to dispatch virtual functions, to access virtual base class sub objects, and to access information for runtime type identi?cation (RTTI). Each class that has virtual member functions or virtual bases has an associated set of vtables. The vtable pointers within all the objects (instances) of a class point to the same set of vtables.

Vtable layout

Each vtable consists of the following parts, in the order listed.All offsets in a vtable are of type ptrdiff_t.

"Virtual base offsets" are used to access the virtual bases of anobject and to non virtual bases when pointer adjustment is required for some overriden virtual function. Each entry is a displacement to a virtual base subobject from the location within the object of the vtable pointer that addresses this vtable. These entries are only necessary if the class directly or indirectly inherits from virtual base classes, or if it overrides a virtual function defined in a base class and if adjustment from the based to the derived class is needed. The values can be positive or negative.

"Offset to top" holds the displacement to the top of the object from the location within the object of the vtable pointer that addresses this vtable. A negative value indicates the vtable pointer is part of an embedded base class subobject; otherwise it is zero. The offset provides a way to ?nd the top of the object from any base subobject with a vtable pointer. This is necessary for dynamic_cast in particular. The virtual pointer points to the "offset to top" field.

"Typeinfo pointer" points to the typeinfo object used for RTTI. All entries in each of the vtables for a given class point to the same typeinfo object.

"Duplicate base information pointer" points to a table used to perform runtime disambiguation of duplicate base classes for dynamic casts. The entries in each of the vtables for a given class do not all point to the same table of duplicate base information.

Function pointers are used for virtual function dispatch. Each Pointer holds either the address of a virtual function of the class, or the address of a secondary entry point that performs certain
adjustments before transferring control to a virtual function. [To be discussed] In the case of shared library builds, [Solution 1] a function pointer entry contains the address of a function descriptor, which contains the target GP value and the actual function address [Solution 2] a function pointer entry contains two words: the value of the target GP value and the actual function address [Solution 3] a function pointer points to an import table generated by the dynamic loader, which will transfer control to the target function.

The function pointers are grouped so that the entries for all virtual functions introduced by a base class are kept together, in declaration order. Function pointers from a derived class immediately follow those for the base class. The order of function pointers therefore depends on the static type of subobject whose vtable pointer points to that virtual table.

A vtable pointer in an object addresses the "offset to top" ?eld of a vtable. This location is known as the address point of thevtable. Note that the virtual base offsets are at negative displacements from the address point.

The typeinfo and duplicate base information are covered in separate discussions.

Types of vtables

The following categories describe the rules for how vtables of a class are constructed from the vtables of its bases.

Category 1

This category is for a class that inherits no base classes. If the class declares no virtual functions, then it has no vtable, and its objects have no vtable pointers.

If the class declares virtual functions, then it has a single vtable containing RTTI ?elds followed by function pointer entries. There is one function pointer entry for each virtual function declared in the class. The vtable pointer in an object of the class addresses this vtable.

Category 2

This category is for a class that inherits only non-virtual base classes, and the non- virtual base classes have no base classes, and there is no adjustment in any of the overriden virtual functions.

If none of the base classes have vtables, a vtable is constructed for the class according to the same rules as in Category 1. Otherwise the class has a vtable for each base class that has a vtable. The class's vtables are constructed from copies of the base class vtables. The entries are the same, except: - The RTTI ?elds contain information for the class, rather than for the base class. - The function pointer entries for virtual functions inherited from the base class and overridden by this class are replaced with the addresses of the overridden functions (or the corresponding adjustor secondary entry points), - At negative offsets, offsets to the base classes are generated if used by adjustor secondary entry points.

Informally, each of these vtables has a name in the form Base-in-Derived vtable, where Base is a base class and Derived is the derived class. Each vtable pointer in an object addresses one of
these vtables for the class. The vtable pointer of an A subobject within a B object would address the A-in-B vtable.

The vtable copied from the primary base class is also called the primary vtable; it is addressed by the vtable pointer at the top of the object. The other vtables of the class are called secondary
vtables; they are addressed by vtable pointers inside the object.

Aside from the function pointer entries that correspond to those of the primary base class, the primary vtable holds the following additional entries at its tail:- Entries for virtual functions introduced by this class - Entries for overridden virtual functions not already in the vtable. (These are also called replicated entries because they are already in the secondary vtables of the class.) [I wonder if this is actually needed, this seems to be a consequence of RRBC]

The primary vtable, therefore, has the base class functions appearing before the derived class functions. The primary vtable can be viewed as two vtables accessed from a shared vtable pointer.

Note Another bene?t of replicating virtual function entries is that it reduces the number of this pointer adjustments during virtual calls. Without replication, there would be more cases where the this pointer would have to be adjusted to access a secondary vtable prior to the call. These additional cases would be exactly those where the function is overridden in the derived class, implying an additional thunk adjustment back to the original pointer. Thus replication saves
two adjustments for each virtual call to an overridden function introduced by a non-primary base class.

Category 3

This category is for a class that inherits only virtual base classes, and the virtual base classes have no base classes.

The class has a vtable for each virtual base class that has a vtable. These are all secondary vtables and are constructed from copies of the base class vtables according to the same rules as in Category 2. The vtable pointers of the virtual base subobjects within the object address these vtables.

The class also has a vtable that is not copied from the virtual base class vtables. This vtable is the primary vtable of the class and addressed by the vtable pointer at the top of the object, which is not shared. It holds the following function pointer entries:- Entries for virtual functions introduced by this class - Entries for overridden virtual functions. (These are also called replicated entries, because they are already in the secondary vtables of the class)

The primary vtable also has virtual base offset entries to allow ?nding the virtual base subobjects. There is one virtual base offset entry for each virtual base class. For a class that inherits only virtual bases, the entries are in the reverse order in which the virtual bases appear in the class declaration, that is, the entry for the leftmost virtual base is closest to the address point of the vtable.

Category 4

This category is for a class that directly or indirectly inherits base classes that are either virtual or non-virtual.

The rules for constructing vtables of the class are a combination of the rules from Categories 2 and 3, and for the most part can be determined inductively. However the rules for placing virtual base offset entries in the vtables requires elaboration.

The primary vtable has virtual base offset entries for all virtual bases directly or indirectly inherited by the class. Each secondary vtable has entries only for virtual bases visible to the
corresponding base class. The entries in the primary vtable are ordered so that entries for virtual bases visible to the primary base class appear below entries for virtual bases only visible to this class.

For virtual bases only visible to this class, the entries are in the reverse order in which the virtual bases are encountered in a depth-?rst, left-to-right traversal of the inheritance graph formed by the class de?nitions. Note that this does not follow the order that virtual bases are placed in the object.

[To be discussed] Vtables for partially constructed objects

In some situations, a special vtable, called a construction vtable is used during the execution of base class constructors and destructors. These vtables are for speci?c cases of virtual inheritance.

During the construction of a class object, the object assumes the type of each of its base classes, as each base class subobject is constructed. RTTI queries in the base class constructor will return the type of the base class, and virtual calls will resolve to member functions of the base class rather than the complete class. Normally, this behavior is accomplished by setting, in the base class constructor, the object's vtable pointers to the addresses of the vtables for the base class.

However, if the base class has direct or indirect virtual bases, the vtable pointers have to be set to the addresses of construction vtables. This is because the normal base class vtables may not hold the correct virtual base index values to access the virtual bases of the object under construction, and adjustment addressed by these vtables may hold the wrong this parameter adjustment if the adjustment is to cast from a virtual base to another part of the object. The problem is that a complete object of a base class and a complete object of a derived class do not have virtual bases at the same offsets.

A construction vtable holds the virtual function addresses and the RTTI information associated with the base class and the virtual base indexes and the addresses of adjustor entry points with this parameter adjustments associated with objects of the complete class.

To ensure that the vtable pointers are set to the appropriate vtables during base class construction, a table of vtable pointers, called the VTT, which holds the addresses of construction and non-construction vtables is generated for the complete class. The constructor for the complete class passes to each base class constructor a pointer to the appropriate place in the VTT where the base class constructor can ?nd its set of vtables. Construction vtables are used in a similar way during the execution of base class destructors.

Sudoku Solver in c


/********************************** **************************
*** Dipl.- Inf. Detlef Hafer
*** D-91058 Erlangen (Germany)
********************************** ***************************/

#include "stdio.h>"
#include "stdlib.h"
#include "string.h"

#define BACK -1
#define FORWARD 1
#define NSIZE 9
#define BOOL bool
#define FALSE false
#define TRUE true

int F[NSIZE][NSIZE];

#if _DEBUG
static int M[NSIZE][NSIZE] = { {1, 6, 4, 0, 0, 0, 0, 0, 2},
{2, 0, 0, 4, 0, 3, 9, 1, 0},
{0, 0, 5, 0, 8, 0, 4, 0, 7},

{0, 9, 0, 0, 0, 6, 5, 0, 0},
{5, 0, 0, 1, 0, 2, 0, 0, 8},
{0, 0, 8, 9, 0, 0, 0, 3, 0},

{8, 0, 9, 0, 4, 0, 2, 0, 0},
{0, 7, 3, 5, 0, 9, 0, 0, 1},
{4, 0, 0, 0, 0, 0, 6, 7, 9} };

#endif

static BOOL findnumber (int z, int s)
{
int u = (z/3)*3;
int v = (s/3)*3;
int m = F[z][s];
F[z][s] = 0;

for (int t = m+1; t <= NSIZE; t++)
{
for (int i = 0; i < NSIZE; i++)
{
div_t q = div(i,3);
if ((F[i][s] == t) || (F[z][i] == t) || F[u+q.quot][v+q.rem] == t)
break;
}
if (i == NSIZE )
{
F[z][s] = t;
return TRUE;
}
}
return FALSE;
}

BOOL soduko (void)
{
BOOL bFix[NSIZE][NSIZE];
int r = FORWARD;

#if _DEBUG
memcpy(F, M, sizeof(M));
#endif

for (int i = 0; i < NSIZE; i++)
for (int j = 0; j < NSIZE; j++)
bFix[i][j] = (F[i][j] != 0);

i = 0;
while ( (i >= 0) && (i < NSIZE*NSIZE) )
{
div_t q = div(i,NSIZE);
int z = q.quot;
int s = q.rem;

if ( ! bFix[z][s])
{
if ( ! findnumber(z,s))
r = BACK;
else
r = FORWARD;
}
i += r;
}
if ( i < 0)
{
// no solution
return FALSE;
}
return TRUE;
}

int main()
{
soduko();


for (int i = 0; i < NSIZE; i++)
{
for (int j = 0; j < NSIZE; j++)
{
printf("%d ",M[i][j]);
}
printf("\n");
}
printf("\n");
printf("\n");

for (int i = 0; i < NSIZE; i++)
{
for (int j = 0; j < NSIZE; j++)
{
printf("%d ",F[i][j]);
}
printf("\n");
}


}
cppcoder.blogspot.com/

List View Item Control.

Here is a sample listing of code that will add bitmap IDs(win32 application) or ICON Ids to the list view control. few month back I made this to add a feature to my existing application module.

You cannot blindly add this to ur workspace since it need some modifications. Treat this as a code snippet or an example to make the target.!! Happy coding

/**

     class/structure:     SListControl

author: renjith



creation: 25-march-2008



Modification History

---------------------------------------------------------------------------------

Date comments Reason



---------------------------------------------------------------------------------

27-Mar-08 Added ne method AddBmpImage() which To add this class in

takes a vector of Ids and Names as Input. main dialog of CADPartDB





16-Jun-08 Added new methods SetProductName() and Support for new fron-end

GetProductName() to support the new front interface (insert/update

end Interface the contents of DB)





---------------------------------------------------------------------------------

**/




#pragma once



#include

#include "../resource.h"

#include "../stdafx.h"





struct SListControl

{





private:

LV_ITEM lvi;

LV_COLUMN lvc;



std::vector<_str> m_strProdName;





public:



//int AddString ( LPCTSTR str ) { return ::SendMessage( handle, LB_ADDSTRING, 0, (LPARAM)str ); };



int GetCurSel();

void SetProductName(const std::vector<_str> & strVecName);



std::vector<_str> GetProductName();



void AddBmpImage(std::vector<int> nVecIDs,std::vector<_str> strVecName);

bool AddBmpImage(int nIDStart,int nIDEnd, _str strName);



bool AddIconImage(int nIDStart,int nIDEnd, _str strName);

};

















/**

class/structure: SListControl

author: renjith



creation: 25-march-2008



Modification History

---------------------------------------------------------------------------------

Date comments Reason



---------------------------------------------------------------------------------

27-Mar-08 Added ne method AddBmpImage() which To add this class in

takes a vector of Ids and Names as Input. main dialog of CADPartDB





16-Jun-08 Added new methods SetProductName() and Support for new fron-end

GetProductName() to support the new front interface (insert/update

end Interface the contents of DB)





---------------------------------------------------------------------------------

**/








#include "guicontrolenhanced.h"

#include "StdAfx.h"



#include



#include "../resource.h"

/*



#include


#include


using namespace std;*/








void SListControl::SetProductName(const std::vector<_str> & strVecName)



{

m_strProdName = strVecName;

}



std::vector<_str> SListControl::GetProductName()

{

return m_strProdName;



}



void SListControl::AddBmpImage(std::vector<int> nVecIDs,std::vector<_str> strVecName)

{

int nMAX = nVecIDs.size();



HWND hList = handle;

RECT Rect;

HIMAGELIST himlLarge;



SetProductName(strVecName);



//LV_ITEM lvi;

//LV_COLUMN lvc;



int iStatus;

int i;

char szStr[ 32 ];



//Registers and initializes certain common control window classes.



InitCommonControls();



if( ! hList )

MessageBox(NULL,
"hList is Null","",MB_OK);





// Create an Image list, of 80x80 pixels

himlLarge = ImageList_Create(80,80,ILC_COLOR32,100,100);

//4th argument is the number of images that the image list initially contains.

//5th argument is the the number of images by which the image list can grow when

//the system needs to make room for new images.





for( i = 0; i < color="#008000">// Add Images to each image list

{

HBITMAP hBitMap;
// bitmap handler



int imlindex=-1;



hBitMap=LoadBitmap(g_hModule,MAKEINTRESOURCE(nVecIDs[i]));

if(!hBitMap)

MessageBox(NULL,
"hBitMap is null","Msg",MB_OK);





imlindex = ImageList_Add(himlLarge,hBitMap,NULL);

}



// Make the listview use the images lists and exit



//ListView_SetImageList( hList, himlLarge, LVSIL_NORMAL);



// this is # defined in the header as...

SendMessage(hList, LVM_SETIMAGELIST, (WPARAM)(LVSIL_NORMAL), (LPARAM)(HIMAGELIST)(himlLarge));



GetClientRect( hList, &Rect );
// Get the listview RECT size



lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;



lvc.fmt = LVCFMT_LEFT;

lvc.cx = Rect.right - Rect.left;
// Make bar width of window

lvc.pszText =
"Item Status";

lvc.iSubItem = 0;
// Add display column (for Report View)



//iStatus = ListView_InsertColumn( hList, 0, &lvc );

iStatus = SendMessage((hList), LVM_INSERTCOLUMN, (WPARAM)(
int)(0), (LPARAM)(const LV_COLUMN *)(&lvc));





lvi.mask = LVIF_IMAGE | LVIF_PARAM | LVIF_TEXT | LVIF_STATE;

lvi.state = 0;

lvi.stateMask = LVIS_FOCUSED;
// Set generic structure values

lvi.pszText = szStr;



for( i = 0; i < color="#008000">// Add 20 items to the control



{



wsprintf( szStr,
"%s",strVecName[i].c_str() ); // Name depends on number

lvi.iImage = i ;
// 5 images



lvi.iItem = i;

lvi.iSubItem = 0;

lvi.lParam = 1;

//iStatus = ListView_InsertItem( hList, &lvi ); // Add item to control



iStatus = ::SendMessage((hList), LVM_INSERTITEM, 0, (LPARAM)(
const LV_ITEM *)( &lvi));

}

}



bool SListControl::AddBmpImage(int nIDStart,int nIDEnd, _str strName)



{

int nMAX = nIDEnd - nIDStart;

HWND hList = handle;

RECT Rect;

HIMAGELIST himlLarge;

// HIMAGELIST himlSmall;





//LV_ITEM lvi;

//LV_COLUMN lvc;

int iStatus;

int i;



char szStr[ 32 ];





InitCommonControls();



if( ! hList )

MessageBox(NULL,
"hList is Null","",MB_OK);



// Create two lists, one for 32x32 and another for 16x16 icons



himlLarge = ImageList_Create(80,80,ILC_COLOR32,100,100);
//100, 100, ILC_COLOR32, 0, 10



for( i = 0; i <= nMAX; i++ ) // Add icons to each image list



{

HBITMAP hBitMap;
// bitmap handler

int imlindex=-1;





hBitMap=LoadBitmap(g_hModule,MAKEINTRESOURCE(nIDStart+i));

if(!hBitMap)

MessageBox(NULL,
"hBitMap is null","Msg",MB_OK);





imlindex = ImageList_Add(himlLarge,hBitMap,NULL);

}



// Make the listview use the images lists and exit



//ListView_SetImageList( hList, himlLarge, LVSIL_NORMAL);



SendMessage(hList, LVM_SETIMAGELIST, (WPARAM)(LVSIL_NORMAL), (LPARAM)(HIMAGELIST)(himlLarge));



GetClientRect( hList, &Rect );
// Get the listview RECT size



lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;

lvc.fmt = LVCFMT_LEFT;



lvc.cx = Rect.right - Rect.left;
// Make bar width of window

lvc.pszText =
"Item Status";

lvc.iSubItem = 0;
// Add display column (for Report View)

//iStatus = ListView_InsertColumn( hList, 0, &lvc );



iStatus = SendMessage((hList), LVM_INSERTCOLUMN, (WPARAM)(
int)(0), (LPARAM)(const LV_COLUMN *)(&lvc));



lvi.mask = LVIF_IMAGE | LVIF_PARAM | LVIF_TEXT | LVIF_STATE;

lvi.state = 0;



lvi.stateMask = LVIS_FOCUSED;
// Set generic structure values

lvi.pszText = szStr;



for( i = 0; i <= nMAX; i++ ) // Add 20 items to the control

{





wsprintf( szStr,
"%s #%d",strName.c_str(), i + 1 ); // Name depends on number

lvi.iImage = i ;
// 5 images



lvi.iItem = i;

lvi.iSubItem = 0;

lvi.lParam = 1;

//iStatus = ListView_InsertItem( hList, &lvi ); // Add item to control



iStatus = ::SendMessage((hList), LVM_INSERTITEM, 0, (LPARAM)(
const LV_ITEM *)( &lvi));

}

// SendMessage(hList,LVM_DELETEITEM,3,0);



return true;



}



bool SListControl::AddIconImage(int nIDStart,int nIDEnd, _str strName)

{

int nMAX = nIDEnd - nIDStart;



HWND hList = handle;

RECT Rect;

HICON hiconItem;

HIMAGELIST himlLarge;

//LV_ITEM lvi;

//LV_COLUMN lvc;



int iStatus;

char szStr[ 32 ];

int i;



InitCommonControls();





if( ! hList )

MessageBox(NULL,
"hList is Null","",MB_OK);

// Create lists, for 32x32 icons



himlLarge = ImageList_Create( GetSystemMetrics( SM_CXICON ),

GetSystemMetrics( SM_CYICON ),

TRUE, 1, 1 );





for( i = 0; i < color="#008000">// Add icons to each image list

{





hiconItem = (HICON)LoadImage( g_hModule, MAKEINTRESOURCE( 1000+i ),IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR );

if(!hiconItem)

MessageBox(NULL,
"hiconItem is Null","",MB_OK);





ImageList_AddIcon( himlLarge, hiconItem );

DeleteObject( hiconItem );

}





// Make the listview use the images lists and exit

//ListView_SetImageList( hList, himlLarge, LVSIL_NORMAL);

SendMessage(hList, LVM_SETIMAGELIST, (WPARAM)(LVSIL_NORMAL), (LPARAM)(HIMAGELIST)(himlLarge));



GetClientRect( hList, &Rect );
// Get the listview RECT size





lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;

lvc.fmt = LVCFMT_LEFT;

lvc.cx = Rect.right - Rect.left;
// Make bar width of window

lvc.pszText =
"Item Status";



lvc.iSubItem = 0;
// Add display column (for Report View)

//iStatus = ListView_InsertColumn( hList, 0, &lvc );

iStatus = SendMessage((hList), LVM_INSERTCOLUMN, (WPARAM)(
int)(0), (LPARAM)(const LV_COLUMN *)(&lvc));







lvi.mask = LVIF_IMAGE | LVIF_PARAM | LVIF_TEXT | LVIF_STATE;

lvi.state = 0;

lvi.stateMask = LVIS_FOCUSED;
// Set generic structure values

lvi.pszText = szStr;



for( i = 0; i < color="#008000">// Add 20 items to the control



{

wsprintf( szStr,
"%s #%d",strName.c_str(), i + 1 ); // Name depends on number

lvi.iImage = i ;
//% 5; // 5 images



lvi.iItem = i;

lvi.iSubItem = 0;

lvi.lParam = 1;

//iStatus = ListView_InsertItem( hList, &lvi ); // Add item to control



iStatus = ::SendMessage((hList), LVM_INSERTITEM, 0, (LPARAM)(
const LV_ITEM *)( &lvi));

}





return true;



}



int SListControl::GetCurSel()

{

//return ListView_GetNextItem(handle,-1,LVNI_FOCUSED);;

return SendMessage(handle,LVM_GETNEXTITEM,-1,LVNI_FOCUSED); // return item selected



}



cppcoder.blogspot.com/

Wednesday, 25 August 2010

Write c program which shutdown the window operating system ?


Write the following program in TURBO C.
void main(void)
{
system("shutdown -s");
}
Save the above .Let file name is close.c and compile and execute the above program. Now close the turbo c compiler and open the directory in window you have saved the close.c ( default directory c:\tc\bin) and double click the its exe file(close.exe).After some time your window will shutdown
.