I am having a trouble in calling the user defined functions in the main program, using unix. the program is executing only for the number generation in the main program. but when i call the predefined function . the output retrieved is incorrect. Can someone please correct me where i have done it wrong
My main program states as
#include <stdio.h>
#include <stdlib.h>
void sort1(int []);
int main(void) {
int array[100];
int i , j;
printf("ten random numbers in [1,1000]\n");
for (i = 1; i <= 10; i++)
{
generate random numbers
}
printf("The list of Hundred random numbers are \n");
for (j = 1; j <= 10; j++ )
{
//to print the random numbers
}
sort1(array);
return 0;
}
//this is my user defined function: sort1.c
include <stdio.h>
int sort1(int a[])
{
int array[100], i, d, swap, e=10;
// algortithm
}
}
printf("Sorted list in ascending order:\n");
for ( i= 0 ; i< e ; i++ )
printf("%d\n", array[i]);
}
I get the output as
ten random numbers in [1,1000]
The list of Hundred random numbers are
--This gives correct output
Sorted list in ascending order:
1
-1442229816
0
-1444472964
#include <stdio.h>
#include <stdlib.h>
void sort1(int []);
int main(void) {
int array[100];
int i;
printf("ten random numbers in [1,1000]\n");
for (i = 1; i <= 10; i++)
{
array[i] = rand()%1000 + 1;
}
printf("The list of Hundred random numbers are \n");
for (i = 1; i <= 10; i++ )
{
printf("Element[%d] = %d\n", i, array[i] );
}
//Up to here it's ok but you have set the values in the positions 1-10 of the array so keep consistent with it
sort1(array);
printf("Sorted list in ascending order:\n");
for ( i= 1 ; i<= 10 ; i++ )
printf("%d\n", array[i]);
return 0;
}
void sort1(int a[])
{
int i,swap,sorted=0;
while(sorted==0){ //flag to know if array is sorted 0 means not sorted.
sorted=1; // we set the flag to sorted at start of sweep
for (i= 1 ; i<= (10-1); i++) //sweep through array
{
if (a[i] > a[i+1]) //check if sorted
{
swap = a[i];
a[i] = a[i+1];
a[i+1] = swap;
sorted=0; //if not sorted set flag to 0 and swap
}
}
}
}
Main problems in your code:
1) array[100] is not initialized in sort1 function.
2) I do not understand your sorting algorithm but in any case you are checking for values of a[0] which are not initialized so take care of the array positions you use each time and be consistent with it.
3) function prototype does not match
Related
I'm actually working on a personal "Excel" for school.
When the value of my cell is a number (int), I want to add it in my listNumber (QList int). When the value of my cell is a String, I want to add it my listString.
These two lists then allow me to sort.
The problem is here :
QString test = text(i, j);
test.toInt(&ok);
if (ok == true) {
listNumber.append(test.toInt());
qSort(listNumber.begin(), listNumber.end());
}
ERROR ASSERT failure in QList<T>::at: "index out of range" .
I think it's because it wants to "insert" a string in a list of integer.
Here my function "sort"
QList<QString> listString;
QList<int> listNumber;
bool ok;
QTableWidgetSelectionRange range = selectedRange();
for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
for (int i = range.topRow(); i <= range.bottomRow(); ++i) {
QString test = text(i, j);
test.toInt(&ok);
if (ok == true) {
listNumber.append(test.toInt());
qSort(listNumber.begin(), listNumber.end());
}
}
}
if (listNumber.count() == 0) {
QMessageBox test;
test.setText("liste vide");
test.exec();
}
else {
int x = 0;
for (int j = range.leftColumn(); j <= range.rightColumn(); ++j) {
for (int i = range.topRow(); i <= range.bottomRow(); ++i) {
Spreadsheet::setFormula(i, j, QString::number(listNumber.at(x)));
x++;
}
}
}
Thank you a lot for your help.
First of all, qSort in Qt is deprecated and it is recommended not to use it:
QT_DEPRECATED_X("Use std::sort") inline void qSort(...
You can use std::sort instead:
#include <algorithm>
//...
std::sort(listNumber.begin(), listNumber.end(), std::less<int>());
//or simply:
std::sort(listNumber.begin(), listNumber.end()); // using default comparison (operator <)
(But also you can simply call deprecated qSort:)
qSort(listNumber);
I am trying to perform a backward slicing of an array element at specific position. I tried two different source codes. The first one is (first.c):
const int in_array[5][5]={
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
21,22,23,24,25
};
int out_array[5][5];
int main(unsigned int x, unsigned int y)
{
int res;
int i;
int j;
for(i=0; i<5; i++){
for(j=0; j<5; j++){
out_array[i][j]=i*j*in_array[i][j];
}
}
res = out_array[x][y];
return res;
}
I run the command:
frama-c-gui -slevel 10 -val -slice-return main file.c
and get the following generated code:
int main(unsigned int x, unsigned int y)
{
int res;
int i;
int j;
i = 0;
while (i < 5) {
j = 0;
while (j < 5){
out_array[i][j] = (i * j) * in_array[i][i];
j ++;
}
i ++;
}
res = out_array[x][y];
return res;
}
This seems to be ok, since the x and y are not defined, so the "res" can be at any position in the out_array. I tried then with the following code:
const int in_array[5][5]={
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
21,22,23,24,25
};
int out_array[5][5];
int main(void)
{
int res;
int i;
int j;
for(i=0; i<5; i++){
for(j=0; j<5; j++){
out_array[i][j]=i*j*in_array[i][j];
}
}
res = out_array[3][3];
return res;
}
The result given was exactly the same. However, since I am explicitly looking for a specific position inside the array, and the loops are independent (parallelizable), I would expect the output to be something like this:
int main(void)
{
int res;
int i;
int j;
i = 3;
j = 3;
out_array[i][j]=(i * j) * in_array[i][j];
res = out_array[3][3];
}
I am not sure if is it clear from the examples. What I want to do is to identify, for a given array position, which statements impact its final result.
Thanks in advance for any support.
You obtain "the statements which impact the final result". The issue is that not all loop iterations are useful, but there is no way for the slicing to remove a statement to the code in its current form. If you perform syntactic loop unrolling, with -ulevel 5, then you will each loop iteration is individualized, and slicing can decide for each of them whether it is to be included in the slice or not. In the end, frama-c-gui -ulevel 5 -slice-return main loop.c gives you the following code
int main(void)
{
int res;
int i;
int j;
i = 0;
i ++;
i ++;
i ++;
j = 0;
j ++;
j ++;
j ++;
out_array[i][j] = (i * j) * in_array[i][j];
res = out_array[3][3];
return res;
}
which is indeed the minimal set of instructions needed to compute the value of out_array[3][3].
Of course whether -ulevel n scales up to very high values of n is another question.
I have below code two get a dot product of two vectors of size VECTORSIZE. Code works fine until VECTORSIZE up to 10000 but then it gives unrelated results. When I tried to debug the program I have seen that processor 0 (root) finishes its job before all processors send their local results. I got the same situation when I utilized the MPI_Reduce() (code part 2). However if I use MPI_Scatter() before MPI_Reduce() it is OK.
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#define VECTORSIZE 10000000
#define ROOT 0
//[[## operation ConstructVectorPart()
void ConstructVector(double * vector, int size, short vectorEnu)
{
int i = 0;
if(vectorEnu == 1) // i.e vector 1
{
for(i = 0; i < size; i++)
{
vector[i] = 0.1 + (i%20)*0.1;
}
}
else if(vectorEnu == 2) // i.e. vector 2
{
for(i = 0 ; i < size; i++)
{
vector[i] = 2-(i%20)*0.1;
}
}
}
//[[## operation dotproduct()
double dotproduct(double* a, double* b, int length)
{
double result = 0;
int i = 0;
for (i = 0; i<length; i++)
result += a[i] * b[i];
return result;
}
int main( argc, argv )
int argc;
char **argv;
{
int processorID, numofProcessors;
int partialVectorSize ;
double t1, t2, localDotProduct, result;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &numofProcessors );
MPI_Comm_rank( MPI_COMM_WORLD, &processorID );
if(processorID == 0)
t1 = MPI_Wtime();
// all processors constitute their own vector parts and
// calculates corresponding partial dot products
partialVectorSize = VECTORSIZE/ numofProcessors;
double *v1, *v2;
v1 = (double*)(malloc((partialVectorSize) * sizeof(double)));
v2 = (double*)(malloc((partialVectorSize) * sizeof(double)));
ConstructVectorPart(v1,0,partialVectorSize,1);
ConstructVectorPart(v2,0,partialVectorSize,2);
localDotProduct = dotproduct(v1,v2, partialVectorSize);
printf(" I am processor %d \n",processorID);
//----------------- code part 1 ---------------------------------------------
if( processorID != 0 ) // if not a master
{ // send partial result to master
MPI_Send( &localDotProduct, 1, MPI_DOUBLE, 0,0, MPI_COMM_WORLD );
}
else // master
{ // collect results
result = localDotProduct; // own result
int j;
for( j=1; j<numofProcessors; ++j )
{
MPI_Recv( &localDotProduct, 1, MPI_DOUBLE, j, 0, MPI_COMM_WORLD,MPI_STATUS_IGNORE);
result += localDotProduct;
}
t2 = MPI_Wtime();
printf(" result = %f TimeConsumed = %f \n",result, t2-t1);
}
//----------------------------------------------------------------------------
/*
//--------------------- code part 2 ----------------
MPI_Reduce(&localDotProduct, &result, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
if(processorID == 0)
{
t2 = MPI_Wtime();
printf(" result = %f TimeConsumed = %f \n",result, t2-t1);
}
//---------------------------------------------------
*/
MPI_Finalize();
free(v1);
free(v2);
return 0;
}
I'm not sure why this recursion is not working! I'm trying to get the total of an input from i=0 to n. I'm also testing recursion instead of 'for loop' to see how it performs. Program runs properly but stops after the input. I would appreciate any comments, thx!
int sigma (int n)
{
if (n <= 0) // Base Call
return 1;
else {
printf ("%d", n);
int sum = sigma( n+sigma(n-1) );
return sum;
}
// recursive call to calculate any sum>0;
// for example: input=3; sum=(3+sigma(3-1)); sum=(3+sigma(2))
// do sigma(2)=2+sigma(2-1)=2+sigma(1);
// so sigma(1)=1+sigma(1-1)=1+sigma(0)=1;
// finally, sigma(3)=3+2+1+0=6
}
int main (int argc, char *argv[])
{
int n;
printf("Enter a positive integer for sum : ");
scanf( " %d ", &n);
int sum = sigma(n);
printf("The sum of all numbers for your entry: %d\n", sum);
getch();
return 0;
}
Change
int sum = sigma( n+sigma(n-1) );
to
int sum = n + sigma( n-1 );
As you've written it, calling sigma(3) then calls sigma(5), etc...
Also, return 0 from the guard case, not 1.
I think it should be
int sum = n + sigma(n-1)
I made dynamic vector class..
But the problem show when main function is looping on and on,
my2dArr's row size is increasing when the function is looping
When data is coming on looping, i want to copy new data..
void main()
{
int data[450];
DynamicArray<int> my2dArr(36, 100);
for(int i = 0;i < 36;++i)
{
for(int j = 1;j < 16;++j)
{
my2dArr[i][j-1] = data[i];
}
}
}
// vector class
class DynamicArray
{
public:
DynamicArray(){};
DynamicArray(int rows, int cols): dArray(rows, vector<T>(cols)){}
vector<T> & operator[](int i)
{
return dArray[i];
}
const vector<T> & operator[] (int i) const
{
return dArray[i];
}
void resize(int rows, int cols)//resize the two dimentional array .
{
dArray.resize(rows);
for(int i = 0;i < rows;++i) dArray[i].resize(cols);
}
void clearCOL()
{
for(int i = 0;i < dArray.size();i++)
{
for(int j = 0;j < dArray[i].size();++j)
{
dArray[j].erase();
}
}
}
private:
vector<vector<T> > dArray;
};
The nested for loop should be fine at Initializing your array, but you'd need to put values into the data array to use it in initializing.
If you're only initializing the data once you might consider a third constructor overload that takes in an int[], like so:
DynamicArray( int rows, int cols, T array[] ): dArray( rows, vector< T >( cols ) )
{
for( int i = 0; i < rows; i++ )
{
for( int j = 0; j < cols; j++ )
{
dArray[i][j] = array[i * rows + j];
}
}
}
You'd need to make sure the array was the size you specified. In your example you pass a 450 int array in to initialize a 3,600 int DynamicArray. In you're example you're actually reading illegal data cause you go to the 16th column of each of the 36 rows so you're actually reading 576 elements from a 450 int array. I suppose the array is uninitialized anyway though, so it's all garbage.