Friday, July 31, 2009

How to modify values in an array and print the new values in C/C++ programming?

#include%26lt;stdio.h%26gt;





void main()


{


int n, i,j, bit[8];





printf("\nEnter the number of bits that you want to convert to unipolar: ");


scanf("%d",%26amp;n);





for(i=1;i%26lt;=n;i++){


printf("Enter the bits(%d): ",i);


scanf("%d",%26amp;bit[i]);





}








printf("The stream of bits is: ");


for(i=1;i%26lt;=n;i++){





printf(" %d",bit[i]);


}





}





that's the program in C that i've written to enter and display a stream of bits [0,1].


but i am having troubles to convert the values in the array to unipolar voltages.





Can someone help me with the code of how to change the input bits [1] to 5v and the bits [0] to 0V and display the unipolar voltages.

How to modify values in an array and print the new values in C/C++ programming?
What is the big deal? Arrays and pointers are very similar, in fact, C tends to pass arrays by reference while passing individual variables by value -- meaning you pass it to a function and can usually modify the values directly using either array[offset] or *array+offset.





An array is a contiguous block of memory which holds as many elements as you have set aside memory for. While pointers can be arcane and therefore it is possible to approach arrays in an arcane manner, there is nothing arcane about arrays themselves unless they are strings.





Assuming what you enter are 1s and 0s, then this line will convert all the 1s to 5s:





for (i=1;i%26lt;=n;i++) if (bit[i]==1) bit[i]=5;





And your program shouldn't crash. It will store garbage in all the elements you don't specify, it will crash if you try to store eight or more values (arrays start at array[0] not array[1]) and it won't check for improper inputs but it's all straightforward.





You can also add an else bit[i]=0;

daisy

No comments:

Post a Comment