#include <stdio.h>
#include <stdlib.h>
#include <wiringPi.h>
void
blink(){
digitalWrite(0,1);
delay(300);
digitalWrite(0,0);
}
char
get_key(){
int i;
int j;
for (j = 21; j < 25; ++j) {
digitalWrite(j, 1);
}
for (;;) {
for (i = 25; i < 29; ++i) {
if (digitalRead(i)) {
for (j = 21; j < 25; ++j) {
digitalWrite(j, 0);
if (!digitalRead(i)) {
blink();
switch (((i - 25) << 2) | (j - 21)) {
case 0: return '1';
case 1: return '4';
case 2: return '7';
case 3: return 'C';
case 4: return '2';
case 5: return '5';
case 6: return '8';
case 7: return '0';
case 8: return '3';
case 9: return '6';
case 10: return '9';
case 11: return '#';
case 12: return 'A';
case 13: return 'B';
case 14: return 'C';
case 15: return 'D';
}
}
}
}
}
}
}
int
get_num (
int count,
int x
){
char k;
printf("in get number");
while(count){
printf ("\ncount = %d", count);
k = get_key();
printf ("key = %c\n", k);
if (k == '#') return x;
if (('0' <= k) && (k <= '9')){
x = (x * 10) + (k - '0') ;
}
else return -1;
--count;
}
k = get_key();
if (k == '#') return x;
else return -1;
}
int
main()
{
int a;
int i,j;
int x,y,z;
int count;
wiringPiSetup();
pinMode(21, OUTPUT);
pinMode(22, OUTPUT);
pinMode(23, OUTPUT);
pinMode(24, OUTPUT);
pinMode(25, INPUT);
pinMode(26, INPUT);
pinMode(27, INPUT);
pinMode(28, INPUT);
pinMode(0, OUTPUT);
x = get_num( 6,0 );
printf("\nthe number = %d\n" , x );
}
Sunday, December 13, 2015
Wednesday, December 9, 2015
Sound Sensor code - 9 Dece 2015
#include <stdio.h>
#include <wiringPi.h>
#include <pcf8591.h>
#define PCF 120
int main (void)
{
int value;
int count = 0;
wiringPiSetup ();
// Setup pcf8591 on base pin 120, and address 0x48
pcf8591Setup (PCF, 0x48);
while(1) // loop forever
{
value = analogRead (PCF + 0);
//printf("%d\n", value);
if (value < 50){
count++;
printf("Voice In!! %d\n", count);
}
}
return 0;
}
#include <wiringPi.h>
#include <pcf8591.h>
#define PCF 120
int main (void)
{
int value;
int count = 0;
wiringPiSetup ();
// Setup pcf8591 on base pin 120, and address 0x48
pcf8591Setup (PCF, 0x48);
while(1) // loop forever
{
value = analogRead (PCF + 0);
//printf("%d\n", value);
if (value < 50){
count++;
printf("Voice In!! %d\n", count);
}
}
return 0;
}
Thursday, November 19, 2015
19 October 2015 - Button switch (momentary) example program and Pi 2B J8 Header
// Program button.c
//
#include <wiringPi.h>
#include <stdio.h>
// One side of the button is placed on GPIO 0
// The other side is on 5V
#define BtnPin 0
int
main(
){
wiringPiSetup();
pinMode(BtnPin,INPUT);
for(;;)
{
if(0==digitalRead(BtnPin))
{
printf("\nButton is NOT Pressed\n");
}
if(1==digitalRead(BtnPin))
{
printf("\nButton is Pressed\n");
}
}
return(0);
}
//
#include <wiringPi.h>
#include <stdio.h>
// One side of the button is placed on GPIO 0
// The other side is on 5V
#define BtnPin 0
int
main(
){
wiringPiSetup();
pinMode(BtnPin,INPUT);
for(;;)
{
if(0==digitalRead(BtnPin))
{
printf("\nButton is NOT Pressed\n");
}
if(1==digitalRead(BtnPin))
{
printf("\nButton is Pressed\n");
}
}
return(0);
}
Tuesday, November 10, 2015
DC Motor Control using PWM for Speed Control
In this exercise, we use DC Motor control using PWM for speed control. The electronic driver is called an H-Bridge that will allow the motor to turn either way if hooked up properly. That will be shown in a follow-on Blog entry.
We us a 31162MP H-Driver as hooked up to the Raspberry Pi 2B as shown:
https://www.dropbox.com/s/c0xvxc32x4q75tn/hDrivePi.pptx?dl=0
The specification for the 31162MP H-Driver board is:
https://www.dropbox.com/s/m2cym0tm2e7c2f4/31162mp-Hdriver.pdf?dl=0
Test code using a single speed is shown below. The speed can be set depending on the PWM pulse width of 0-1023. Below a value of about 150, the motor may not turn.
https://www.dropbox.com/s/p5e6wjhjwrra2s2/pwmtest1.c?dl=0
We us a 31162MP H-Driver as hooked up to the Raspberry Pi 2B as shown:
https://www.dropbox.com/s/c0xvxc32x4q75tn/hDrivePi.pptx?dl=0
The specification for the 31162MP H-Driver board is:
https://www.dropbox.com/s/m2cym0tm2e7c2f4/31162mp-Hdriver.pdf?dl=0
Test code using a single speed is shown below. The speed can be set depending on the PWM pulse width of 0-1023. Below a value of about 150, the motor may not turn.
https://www.dropbox.com/s/p5e6wjhjwrra2s2/pwmtest1.c?dl=0
Continuous Temperature Sensor with LED Indicator Program
Continuous Temperature Sensor with LED Indicator Program using linked compile for the functions.
The main program: tempmain.c
GPIO Setup program (function): setupPi.c
LED Off program (function): leds_off.c
Read Temperature Sensor program (function): readTemp.c
Turn on LED Corresponding to Temperature (I used 3 temperature ranges): led_temp_on.c
To compile:
gcc tempmain.c setupPi.c leds_off.c readtemp.c led_temp_on.c -lwiringPi
Single Pass Example Temperature Sensor with LED Indicator Program
SINGLE PASS Example Temperature Sensor with LED Indicator Program using linked compile for the functions.
The main program: tempmainEx.c
GPIO Setup program (function): setupPiEx.c
LED Off program (function): leds_offEx.c
Read Temperature Sensor program (function): readTempEx.c
Turn on LED Corresponding to Temperature (I used 3 temperature ranges): led_temp_onEx.c
To compile:
gcc tempmainEx.c setupPiEx.c leds_offEx.c readtempEx.c led_temp_onEx.c -lwiringPi
You'll see on the display when certain entries and exits to and from functions occur.
Monday, October 19, 2015
Bubble sort with function
/* Bubble sort code with function */
#include <stdio.h>
#define MAX 1000000
int main()
{
int array[MAX];
int n,a,b,swap;
printf("\n Enter number of elements\n");
scanf("%d", &n);
/* placed number of elements, n, in address &n */
printf("\nEnter number of integers %d \n", n);
for (a=0;a<n;a++)
{
scanf("%d",&array[a]);
/* Input array elements into their address locations */
}
printf("\nSorted list in ascending order:\n");
sort(n,array);
printf("\n\n\nEnd Sort \n");
return 0;
}
int sort(int num,int x[])
{ int a, b, j, swap;
for (a=0;a<(num-1);a++)
{
for (b =0;b<num-a-1;b++)
{
if (x[b] > x[b+1]) /* For decreasing order use < */
{
swap=x[b];
x[b]=x[b+1];
x[b+1]=swap;
}
}
}
for (j=0;j<num;j++ )
{
printf("%d\n", x[j]);
}
}
#include <stdio.h>
#define MAX 1000000
int main()
{
int array[MAX];
int n,a,b,swap;
printf("\n Enter number of elements\n");
scanf("%d", &n);
/* placed number of elements, n, in address &n */
printf("\nEnter number of integers %d \n", n);
for (a=0;a<n;a++)
{
scanf("%d",&array[a]);
/* Input array elements into their address locations */
}
printf("\nSorted list in ascending order:\n");
sort(n,array);
printf("\n\n\nEnd Sort \n");
return 0;
}
int sort(int num,int x[])
{ int a, b, j, swap;
for (a=0;a<(num-1);a++)
{
for (b =0;b<num-a-1;b++)
{
if (x[b] > x[b+1]) /* For decreasing order use < */
{
swap=x[b];
x[b]=x[b+1];
x[b+1]=swap;
}
}
}
for (j=0;j<num;j++ )
{
printf("%d\n", x[j]);
}
}
Bubble Sort Code
/* Bubble sort code */
#include <stdio.h>
#define MAX 1000000
int main()
{
int array[MAX];
int n,a,b,swap;
printf("\n Enter number of elements\n");
scanf("%d", &n);
/* placed number of elements, n, in address &n */
printf("\nEnter number of integers %d \n", n);
for (a=0;a<n;a++)
{
scanf("%d",&array[a]);
/* Input array elements into their address locations */
}
for (a=0;a<(n-1);a++)
{
for (b =0;b<n-a-1;b++)
{
if (array[b] > array[b+1]) /* For decreasing order use < */
{
swap=array[b];
array[b]=array[b+1];
array[b+1]=swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (a=0;a<n;a++ )
{
printf("%d\n", array[a]);
}
return 0;
}
#include <stdio.h>
#define MAX 1000000
int main()
{
int array[MAX];
int n,a,b,swap;
printf("\n Enter number of elements\n");
scanf("%d", &n);
/* placed number of elements, n, in address &n */
printf("\nEnter number of integers %d \n", n);
for (a=0;a<n;a++)
{
scanf("%d",&array[a]);
/* Input array elements into their address locations */
}
for (a=0;a<(n-1);a++)
{
for (b =0;b<n-a-1;b++)
{
if (array[b] > array[b+1]) /* For decreasing order use < */
{
swap=array[b];
array[b]=array[b+1];
array[b+1]=swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (a=0;a<n;a++ )
{
printf("%d\n", array[a]);
}
return 0;
}
Traffic Light Program
#include <stdio.h>
#include <wiringPi.h>
void red(void);
void yellow(void);
void green(void);
int main()
{
/* set up the wiring pi library functions */
wiringPiSetup();
pinMode(0,OUTPUT);
pinMode(1,OUTPUT);
pinMode(2,OUTPUT);
/* pinMode 0 is the GPIO_0 (GPIO Zero) pin that is */
/* pin #7 on the header - green*/
/* set up GPIO_0 as an output port (as opposed to input port * /
/*pinMode 1 is GPIO_1 yellow and pinMode 2 is GPIO_2 red */
while(1)
{
green();
delay(300);
yellow();
delay(300);
red();
delay(300);
}
return (0);
/* Not necessay in C Code - main() returns 0 <--zero */
/*at the termination of program */
}
void green(void)
{
digitalWrite(0,HIGH);
delay(700);
digitalWrite(0,LOW);
}
void yellow(void)
{
digitalWrite(1,HIGH);
delay(700);
digitalWrite(1,LOW);
}
void red(void)
{
digitalWrite(2,HIGH);
delay(700);
digitalWrite(2,LOW);
}
#include <wiringPi.h>
void red(void);
void yellow(void);
void green(void);
int main()
{
/* set up the wiring pi library functions */
wiringPiSetup();
pinMode(0,OUTPUT);
pinMode(1,OUTPUT);
pinMode(2,OUTPUT);
/* pinMode 0 is the GPIO_0 (GPIO Zero) pin that is */
/* pin #7 on the header - green*/
/* set up GPIO_0 as an output port (as opposed to input port * /
/*pinMode 1 is GPIO_1 yellow and pinMode 2 is GPIO_2 red */
while(1)
{
green();
delay(300);
yellow();
delay(300);
red();
delay(300);
}
return (0);
/* Not necessay in C Code - main() returns 0 <--zero */
/*at the termination of program */
}
void green(void)
{
digitalWrite(0,HIGH);
delay(700);
digitalWrite(0,LOW);
}
void yellow(void)
{
digitalWrite(1,HIGH);
delay(700);
digitalWrite(1,LOW);
}
void red(void)
{
digitalWrite(2,HIGH);
delay(700);
digitalWrite(2,LOW);
}
Average and standard deviation program
/* Average (mean) and standard deviation program */
/* avg_std3.c */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Require math.h to perform square-root and square calculations */
int
main(
){
int i,j;
int x[10];
double sum,avg,sigma,sigma_sq;
int *ptr;
sum = 0;
for(i=0;i<10;i++)
{
x[i]=i;
/* ptr is assigned the value of the x[i] element address */
ptr=&x[i];
/* notice for long printf() statements, close the " and open " on next line */
printf("\nx[%d] = %d, at address using pointer *ptr %X, "
"and using pointer ADDRESS operator &x[i] = %X\n",i,x[i],ptr,&x[i]);
/* taking a running average by using the variable, sum */
/* also using the pointer *ptr to 'point' to the value */
sum=sum+*ptr;
}
j=i;
printf("\nSum = %f\n", sum);
avg=sum/(i);
printf("\nAverage = %f\n", avg);
sum=0;
for (i=0;i<10;i++)
{
/* the pow(a,b) = a^b using the math.h library */
sum=sum+pow((x[i]-avg),2);
}
/*calculate the variance whichi is the square of the standard deviation, sigma_sq*/
sigma_sq=sum/(i);
/*take the square root of the variance to calculate the standard deviation, sigma*/
/* sqrt(a) is the square root function using the math.h library */
sigma=sqrt(sigma_sq);
printf("\nVariance sigma_sq = %f\n\n",sigma_sq);
printf("\nStandard Deviation sigma = %f\n\n",sigma);
/******************************************************************/
/* to compile, */
/* gcc avg_std3.c -lm */
/* */
/* the -lm links the math.h library to the program avg_std3.c */
/* during compile. */
/* */
/* the program can be compiled in the 'me' directory */
/* */
/* To execute, ./a.out */
/* */
/* To name an executable named avg_std3: */
/* gcc avg_std3.c -o avg_std3 -lm */
/******************************************************************/
return(0);
}
/* avg_std3.c */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Require math.h to perform square-root and square calculations */
int
main(
){
int i,j;
int x[10];
double sum,avg,sigma,sigma_sq;
int *ptr;
sum = 0;
for(i=0;i<10;i++)
{
x[i]=i;
/* ptr is assigned the value of the x[i] element address */
ptr=&x[i];
/* notice for long printf() statements, close the " and open " on next line */
printf("\nx[%d] = %d, at address using pointer *ptr %X, "
"and using pointer ADDRESS operator &x[i] = %X\n",i,x[i],ptr,&x[i]);
/* taking a running average by using the variable, sum */
/* also using the pointer *ptr to 'point' to the value */
sum=sum+*ptr;
}
j=i;
printf("\nSum = %f\n", sum);
avg=sum/(i);
printf("\nAverage = %f\n", avg);
sum=0;
for (i=0;i<10;i++)
{
/* the pow(a,b) = a^b using the math.h library */
sum=sum+pow((x[i]-avg),2);
}
/*calculate the variance whichi is the square of the standard deviation, sigma_sq*/
sigma_sq=sum/(i);
/*take the square root of the variance to calculate the standard deviation, sigma*/
/* sqrt(a) is the square root function using the math.h library */
sigma=sqrt(sigma_sq);
printf("\nVariance sigma_sq = %f\n\n",sigma_sq);
printf("\nStandard Deviation sigma = %f\n\n",sigma);
/******************************************************************/
/* to compile, */
/* gcc avg_std3.c -lm */
/* */
/* the -lm links the math.h library to the program avg_std3.c */
/* during compile. */
/* */
/* the program can be compiled in the 'me' directory */
/* */
/* To execute, ./a.out */
/* */
/* To name an executable named avg_std3: */
/* gcc avg_std3.c -o avg_std3 -lm */
/******************************************************************/
return(0);
}
Program with Function
*Example of a program with functions*/
/*temperature conversion program*/
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
double CelToFahr(double temp_cel);
double FahrToCel(double fahr_temp);
int main()
{
int answer_1, dummy;
double celsius, fahr;
answer_1=TRUE;
while(answer_1==TRUE) {
printf("\nInput degrees Fahrenheit for conversion to Celsius(^z to exit): \n");
scanf("%lf",&fahr);
celsius=FahrToCel(fahr);
printf("\n%lf Celsius.\n\n",celsius);
printf("\nAnother F to C conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
scanf("%d",&answer_1);
while(answer_1==TRUE) {
printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit): \n");
scanf("\n%lf",&celsius);
fahr=CelToFahr(celsius);
printf("\n%lf Fahrenheit.\n\n", fahr);
}
printf("End of program - enter any number to exit.\n");
scanf("%d",&dummy);
}
double FahrToCel(double fahr_temp)
/* Function to convert Fahrenheit to Celsius */
{
double cel_temp;
cel_temp=(5.0/9.0)*(fahr_temp-32.0);
return(cel_temp);
}
double CelToFahr(double temp_cel)
/* Function to convert Celsius to Fahrenheit */
{
double temp_fahr;
temp_fahr=(9.0/5.0)*temp_cel+32.0;;
return(temp_fahr);
}
/*temperature conversion program*/
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
double CelToFahr(double temp_cel);
double FahrToCel(double fahr_temp);
int main()
{
int answer_1, dummy;
double celsius, fahr;
answer_1=TRUE;
while(answer_1==TRUE) {
printf("\nInput degrees Fahrenheit for conversion to Celsius(^z to exit): \n");
scanf("%lf",&fahr);
celsius=FahrToCel(fahr);
printf("\n%lf Celsius.\n\n",celsius);
printf("\nAnother F to C conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
scanf("%d",&answer_1);
while(answer_1==TRUE) {
printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit): \n");
scanf("\n%lf",&celsius);
fahr=CelToFahr(celsius);
printf("\n%lf Fahrenheit.\n\n", fahr);
}
printf("End of program - enter any number to exit.\n");
scanf("%d",&dummy);
}
double FahrToCel(double fahr_temp)
/* Function to convert Fahrenheit to Celsius */
{
double cel_temp;
cel_temp=(5.0/9.0)*(fahr_temp-32.0);
return(cel_temp);
}
double CelToFahr(double temp_cel)
/* Function to convert Celsius to Fahrenheit */
{
double temp_fahr;
temp_fahr=(9.0/5.0)*temp_cel+32.0;;
return(temp_fahr);
}
Program without function
/*Example of a program without functions*/
/*temperature conversion program*/
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
int main()
{
int answer_1;
double celsius;
double fahr;
answer_1=TRUE;
while(answer_1==TRUE) {
printf("\nInput degrees Fahrenheit for conversion to Celsius (^z to exit): \n");
scanf("%lf",&fahr);
celsius=((fahr-32.0)*5.)/9.;
printf("\n%lf Celcius\n\n", celsius);
printf("\nAnother F to C conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
scanf("%d", &answer_1);
while(answer_1==TRUE) {
printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit): \n");
scanf("%lf",&celsius);
fahr=(9.0/5.0)*celsius+32.0;
printf("\n\n%lf Fahrenheit. \n\n",fahr);
printf("\nAnother C to F conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\n\nEnd of program \n");
return (0);
}
/*temperature conversion program*/
#include <stdio.h>
#include <math.h>
#define TRUE 1
#define FALSE 0
int main()
{
int answer_1;
double celsius;
double fahr;
answer_1=TRUE;
while(answer_1==TRUE) {
printf("\nInput degrees Fahrenheit for conversion to Celsius (^z to exit): \n");
scanf("%lf",&fahr);
celsius=((fahr-32.0)*5.)/9.;
printf("\n%lf Celcius\n\n", celsius);
printf("\nAnother F to C conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\nDo you want to input degrees in Celsius for conversion? (yes=1)\n");
scanf("%d", &answer_1);
while(answer_1==TRUE) {
printf("\n\nInput degrees Celsius for conversion to Fahrenheit (^z to exit): \n");
scanf("%lf",&celsius);
fahr=(9.0/5.0)*celsius+32.0;
printf("\n\n%lf Fahrenheit. \n\n",fahr);
printf("\nAnother C to F conversion? (0 to exit conversion): \n");
scanf("%d", &answer_1);
}
printf("\n\nEnd of program \n");
return (0);
}
Inputting Integers, characters, and strings
#include <stdio.h>
#include <string.h>
void main()
{
int a, b;
float c, d;
double e, f;
char g,h;
char hello[10], cousin[10];
a=10; b=12; c=10; d=12; e=10; f=12;
g='H'; h='C';
strcpy(hello, "Howzit");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
strcpy(cousin, "Cuz");
printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
printf("\ne=%f, f=%f\n",e,f);
printf("\ng=%c, h=%c\n\n", g,h);
printf("\nHello=%s, Cousin=%s\n\n",hello,cousin);
printf("a= ");
scanf("%d",&a);
printf("\nb= ");
scanf("%d", &b);
printf("\n\n");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
printf("\na=%d \tb=%d \tc=%f \td=%f \n", a,b,c,d);
printf("Input String hello: ");
scanf("%s",&hello);
printf("Input String cousin: ");
scanf("%s", &cousin);
/* scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */
/* scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */
printf("\n\nHello = %s \n",hello);
printf("\nCousin = %s \n",cousin);
printf("\n\n%s %s\n\n",hello,cousin);
puts(hello);
puts(cousin);
}
#include <string.h>
void main()
{
int a, b;
float c, d;
double e, f;
char g,h;
char hello[10], cousin[10];
a=10; b=12; c=10; d=12; e=10; f=12;
g='H'; h='C';
strcpy(hello, "Howzit");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
strcpy(cousin, "Cuz");
printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
printf("\ne=%f, f=%f\n",e,f);
printf("\ng=%c, h=%c\n\n", g,h);
printf("\nHello=%s, Cousin=%s\n\n",hello,cousin);
printf("a= ");
scanf("%d",&a);
printf("\nb= ");
scanf("%d", &b);
printf("\n\n");printf("\na=%d, b=%d, c=%f, d=%f \n", a,b,c,d);
printf("\na=%d \tb=%d \tc=%f \td=%f \n", a,b,c,d);
printf("Input String hello: ");
scanf("%s",&hello);
printf("Input String cousin: ");
scanf("%s", &cousin);
/* scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */
/* scanf("Input Hello String=%s and Input Cousin String=%s", hello, cousin); */
printf("\n\nHello = %s \n",hello);
printf("\nCousin = %s \n",cousin);
printf("\n\n%s %s\n\n",hello,cousin);
puts(hello);
puts(cousin);
}
Using Pointers
USING
POINTERS
This example program shows a
pointer being used to swap between two floating point values. The actual
manipulation of the floating point values is done within the function get_value, which doesn't have any parameters. I decided that I
would do it by reassigning a pointer within the main program.
#include
<stdio.h>
/*
The pointer has to be declared here so that */
/*
the function get_value can get access to it. */
float
*my_point;
/*
The floating point variables have to be */
/*
declared here so that function display_values */
/*
can access them.*/
float
x = 36.3, y = -100.44;
int
main ()
{ display_values();
my_point = &x; // Points to x
get_value();
my_point = &y; // Points to y
get_value();
display_values();
return 0;
}
void
get_value ()
{ float decimal_number;
printf(\n "Please enter a number : \n");
scanf(“%f”,decimal_number);
*my_point = decimal_number;
}
void
display_values ()
{ printf("\nThe value of x is %f \n",x);
printf("\nThe value of y is %f \n",y);
}
The
value of x is 36.3
The
value of y is -100.44
Please
enter a number : 2.1
Please
enter a number : 3.1
The
value of x is 2.1
The
value of y is 3.1
_____________________________________________________________________________________________
I thought it might be interesting to see what the address of a variable is. Here I have declared three unsigned long values together with a pointer that moves between them. In each case, the address that the pointer is pointed to is displayed.
I thought it might be interesting to see what the address of a variable is. Here I have declared three unsigned long values together with a pointer that moves between them. In each case, the address that the pointer is pointed to is displayed.
#include
<stdio.h>
int
main ()
{ unsigned long a = 1, b = 2, c = 3, *p;
p = &a;
printf("\nThe address of a is %X\n",p);
printf("\nThe value of a is %d\n",*p);
p = &b;
printf("\nThe address of b is %X\n",p);
printf("\nThe value of b is %d\n",*p);
p = &c;
printf("\nThe address of c is %X\n",p);
printf("\nThe value of c is %d\n",*p);
return 0;
}
The
address of a is 0x3c27245e
The
value of a is 1
The
address of b is 0x3c27245a
The
value of b is 2
The
address of c is 0x3c272456
The
value of c is 3
____________________________________________________________________________________________
This function is used to sort
arrays of integers. The array itself is specified as a pointer. However, the
routine doesn't know in advance how many elements the array will have, so that
must also be passed across as an (ordinary) parameter.
void
sort (*int array, int num_elements)
{ int i, j;
int *temp;
/* Used in swopping array values */
for (i = 0; i < num_elements; i++)
for (j = 0; j < num_elements-1; j++)
if (*(array+j) > *(array+j+1))
{ temp = *(array+j);
*(array+j) = *(array+j+1);
*(array+j+1) = temp;
}
}
You will see that the pointer to the array is simply
declared as a pointer to an integer. You would have no way of knowing just by
looking at the first line of the function that the pointer indicated an array
rather than a simple integer (other than the fact that the pointer is called array, of course, which is something of a giveaway!)
The array elements are referred to using the pointer. *(array+j) refers to element array[j] etc.
Check out the program
without functions:
Sorting an array would
involve swapping the elements as necessary, until they are all in ascending or
descending order. There are different sorting methods (called algorithms)
and this worked example demonstrates what is probably the simplest sorting
algorithm - Bubblesort.
|
Bubblesort is so-called as
the largest elements of the array move gradually to the end like bubbles
rising to the surface in a glass of fizzy drink. It is usually the slowest
sorting algorithm (although it can take advantage of array elements which
have been partially sorted already). The algorithm goes as follows:
|
![]() |
Assume
N is the number of elements in the array.
Go
through the elements from 1 to N-1
Look at the current element and the next
one.
Are they out of order? If so, swop them.
At the end of the run, the largest element
will have
"bubbled" to the end of the
array.
Repeat
this process N times.
Here is the code. Go through it matching it
line-by-line with the algorithm above.
#include
<stdio.h>
int
main ()
{ int x[11]; /* Set up an array of 11 values */
x[0] = 74;
x[1] = 23; x[2] = 91; x[3] = 58;
x[4] = 52;
x[5] = 60; x[6] = 30; x[7] = 19;
x[8] = 28;
x[9] = 46; x[10] = 37;
int i,j;
/* These are used as loop variables */
int
temp; /* Used in swopping the values */
printf("\nBefore the sort, the values
are \n");
for (i = 0; i <= 10; i++)
printf(“x[%d] = %d\n”,i,x[i]);
for (i = 0; i < 11; i++) /* Go through 10 times */
for (j = 0; j < 10; j++) /* Check all elements */
if (x[j] > x[j+1]) /* except last */
{ temp = x[j];
x[j] = x[j+1];
x[j+1] = temp;
}
printf("\n\nAfter the sort, the values
are \n");
for (i = 0; i <= 10; i++)
printf(“x[%d]
= %d\n”,i,x[i]);
return 0;
}
Before
the sort, the values are
74
23 91 58 52 60 30 19 28 46 37
After
the sort, the values are
19
23 28 30 37 46 52 58 60 74 91
More on Functions
void
function
void
is a function that has no return value.
/*
Prints a bad, I mean really bad, pun. */
#include
<stdio.h>
main()
{
print_pun();
return 0;
/* return 0 means end of program */
}
void
print_pun(void)
{
printf(“To C, or not to C: That is the question. \n”);
}
General Form of Functions
return-type
function name (parameters)
{
declarations
statements
}
The return type of a fucntion is the type of value that the
function returns. The following rules
govern the return type:
·
Functions may not return arrays, but there are
no other restrictions on the return type.
·
If the return type is omitted, the function is
presumed to return a value type int.
·
Specifying the return type is void
indicates that the function doesn’t return a value.
Local Variables
A variable declared in the body of a function is said to be local to the function. In the following function, log is
the local variable:
int
log2(int n)
{
int log = 0; /* local variable */
while (n>1) {
n /= 2;
log++;
}
return log;
}
By default, local variables have the following properties:
·
Automatic storage duration. The storage duration (or extent)
of a variable is the portion of program execution during which storage for the
variable exists. Storage for a local
variable is automatically allocated when the enclosing function is called and
deallocated when the function returns, so the variable is said to have automatic
storage duration. A local variable
doesn’t retain its value when its enclosing function returns. When the function is called again, there is
no guarantee that the variable will still have its old value.
·
Bock scope.
The scope of a variable is the portion of the program text in which
the variable can be referenced. A local
variable has block scope: It is visible
from its point of declaration to the end of the enclosing function body
only. Since the scope of a local
variable doesn’t extend beyond the function to which it belongs, other
functions can use the same name for other purposes.
Global or External
Variables
Passing arguments is
one way to transmit information to a function.
Functions can also communicate through global variables –
variables that are declared outside the body of any function:
#include
<stdio.h>
int x, y; /* global variables */
double k, z;
/* global variables */
main()
{
declarations
statements
}
return-type
function name (parameters)
{
declarations
statements
}
The properties of global variables are different from those
of local variables:
·
Static storage duration. A value stored in a global variable wil stay
there indefinitely until program termination.
·
File scope. A global variable has file scope: It is visible from its point of declaration
to the end of the enclosing file. As a result, a global variable can be
accessed by all functions that follow its declaration.
Pros and Cons of Global Variables
In most cases, it is better for functions to communicate
through parameters rather than by sharing values. Here’s why:
·
If we change a global variable during program
modification, we’ll need to check every function in the same file to see how
the change affects it.
·
If a global variable is assigned an incorrect
value, it may be difficult to identify the guilty function.
·
Functions that rely on global variables are hard
to reuse in other programs. A function
that depends on global variables is not self-contained.
Pre-Processor
Directives
·
Macro definition. The #define directive defines a
macro; the #undef
directive removes a macro definition.
·
File inclusion. The #include directive causes the
contents of a specified file to be included in a program.
·
Conditional compilation. The #if, #ifdef, #ifndef, #elif, #else,
and #endif
directives allow blocks of text to be either included in or excluded from a
program, depending on conditions that can be tested by the pre-processor.
Simple Macros
The definition of a simple macro has the form
#define identifier replacement-list
replacement-list
is any sequence of C tokens: It may
include identifier, keyworkds, number, character constants, string literal,
operators, and punctuation. When it
encounters a macro definition, the pre-processor makes anote that the identifier represents replacement-list
. Wherever identifier
appears later in the file, the pre-processor substitutes replacement-list
.
Don’t put any symbols in the macro definition – they’ll
become part of the replacement list.
Putting the =
symbol in a macro definition is a common error:
#define N = 100 /*****WRONG!!!*****/
#define N 100;
/*****WRONG!!! Semi-colon is not supposed to be used*****/
#define N 100
/** CORRECT**/
Sample good macros:
#define STR_LEN 80
#define TRUE 1
#define pi 3.14159
#define CR ‘\r’
#define MEM_ERR “Error: not enough memory.”
Parameterized Macros
The definition of a parameterized macro has the form
#define identifier (x1, x2,
..., xn) replacement-list
Example:
#define
IS_EVEN(n) ((n)%2==0)
So when
if (IS_EVEN(i)) i++ ;
appears later in the program, the preprocessor will replace
this line with:
if
(((n)%2==0)) i++ ;
Subscribe to:
Posts (Atom)

