answersLogoWhite

0

📱

C Programming

Questions related to the C Computer Programming Language. This ranges all the way from K&R to the most recent ANSI incarnations. C has become one of the most popular languages today, and has been used to write all sorts of things for nearly all of the modern operating systems and applications. It it a good compromise between speed, power, and complexity.

9,649 Questions

Menu driven program for selection sort bubble sort and insertion sort in c?

#include<iostream>

#include<time.h>

#include<iomanip>

#include<string>

void swap(int& x, int& y)

{

x^=y^=x^=y;

}

void bubble_sort(int* A, int size)

{

while(size)

{

int n=0;

for(int i=1; i<size; ++i)

{

if(A[i-1]>A[i])

{

swap(A[i-1], A[i]);

n=i;

}

}

size=n;

}

}

void insertion_sort(int* A, int size)

{

for(int i=1; i<size; ++i)

{

int value=A[i];

int hole=i;

while( hole && value<A[hole-1] )

{

A[hole]=A[hole-1];

--hole;

}

A[hole]=value;

}

}

void selection_sort(int* A, int size)

{

for(int i=0; i<size-1; ++i)

{

int j=i;

for(int k=i+1; k<size; ++k)

if(A[k]<A[j])

j=k;

if( i!=j )

swap(A[i],A[j]);

}

}

void sort(int* A, int size, int sort_type)

{

switch(sort_type)

{

case(0): bubble_sort( A, size );

case(1): insertion_sort( A, size );

case(2): selection_sort( A, size );

}

}

int* copy_array(int* A, int size)

{

int* copy=new int[size];

memcpy(copy, A, size*sizeof(int));

return(copy);

}

void print_array(int* A, int size, char* prompt)

{

std::cout<<prompt<<"\t";

for(int i=0; i<size; ++i)

std::cout<<std::setw(2)<<A[i]<<" ";

std::cout<<std::endl;

}

int get_rand(int range_min=0, int range_max=RAND_MAX)

{

return((int) ((double)rand() / (RAND_MAX + 1) * ((range_max + 1) - range_min) + range_min));

}

int input_char(std::string prompt, std::string input)

{

char ch;

do

{

std::cout<<prompt<<": ";

std::cin>>ch;

}

while(input.find(ch)==std::string::npos);

return(input.find(ch)%(input.size()/2));

}

int main()

{

srand((unsigned) time(NULL));

int size = get_rand( 10, 80);

if( int* A = new int[size] )

{

for( int i=0; i<size; ++i )

A[i]=get_rand( 1, size );

int choice=input_char("Please select a sorting method:\n[B]ubble, [I]nsert, [S]election", "bisBIS");

std::cout<<"You chose ";

switch(choice)

{

case(0): std::cout<<"bubble"; break;

case(1): std::cout<<"insertion"; break;

case(2): std::cout<<"selection"; break;

}

std::cout<<" sort...\n"<<std::endl;

print_array( A, size, "Before sorting" );

sort(A, size, choice);

print_array( A, size, "After sorting" );

delete [] A;

}

return(0);

}

The data type of an item price?

I am assuming that the question is "What would the best data type to represent a price".

Although this is open for debate, in Java I think that the best data type for a price is double and the best data type in C# to be decimal.

I hope this answers your question.

Can a Structure contain a Pointer to itself?

Yes, it is quite common.

Example:

struct List {

struct List *Next;

int value;

}

typedef struct List List;

Example2:

typedef struct Tree Tree;

struct Tree {

Tree *left,*right;

int value;

};

How do you write a program in c without using editor?

compling c executing c program without editor is similar to that of Java program. we just have to set the path to TC to the PATH environment variable. then using the TCC command we can execute the C program..... EG: TCC sam.c //Compilation sam //Execution

Write A program to add and multiply two very large numbers using doubly linked list?

class Node

002

{

003

private:

004

int data;

005

006

public:

007

friend class List;

008

friend class stack;

009

010

Node* next;

011

012

Node(){data = 0;}

013

014

Node(int x)

015

{

016

next = 0;

017

setdata(x);

018

}

019

020

int getdata()

021

{

022

return data;

023

}

024

025

void setdata(int x)

026

{

027

data = x;

028

}

029

030

void print()

031

{

032

cout<<data;

033

}

034

035

~Node(){}

036

};

037

038

class List

039

{

040

private:

041

Node* Head;

042

Node* Tail;

043

044

public:

045

046

friend class stack;

047

List(){Head = 0; Tail = 0;}

048

049

void addnode(int x)

050

{

051

Node *current = new Node(x);

052

053

if(Head 0)

197

{

198

return true;

199

}

200

else

201

{

202

return false;

203

}

204

}

205

206

Node* topEl()

207

{

208

return (L.top());

209

}

210

211

void printstack()

212

{

213

L.printlist();

214

}

215

216

~stack()

217

{

218

L.deletelist();

219

}

220

221

};

222

223

int main()

224

{

225

stack operand1;

226

stack operand2;

227

stack carry;

228

stack result;

229

int tempsum;

230

int a,b,c;

231

int carry1;

232

Node *n1 = NULL;

233

Node *n2 = NULL;

234

Node *n3 = NULL;

235

236

operand1.push(3);

237

operand1.push(8);

238

operand1.push(0);

239

operand2.push(5);

240

operand2.push(3);

241

operand2.push(5);

242

243

244

245

while(!(operand1.isEmpty()) && !(operand2.isEmpty()))

246

{

247

n1 = operand1.topEl();

248

a = n1->getdata();

249

n2 = operand2.topEl();

250

b = n2->getdata();

251

tempsum = a + b;

252

253

if(tempsum > 9)

254

{

255

c = 0;

256

if(!(carry.isEmpty()))

257

{

258

n3 = carry.topEl();

259

c = n3->getdata();

260

carry.pop();

261

}

262

carry1 = tempsum / 10;

263

tempsum = tempsum % 10;

264

carry.push(carry1);

265

result.push(tempsum + c);

266

}

267

else

268

{

269

if(!(carry.isEmpty()))

270

{

271

n3 = carry.topEl();

272

c = n3->getdata();

273

result.push(tempsum + c);

274

carry.pop();

275

}

276

else

277

{

278

result.push(tempsum);

279

}

280

}

281

operand1.pop();

282

operand2.pop();

283

}

284

285

n1 = operand1.topEl();

286

a = n1->getdata();

287

n2 = operand2.topEl();

288

b = n2->getdata();

289

tempsum = a + b;

290

if(carry.isEmpty())

291

{

292

result.push(tempsum);

293

}

294

else

295

{

296

n3 = carry.topEl();

297

c = n3->getdata();

298

result.push(tempsum + c);

299

carry.pop();

300

}

301

operand1.pop();

302

operand2.pop();

303

304

result.printstack();

305

306

system("pause");

307

return 0;

308

}

What level of raw data CANNOT be re-organized to form an array?

There is no level of data that cannot be organised to form an array. Although it is not possible to form an array of references, a reference has no address of its own and cannot be regarded as data. It is a programming tool, nothing more.

Can a double value be assigned to float variable?

THIS IS FOR JAVA i don't know about anything about other languages yes it can be assigned

the syntax is:

int (number) = (float) number

FOR EXAMPLE:

int = a;

a = (float ) 5.5;

if the (float) is not there then in Java it gives an error saying precision loss of data type

How do you declare data types?

typedef data_type data_name, for instance:

typedef int myDataType;

How do you implement a will?

You really need legal advice to do this so that it meets laws in your state or country. Basically, state your name, place of residence, the date, and declare that this is your last will and testament. Then state what property you want to leave to who, and sign it in front of witnesses (people that are NOT in the will) who will date and sign it as witnesses. Usually 3 witnesses.

Write a program in c to find even and odd nos?

#include<iostream>

using namespace std;

void main() {

int odd,even,number;

odd=0;

even=0;

for(int x=1;x<=10;x=x+1){

cout<<"enter a number\n";

cin>>number;

if(number%2==0){

even++;

}

else {

odd++;

}

}

cout<<"even number has:"<<even;

cout<<"odd number has:"<<odd;

}

How do you solve undefined references error in c?

Linker errors are many and varied. Without knowing the error it is impossible to say how you solve it.

Most linker errors relate to undefined symbols. For instance, if you declare a function but do not implement it, the function is undefined. This can also happen when you include a function library header but do not link to the function library containing the definitions. The compiler uses the header declarations to ensure all calls to the functions are valid even if the definition hasn't yet been compiled. It is the linker's job to ensure all declarations are defined. The only exception is templates which must be defined before they are used. This is why all template definitions are placed in the header alongside the declarations.

How does a high level language relate to the microprocessor's instruction set?

Generally speaking, it doesn't relate at all. If it did, it wouldn't be high-level, it would be machine-dependent. The relationship between the high-level code and the machine-code is ultimately determined by the language translator (compiler and/or interpreter) but, unlike assembly language which maps 1:1 with the microprocessor instruction set, compilers and interpreters are code generators and there is seldom a 1:1 relationship between the high-level source code and the machine code.

What is the syntax to declare the variable in c?

A variable is declared by declaring its name and type. Once a variable is declared you can use it in expressions, whether to assign a value or use the value. The name is also a reference to the memory address allocated to the variable, thus you can take the address of the name if required.

Need of constructor in c plus plus?

There is no specific keyword for a constructor in C++. Simply define and declare a method of the class with the same name as the class and it will be a constructor.

A constructor with no arguments is the default constructor, a constructor with one argument of class type is the copy constructor, and a constructor with one argument of some other type is the conversion constructor. You can provide other overloaded constructors if you want.

Write a program to read any five numbers and print average value?

#include<stdio.h>

#include<conio.h>

#define p printf

#define s scanf

int main()

{

clrscr();

int a,b,c,d,e;

int ans;

p("\nEnter first no.:");

s("%d",&a);

p("\nEnter second no.:");

s("%d",&b);

p("\nEnter third no.:");

s("%d",&c);

p("\nEnter fourth no.:");

s("%d",&d);

p("\nEnter fifth no.:");

s("%d",&e);

ans=(a+b+c+d+e)/5;

p("\nThe average is: %d",ans);

getch();

return 0;

}

What is the advantage of a binary search tree over an array based structure?

In a binary search tree, insertion, deletion and lookup are O(log n) (i.e. fast) when balanced.
With unsorted arrays, insertion and deletion are O(1) (i.e. very fast) but lookup is O(n) (i.e. slow).
With sorted arrays, insertion and deletion are O(n) (i.e. slow) and lookup is O(log n) (i.e. fast).

Binary search trees are good if you do all three operation (insertion, deletion, lookup) often and have enough data to justify the added burden of more complex structures and algorithms.

Why there is a need for C plus plus and how does it overcome the drawbacks of the C language?

Absolutely! C++ and Java are by far the two most popular programming languages in use today. Java is the most popular due to its ease of use, particularly with cross-platform development, but it compiles to byte code rather than native machine code, thus it is nowhere near as efficient as C++ and is therefore unsuitable for time-critical applications. Even its predecessor, C, is still in use today due to the fact that procedural C can be mapped 1:1 with the underlying machine code making it easier to develop small-scale, cross-platform applications such as driver software. However, since C++ is backward-compatible with C, the ability to mix low-level machine code with intermediate object-oriented code is advantageous when developing more complex applications, including operating systems. Java is simply too high level for this.

Would you write a program for trapezoidal rule in c language?

yes. /* trapezoid.c */ #include #include float f(float); float a; float b; float x; float h; float sum; int n; int i; int main() { printf("Enter value for a: "); scanf("%f", &a); printf("Enter value for b: "); scanf("%f", &b); printf("Enter number of rectangles: "); scanf("%d", &n); h = (b - a) / n; sum = (0.5 * h) * (f(a) + f(b)); printf("%f\n", sum); for (i = 1; i < n; i++) { sum = sum + h * f(a + (i * h)); printf("%f\n", sum); } printf("The value of the integral is: %f\n", sum); } float f(float x) { float value; /* define function here */ value = x*x + 3; return value; }

Which is the easiest sorting method?

There are generally eight sorting algorithms that are studied in school by computer science students. They are as follows: insertion, bubble, quick, quick3, merge, shell, heap, and selection sorting.

There are different types of sorting algorithms. One would be considered good if it is accurate and efficient. Different types of sorting includes; sequential, ascending, and descending.

What always contains a pointer variable?

pointer variable in c contains the address or the location of the other variable.

eg- if a=2 and address of a is 2345. b=&a then b is a pointer which contains 2345 which is the address of a. *b gives value of that is 2.

Write a c program to find the binary addition of two 8 bit numbers?

#include <stdio.h>

#include <iomanip>

int main()

{

int binary1[8] = {0,1,1,1,1,0,1,1}; //8 element array

int binary2[8] = {1,0,1,0,1,1,1,1}; //8 element array

int binarySum[9];

int overflow [9];

int i;

for (i=0; i<9; i++) overflow[i] = 0;

for (i=9; i >= 0; i--)

{

binarySum[i] = binary1[i] + binary2[i] + overflow[i];

if ( binarySum[i] > 1)

{

overflow[i-1] = 1;

binarySum[i] %= 2;

}

}

printf("Binary Sum is: ");

for (i = 0; i<9; i++) printf("%i", binarySum[i]);

printf("\n");

printf("\n");

printf("Carry Bit is: ");

for (i = 8 ; i>=0 ; i--) printf("%i", overflow[i]);

printf("\n");

return (0);

}

Time space trade off in data structure?

IN COMPUTER SCIENCE, A SPACE-TIME OR TIME-MEMORY TRADEOFF IS A SITUATION WHERE THE MEMORY USE CAN BE REDUCED AT THE COST OF SLOWER PROGRAM EXECUTION (OR, VICE VERSA, THE COMPUTATION TIME CAN BE REDUCED AT THE COST OF INCREASED MEMORY USE). AS THE RELATIVE COSTS OF CPU CYCLES, RAM SPACE, AND HARD DRIVE SPACE CHANGE HARD DRIVE SPACE HAS FOR SOME TIME BEEN GETTING CHEAPER AT A MUCH FASTER RATE THAN OTHER COMPONENTS OF COMPUTERS. THE APPROPRIATE CHOICES FOR SPACE-TIME TRADEOFFS HAVE CHANGED RADICALLY. OFTEN, BY EXPLOITING A SPACE-TIME TRADEOFF, A PROGRAM CAN BE MADE TO RUN MUCH FASTER.

THE MOST COMMON SITUATION IS AN ALGORITHM INVOLVING A LOOKUP TABLE: AN IMPLEMENTATION CAN INCLUDE THE ENTIRE TABLE, WHICH REDUCES COMPUTING TIME, BUT INCREASES THE AMOUNT OF MEMORY NEEDED, OR IT CAN COMPUTE TABLE ENTRIES AS NEEDED, INCREASING COMPUTING TIME, BUT REDUCING MEMORY REQUIREMENTS. A SPACE-TIME TRADEOFF CAN BE APPLIED TO THE PROBLEM OF DATA STORAGE. IF DATA IS STORED UNCOMPRESSED, IT TAKES MORE SPACE BUT LESS TIME THAN IF THE DATA WERE STORED COMPRESSED (SINCE COMPRESSING THE DATA REDUCES THE AMOUNT OF SPACE IT TAKES, BUT IT TAKES TIME TO RUN THECOMPRESSION ALGORITHM). DEPENDING ON THE PARTICULAR INSTANCE OF THE PROBLEM, EITHER WAY IS PRACTICAL. ANOTHER EXAMPLE IS DISPLAYING MATHEMATICAL FORMULAE ON PRIMARILY TEXT-BASED WEBSITES, SUCH AS WIKIPEDIA.

Storing only the LaTeX source and rendering it as an image every time the page is requested would be trading time for space - more time used, but less space. Rendering the image when the page is changed and storing the rendered images would be trading space for time - more space used, but less time. Note that there are also rare instances where it is possible to directly work with compressed data, such as in the case of compressed bitmap indices, where it is faster to work with compression than without compression. Larger code size can be traded for higher program speed when applying loop unrolling. This technique makes the code longer for each iteration of a loop, but saves the computation time required for jumping back to the beginning of the loop at the end of each iteration. Algorithms that also make use of space-time tradeoffs include:

BABY-STEP GIANT-STEP ALGORITHM FOR CALCULATING DISCRETE LOGARITHMS.

RAINBOW TABLES IN CRYPTOGRAPHY, WHERE THE ADVERSARY IS TRYING TO DO BETTER THAN THE EXPONENTIAL TIME REQUIRED FOR A BRUTE FORCE ATTACK. RAINBOW TABLES USE PARTIALLY PRECOMPUTED VALUES IN THE HASH SPACE OF A CRYPTOGRAPHIC HASH FUNCTION TO CRACK PASSWORDS IN MINUTES INSTEAD OF WEEKS. DECREASING THE SIZE OF THE RAINBOW TABLE INCREASES THE TIME REQUIRED TO ITERATE OVER THE HASH SPACE.

THE MEET-IN-THE-MIDDLE ATTACK USES A SPACE-TIME TRADEOFF TO FIND THE CRYPTOGRAPHIC KEY IN ONLY 2N + 1 ENCRYPTIONS (AND O(2N) SPACE) VERSUS THE EXPECTED 22N ENCRYPTIONS (BUT ONLY O(1) SPACE) OF THE NAIVE ATTACK.

DYNAMIC PROGRAMMING, WHERE THE TIME COMPLEXITY OF A PROBLEM CAN BE REDUCED SIGNIFICANTLY BY USING MORE MEMORY.

C program to find the year is leap year or not?

Algorithm:

If the year is not divisible by 4 then it is not a leap year.

Else if the year is not divisible by 100 then it is a leap year.

Else if the year is not divisible by 400 then is not a leap year.

Else it is a leap year.

Implementation:

bool is_leap_year (unsigned year) {

if (year%4) return false;

if (year%100) return true;

if (year%400) return false;

return true;

}

Given a linked list of integers sorted in an ascending order and a pointer to a single node containing an integer write a C program that insert the node P in the linked list so that remains sorted?

InsertNode(NODE **q,int num)

{

NODE *r,*temp ;

temp = *q;

r= malloc(sizeof(NODE));

r->data = num;

//if it's fisrt node to be inserted

if ( *q == NULL num < (*q)->data)

{

*q = r ;

(*q)->link=temp;

}

else

{

while(temp)

{

if ( (num > temp->data) && (num < temp->link->data ) )

{

r->link = temp->link;

temp->link = r;

return;

}

temp = temp->link;

}

r->link = NULL;

temp->link = r;

}

}

Which translator translate low level language 1010111 to machines language?

Only assembly languages are generally considered low-level programming languages, so one could argue that there is only one low-level language.

However, there are as many assembly languages as there are processor models or families, as each processor family implements its own set of machine code instructions. Different manufacturers not only invent different mnemonics for similar machine code operations to suit conventions and hardware architecture (e.g. MOVE vs LOAD/SAVE), but also support different notations.

Therefore, conceptually, the assembly language is the only low level programming language. However, the standpoint of view of learning the language, or from that of tools to support the language, there are numerous assembly languages, thus numerous low-level languages.