C PROGRAM ONLY! 1. Set hasDigit to true if the 3-character passCode contains a d
ID: 3884357 • Letter: C
Question
C PROGRAM ONLY!
1. Set hasDigit to true if the 3-character passCode contains a digit.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
int main(void) {
bool hasDigit = false;
char passCode[50] = "";
int valid = 0;
strcpy(passCode, "abc");
/* Your solution goes here */
if (hasDigit) {
printf("Has a digit. ");
}
else {
printf("Has no digit. ");
}
return 0;
}
2. Replace any space ' ' by '_' in 2-character string passCode. Sample output for the given program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char passCode[3] = "";
strcpy(passCode, "1 ");
/* Your solution goes here */
printf("%s ", passCode);
return 0;
}
3. Write an expression that will cause the following code to print "Equal" if the value of sensorReading is "close enough" to targetValue. Otherwise, print "Not equal".
#include <stdio.h>
#include <math.h>
int main(void) {
double targetValue = 0.3333;
double sensorReading = 0.0;
sensorReading = 1.0/3.0;
if (/* Your solution goes here */) {
printf("Equal ");
}
else {
printf("Not equal ");
}
return 0;
}
Explanation / Answer
//Please see the answers below please do thumbs up if you like the solutions
1. Set hasDigit to true if the 3-character passCode contains a digit
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include<iostream>
using namespace std;
int main(void) {
bool hasDigit = false;
char passCode[50] = "";
int valid = 0;
strcpy(passCode, "abc");
/* Your solution goes here */
int i=0;
while(passCode[i])
{
if(passCode[i]>='0' && passCode[i]<'9')
{
hasDigit=true;
}
i++;
}
if (hasDigit) {
printf("Has a digit. ");
}
else {
printf("Has no digit. ");
}
return 0;
}
OUTPUT:
Has no digit.
2. Replace any space ' ' by '_' in 2-character string passCode. Sample output for the given
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char passCode[3] = "";
strcpy(passCode, "1 ");
/* Your solution goes here */
int i=0;
while(passCode[i])
{
if(passCode[i]==' ')
{
passCode[i]='_';
}
i++;
}
printf("%s ", passCode);
return 0;
}
OUTPUT:
1_
3. Write an expression that will cause the following code to print "Equal" if the value of sensorReading is "close enough" to targetValue. Otherwise, print "Not equal".
#include <stdio.h>
#include <math.h>
int main(void) {
double targetValue = 0.3333;
double sensorReading = 0.0;
double epsilon = 0.000000001;
sensorReading = 1.0/3.0;
if (abs(targetValue - sensorReading) < epsilon) {
printf("Equal ");
}
else {
printf("Not equal ");
}
return 0;
}
OUTPUT:
Not equal
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.